text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing.Ast;

namespace Microsoft.PythonTools.Analysis.Values {
    internal class FunctionInfo : AnalysisValue, IReferenceableContainer {
        private Dictionary<AnalysisValue, IAnalysisSet> _methods;
        private Dictionary<string, VariableDef> _functionAttrs;
        private readonly FunctionDefinition _functionDefinition;
        private readonly FunctionAnalysisUnit _analysisUnit;
        private readonly ProjectEntry _projectEntry;
        public bool IsStatic;
        public bool IsClassMethod;
        public bool IsProperty;
        private ReferenceDict _references;
        private readonly int _declVersion;
        private int _callDepthLimit;
        private int _callsSinceLimitChange;

        internal CallChainSet<FunctionAnalysisUnit> _allCalls;

        internal FunctionInfo(FunctionDefinition node, AnalysisUnit declUnit, InterpreterScope declScope) {
            _projectEntry = declUnit.ProjectEntry;
            _functionDefinition = node;
            _declVersion = declUnit.ProjectEntry.AnalysisVersion;

            if (_functionDefinition.Name == "__new__") {
                IsClassMethod = true;
            }

            object value;
            if (!ProjectEntry.Properties.TryGetValue(AnalysisLimits.CallDepthKey, out value) ||
                (_callDepthLimit = (value as int?) ?? -1) < 0) {
                _callDepthLimit = declUnit.ProjectState.Limits.CallDepth;
            }

            _analysisUnit = new FunctionAnalysisUnit(this, declUnit, declScope, _projectEntry);
        }

        public ProjectEntry ProjectEntry {
            get {
                return _projectEntry;
            }
        }

        public override IPythonProjectEntry DeclaringModule {
            get {
                return _analysisUnit.ProjectEntry;
            }
        }

        public FunctionDefinition FunctionDefinition {
            get {
                return _functionDefinition;
            }
        }

        public override AnalysisUnit AnalysisUnit {
            get {
                return _analysisUnit;
            }
        }

        public override int DeclaringVersion {
            get {
                return _declVersion;
            }
        }

        public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) {
            var callArgs = ArgumentSet.FromArgs(FunctionDefinition, unit, args, keywordArgNames);

            FunctionAnalysisUnit calledUnit;
            bool updateArguments = true;

            if (callArgs.Count == 0 ||
                (ProjectState.Limits.UnifyCallsToNew && Name == "__new__") ||
                _callDepthLimit == 0) {
                calledUnit = (FunctionAnalysisUnit)AnalysisUnit;
            } else {
                if (_allCalls == null) {
                    _allCalls = new CallChainSet<FunctionAnalysisUnit>();
                }

                var chain = new CallChain(node, unit, _callDepthLimit);
                if (!_allCalls.TryGetValue(unit.ProjectEntry, chain, _callDepthLimit, out calledUnit)) {
                    if (unit.ForEval) {
                        // Call expressions that weren't analyzed get the union result
                        // of all calls to this function.
                        var res = AnalysisSet.Empty;
                        foreach (var call in _allCalls.Values) {
                            res = res.Union(call.ReturnValue.TypesNoCopy);
                        }
                        return res;
                    } else {
                        _callsSinceLimitChange += 1;
                        if (_callsSinceLimitChange >= ProjectState.Limits.DecreaseCallDepth && _callDepthLimit > 1) {
                            _callDepthLimit -= 1;
                            _callsSinceLimitChange = 0;
                            AnalysisLog.ReduceCallDepth(this, _allCalls.Count, _callDepthLimit);

                            _allCalls.Clear();
                            chain = chain.Trim(_callDepthLimit);
                        }
                        calledUnit = new FunctionAnalysisUnit((FunctionAnalysisUnit)AnalysisUnit, chain, callArgs);
                        _allCalls.Add(unit.ProjectEntry, chain, calledUnit);
                        updateArguments = false;
                    }
                }
            }

            if (updateArguments && calledUnit.UpdateParameters(callArgs)) {
                AnalysisLog.UpdateUnit(calledUnit);
            }
            if (keywordArgNames != null && keywordArgNames.Any()) {
                calledUnit.AddNamedParameterReferences(unit, keywordArgNames);
            }

            calledUnit.ReturnValue.AddDependency(unit);
            return calledUnit.ReturnValue.Types;
        }

        public override string Name {
            get {
                return FunctionDefinition.Name;
            }
        }

        internal void AddParameterString(StringBuilder result) {
            for (int i = 0; i < FunctionDefinition.Parameters.Count; i++) {
                if (i != 0) {
                    result.Append(", ");
                }
                var p = FunctionDefinition.Parameters[i];

                var name = MakeParameterName(p);
                var defaultValue = GetDefaultValue(ProjectState, p, DeclaringModule.Tree);

                result.Append(name);
                if (!String.IsNullOrWhiteSpace(defaultValue)) {
                    result.Append(" = ");
                    result.Append(defaultValue);
                }
            }
        }

        internal static void AddReturnTypeString(StringBuilder result, Func<int, IAnalysisSet> getReturnValue) {
            for (int strength = 0; strength <= UnionComparer.MAX_STRENGTH; ++strength) {
                var retTypes = getReturnValue(strength);
                if (retTypes.Count == 0) {
                    break;
                }
                if (retTypes.Count <= 10) {
                    var seenNames = new HashSet<string>();
                    var addDots = false;
                    var descriptions = new List<string>();
                    foreach (var av in retTypes) {
                        if (av == null) {
                            continue;
                        }

                        if (av.Push()) {
                            try {
                                var desc = av.ShortDescription;
                                if (!string.IsNullOrWhiteSpace(desc) && seenNames.Add(desc)) {
                                    descriptions.Add(desc.Replace("\r\n", "\n").Replace("\n", "\r\n    "));
                                }
                            } finally {
                                av.Pop();
                            }
                        } else {
                            addDots = true;
                        }
                    }

                    var first = true;
                    descriptions.Sort();
                    foreach (var desc in descriptions) {
                        if (first) {
                            result.Append(" -> ");
                            first = false;
                        } else {
                            result.Append(", ");
                        }
                        result.Append(desc);
                    }

                    if (addDots) {
                        result.Append("...");
                    }
                    break;
                }
            }
        }

        internal static void AddDocumentationString(StringBuilder result, string documentation) {
            if (!String.IsNullOrEmpty(documentation)) {
                result.AppendLine();
                result.Append(documentation);
            }
        }

        internal void AddQualifiedLocationString(StringBuilder result) {
            var qualifiedNameParts = new Stack<string>();
            for (var item = FunctionDefinition.Parent; item is FunctionDefinition || item is ClassDefinition; item = item.Parent) {
                if (!string.IsNullOrEmpty(item.Name)) {
                    qualifiedNameParts.Push(item.Name);
                }
            }
            if (qualifiedNameParts.Count > 0) {
                result.AppendLine();
                result.Append("declared in ");
                result.Append(string.Join(".", qualifiedNameParts));
            }
        }

        public override string Description {
            get {
                var result = new StringBuilder();
                if (FunctionDefinition.IsLambda) {
                    result.Append("lambda ");
                    AddParameterString(result);
                    result.Append(": ");

                    if (FunctionDefinition.IsGenerator) {
                        var lambdaExpr = ((ExpressionStatement)FunctionDefinition.Body).Expression;
                        Expression yieldExpr = null;
                        YieldExpression ye;
                        YieldFromExpression yfe;
                        if ((ye = lambdaExpr as YieldExpression) != null) {
                            yieldExpr = ye.Expression;
                        } else if ((yfe = lambdaExpr as YieldFromExpression) != null) {
                            yieldExpr = yfe.Expression;
                        } else {
                            Debug.Assert(false, "lambdaExpr is not YieldExpression or YieldFromExpression");
                        }
                        result.Append(yieldExpr.ToCodeString(DeclaringModule.Tree));
                    } else {
                        result.Append(((ReturnStatement)FunctionDefinition.Body).Expression.ToCodeString(DeclaringModule.Tree));
                    }
                } else {
                    if (FunctionDefinition.IsCoroutine) {
                        result.Append("async ");
                    }
                    result.Append("def ");
                    result.Append(FunctionDefinition.Name);
                    result.Append("(");
                    AddParameterString(result);
                    result.Append(")");
                }

                AddReturnTypeString(result, GetReturnValue);
                AddDocumentationString(result, Documentation);
                AddQualifiedLocationString(result);

                return result.ToString();
            }
        }

        public override IAnalysisSet GetDescriptor(Node node, AnalysisValue instance, AnalysisValue context, AnalysisUnit unit) {
            if ((instance == ProjectState._noneInst && !IsClassMethod) || IsStatic) {
                return SelfSet;
            }
            if (_methods == null) {
                _methods = new Dictionary<AnalysisValue, IAnalysisSet>();
            }

            IAnalysisSet result;
            if (!_methods.TryGetValue(instance, out result) || result == null) {
                if (IsClassMethod) {
                    _methods[instance] = result = new BoundMethodInfo(this, context).SelfSet;
                } else {
                    _methods[instance] = result = new BoundMethodInfo(this, instance).SelfSet;
                }
            }

            if (IsProperty) {
                return result.Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames);
            }

            return result;
        }

        public override string Documentation {
            get {
                if (FunctionDefinition.Body != null) {
                    return FunctionDefinition.Body.Documentation.TrimDocumentation();
                }
                return "";
            }
        }

        public override PythonMemberType MemberType {
            get {
                return IsProperty ? PythonMemberType.Property : PythonMemberType.Function;
            }
        }

        public override string ToString() {
            return "FunctionInfo " + _analysisUnit.FullName + " (" + _declVersion + ")";
        }

        public override IEnumerable<LocationInfo> Locations {
            get {
                var start = FunctionDefinition.NameExpression.GetStart(FunctionDefinition.GlobalParent);
                return new[] { new LocationInfo(
                    ProjectEntry,
                    start.Line,
                    start.Column)
                };
            }
        }

        private class StringArrayComparer : IEqualityComparer<string[]> {
            private IEqualityComparer<string> _comparer;

            public StringArrayComparer() {
                _comparer = StringComparer.Ordinal;
            }

            public StringArrayComparer(IEqualityComparer<string> comparer) {
                _comparer = comparer;
            }

            public bool Equals(string[] x, string[] y) {
                if (x == null || y == null) {
                    return x == null && y == null;
                }

                if (x.Length != y.Length) {
                    return false;
                }

                for (int i = 0; i < x.Length; ++i) {
                    if (!_comparer.Equals(x[i], y[i])) {
                        return false;
                    }
                }
                return true;
            }

            public int GetHashCode(string[] obj) {
                if (obj == null) {
                    return 0;
                }
                int hc = 261563 ^ obj.Length;
                foreach (var p in obj) {
                    hc ^= _comparer.GetHashCode(p);
                }
                return hc;
            }
        }

        public override IEnumerable<OverloadResult> Overloads {
            get {
                var references = new Dictionary<string[], IEnumerable<AnalysisVariable>[]>(new StringArrayComparer());

                var units = new HashSet<AnalysisUnit>();
                units.Add(AnalysisUnit);
                if (_allCalls != null) {
                    units.UnionWith(_allCalls.Values);
                }

                foreach (var unit in units) {
                    var vars = FunctionDefinition.Parameters.Select(p => {
                        VariableDef param;
                        if (unit.Scope.TryGetVariable(p.Name, out param)) {
                            return param;
                        }
                        return null;
                    }).ToArray();

                    var parameters = vars
                        .Select(p => string.Join(", ", p.Types.Select(av => av.ShortDescription).OrderBy(s => s).Distinct()))
                        .ToArray();

                    IEnumerable<AnalysisVariable>[] refs;
                    if (references.TryGetValue(parameters, out refs)) {
                        refs = refs.Zip(vars, (r, v) => r.Concat(ProjectEntry.Analysis.ToVariables(v))).ToArray();
                    } else {
                        refs = vars.Select(v => ProjectEntry.Analysis.ToVariables(v)).ToArray();
                    }
                    references[parameters] = refs;
                }

                foreach (var keyValue in references) {
                    yield return new SimpleOverloadResult(
                        FunctionDefinition.Parameters.Select((p, i) => {
                            var name = MakeParameterName(p);
                            var defaultValue = GetDefaultValue(ProjectState, p, DeclaringModule.Tree);
                            var type = keyValue.Key[i];
                            var refs = keyValue.Value[i];
                            return new ParameterResult(name, string.Empty, type, false, refs, defaultValue);
                        }).ToArray(),
                        FunctionDefinition.Name,
                        Documentation
                    );
                }
            }
        }

        internal static string MakeParameterName(Parameter curParam) {
            string name = curParam.Name;
            if (curParam.IsDictionary) {
                name = "**" + name;
            } else if (curParam.IsList) {
                name = "*" + curParam.Name;
            }

            return name;
        }

        internal static string GetDefaultValue(PythonAnalyzer state, Parameter curParam, PythonAst tree) {
            if (curParam.DefaultValue != null) {
                // TODO: Support all possible expressions for default values, we should
                // probably have a PythonAst walker for expressions or we should add ToCodeString()
                // onto Python ASTs so they can round trip
                ConstantExpression defaultValue = curParam.DefaultValue as ConstantExpression;
                if (defaultValue != null) {
                    return defaultValue.GetConstantRepr(state.LanguageVersion);
                } else {

                    NameExpression nameExpr = curParam.DefaultValue as NameExpression;
                    if (nameExpr != null) {
                        return nameExpr.Name;
                    } else {

                        DictionaryExpression dict = curParam.DefaultValue as DictionaryExpression;
                        if (dict != null) {
                            if (dict.Items.Count == 0) {
                                return "{}";
                            } else {
                                return "{...}";
                            }
                        } else {

                            ListExpression list = curParam.DefaultValue as ListExpression;
                            if (list != null) {
                                if (list.Items.Count == 0) {
                                    return "[]";
                                } else {
                                    return "[...]";
                                }
                            } else {

                                TupleExpression tuple = curParam.DefaultValue as TupleExpression;
                                if (tuple != null) {
                                    if (tuple.Items.Count == 0) {
                                        return "()";
                                    } else {
                                        return "(...)";
                                    }
                                } else {
                                    return curParam.DefaultValue.ToCodeString(tree);
                                }
                            }
                        }
                    }
                }
            }
            return null;
        }

        public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) {
            if (_functionAttrs == null) {
                _functionAttrs = new Dictionary<string, VariableDef>();
            }

            VariableDef varRef;
            if (!_functionAttrs.TryGetValue(name, out varRef)) {
                _functionAttrs[name] = varRef = new VariableDef();
            }
            varRef.AddAssignment(node, unit);
            varRef.AddTypes(unit, value);
        }

        public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) {
            // Must unconditionally call the base implementation of GetMember
            var ignored = base.GetMember(node, unit, name);

            VariableDef tmp;
            if (_functionAttrs != null && _functionAttrs.TryGetValue(name, out tmp)) {
                tmp.AddDependency(unit);
                tmp.AddReference(node, unit);

                return tmp.Types;
            }
            // TODO: Create one and add a dependency
            if (name == "__name__") {
                return unit.ProjectState.GetConstant(FunctionDefinition.Name);
            }

            return ProjectState.ClassInfos[BuiltinTypeId.Function].GetMember(node, unit, name);
        }

        public override IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext) {
            if (_functionAttrs == null || _functionAttrs.Count == 0) {
                return ProjectState.ClassInfos[BuiltinTypeId.Function].GetAllMembers(moduleContext);
            }

            var res = new Dictionary<string, IAnalysisSet>(ProjectState.ClassInfos[BuiltinTypeId.Function].Instance.GetAllMembers(moduleContext));
            foreach (var variable in _functionAttrs) {
                IAnalysisSet existing;
                if (!res.TryGetValue(variable.Key, out existing)) {
                    res[variable.Key] = variable.Value.Types;
                } else {
                    res[variable.Key] = existing.Union(variable.Value.TypesNoCopy);
                }
            }
            return res;
        }

        // Returns False if no more parameters can be updated for this unit.
        private bool UpdateSingleDefaultParameter(AnalysisUnit unit, InterpreterScope scope, int index, IParameterInfo info) {
            if (index >= FunctionDefinition.Parameters.Count) {
                return false;
            }
            VariableDef param;
            var name = FunctionDefinition.Parameters[index].Name;
            if (scope.TryGetVariable(name, out param)) {
                var av = ProjectState.GetAnalysisSetFromObjects(info.ParameterTypes);

                if ((info.IsParamArray && !(param is ListParameterVariableDef)) ||
                    (info.IsKeywordDict && !(param is DictParameterVariableDef))) {
                    return false;
                }

                param.AddTypes(unit, av);
            }

            return true;
        }

        internal void UpdateDefaultParameters(AnalysisUnit unit, IEnumerable<IParameterInfo> parameters) {
            var finishedScopes = new HashSet<InterpreterScope>();
            var scopeSet = new HashSet<InterpreterScope>();
            scopeSet.Add(AnalysisUnit.Scope);
            if (_allCalls != null) {
                scopeSet.UnionWith(_allCalls.Values.Select(au => au.Scope));
            }

            int index = 0;
            foreach (var p in parameters) {
                foreach (var scope in scopeSet) {
                    if (finishedScopes.Contains(scope)) {
                        continue;
                    }

                    if (!UpdateSingleDefaultParameter(unit, scope, index, p)) {
                        finishedScopes.Add(scope);
                    }
                }
                index += 1;
            }
        }

        internal IAnalysisSet[] GetParameterTypes(int unionStrength = 0) {
            var result = new IAnalysisSet[FunctionDefinition.Parameters.Count];
            var units = new HashSet<AnalysisUnit>();
            units.Add(AnalysisUnit);
            if (_allCalls != null) {
                units.UnionWith(_allCalls.Values);
            }

            for (int i = 0; i < result.Length; ++i) {
                result[i] = (unionStrength >= 0 && unionStrength <= UnionComparer.MAX_STRENGTH)
                    ? AnalysisSet.CreateUnion(UnionComparer.Instances[unionStrength])
                    : AnalysisSet.Empty;

                VariableDef param;
                foreach (var unit in units) {
                    if (unit != null && unit.Scope != null && unit.Scope.TryGetVariable(FunctionDefinition.Parameters[i].Name, out param)) {
                        result[i] = result[i].Union(param.TypesNoCopy);
                    }
                }
            }

            return result;
        }

        internal IAnalysisSet GetReturnValue(int unionStrength = 0) {
            var result = (unionStrength >= 0 && unionStrength <= UnionComparer.MAX_STRENGTH)
                ? AnalysisSet.CreateUnion(UnionComparer.Instances[unionStrength])
                : AnalysisSet.Empty;

            var units = new HashSet<AnalysisUnit>();
            units.Add(AnalysisUnit);
            if (_allCalls != null) {
                units.UnionWith(_allCalls.Values);
            }

            result = result.UnionAll(units.OfType<FunctionAnalysisUnit>().Select(unit => unit.ReturnValue.TypesNoCopy));

            return result;
        }

        public PythonAnalyzer ProjectState { get { return ProjectEntry.ProjectState; } }

        internal override void AddReference(Node node, AnalysisUnit unit) {
            if (!unit.ForEval) {
                if (_references == null) {
                    _references = new ReferenceDict();
                }
                _references.GetReferences(unit.DeclaringModule.ProjectEntry).AddReference(new EncodedLocation(unit.Tree, node));
            }
        }

        internal override IEnumerable<LocationInfo> References {
            get {
                if (_references != null) {
                    return _references.AllReferences;
                }
                return new LocationInfo[0];
            }
        }

        public override IPythonType PythonType {
            get { return ProjectState.Types[BuiltinTypeId.Function]; }
        }

        internal override bool IsOfType(IAnalysisSet klass) {
            return klass.Contains(ProjectState.ClassInfos[BuiltinTypeId.Function]);
        }

        internal override bool UnionEquals(AnalysisValue av, int strength) {
            if (strength >= MergeStrength.ToObject) {
                return av is FunctionInfo || av is BuiltinFunctionInfo || av == ProjectState.ClassInfos[BuiltinTypeId.Function].Instance;
            }
            return base.UnionEquals(av, strength);
        }

        internal override int UnionHashCode(int strength) {
            if (strength >= MergeStrength.ToObject) {
                return ProjectState.ClassInfos[BuiltinTypeId.Function].Instance.UnionHashCode(strength);
            }
            return base.UnionHashCode(strength);
        }

        internal override AnalysisValue UnionMergeTypes(AnalysisValue av, int strength) {
            if (strength >= MergeStrength.ToObject) {
                return ProjectState.ClassInfos[BuiltinTypeId.Function].Instance;
            }
            return base.UnionMergeTypes(av, strength);
        }

        #region IReferenceableContainer Members

        public IEnumerable<IReferenceable> GetDefinitions(string name) {
            VariableDef def;
            if (_functionAttrs != null && _functionAttrs.TryGetValue(name, out def)) {
                return new IReferenceable[] { def };
            }
            return new IReferenceable[0];
        }

        #endregion

    }
}


text:
namespace Krkadoni.Enigma.Enums
{
    public enum ReloadSettingsType
    {
        All = 0,
        Services = 1,
        Bouquets = 2
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * ServicePrincipal
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    sf_sandbox
 * @subpackage model
 * @author     gyufi@sztaki.hu
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class ServicePrincipal extends BaseServicePrincipal
{
}


text:
define([
    'lib/EventBus'
], function(
    EventBus
) {
    'use strict';

    return new EventBus();
});


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('suggest', [
  'ngRoute',
  'suggestionFilters',
  'suggestions',
  'myApp.view2',
])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/suggestions'});
}])
;


text:
namespace MoviesLibrary.Services.Data
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using MoviesLibrary.Models;
    using MoviesLibrary.Services.Data.Contracts;

    public class GenresService : IGenresService
    {
        public IList<string> GetAll()
        {
            var genres = Enum.GetNames(typeof(Genre)).ToList();

            return genres;
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res/com.indigo_lab.android.opensynth"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".OpenSynthActivity" >

    <!-- controller area -->
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        />
    <com.google.synthesizer.android.widgets.piano.PianoView
        android:id="@+id/piano"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        app:octaves="2"
        app:first_octave="4"/>
</LinearLayout>


text:
<!DOCTYPE html>

<title>Create Appointment</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link
	href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.4/css/bootstrap.min.css"
	th:href="@{/webjars/bootstrap/3.3.4/css/bootstrap.min.css}"
	rel="stylesheet" media="screen" />
<link
	href="http://cdn.jsdelivr.net/webjars/jquery-ui/1.11.4/jquery-ui.min.css"
	th:href="@{/webjars/jquery-ui/1.11.4/jquery-ui.min.css}"
	rel="stylesheet" media="screen" />

Home

Appointment

Create Appointment

				<form method="POST" action="/appointment" id="createForm">

						Patient name <input type="text"
							class="form-control" id="patientName" name="patientName"
							placeHolder="Patient Name" th:value="${appointment.patientName}"/>

						Doctor name <input type="text"
							class="form-control" id="doctorName" name="doctorName"
							placeHolder="Doctor Name" th:value="${appointment.doctorName}"/>

						Appointment Date
							<input type="text" id="date" name="date" placeHolder="dd/mm/yyyy" th:value="${appointment.date}"/>

						Details <input type="text"
							class="form-control" id="details" name="details"
							placeHolder="Other relevant details" th:value="${appointment.details}"/>

<button type="submit" class="btn btn-default"
										onclick="/appointment_list">Cancel</button>

<button type="submit" class="btn btn-default">Save
										appointment</button>

 <input type="hidden" class="form-control" id="id" value="0" th:value="${appointment.id}"/>
				</form>


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.engine.impl.cmd;

import java.io.Serializable;
import java.util.List;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.ProcessDefinitionQueryImpl;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.persistence.entity.DeploymentEntity;
import org.flowable.engine.impl.repository.AddAsNewDeploymentMergeStrategy;
import org.flowable.engine.impl.repository.AddAsOldDeploymentMergeStrategy;
import org.flowable.engine.impl.repository.MergeByDateDeploymentMergeStrategy;
import org.flowable.engine.impl.repository.VerifyDeploymentMergeStrategy;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.Flowable5Util;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.DeploymentMergeStrategy;
import org.flowable.engine.repository.MergeMode;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.job.service.JobService;

/**
 * @author Joram Barrez
 */
public class ChangeDeploymentTenantIdCmd implements Command<Void>, Serializable {

    private static final long serialVersionUID = 1L;

    protected String deploymentId;
    protected String newTenantId;
    protected DeploymentMergeStrategy deploymentMergeStrategy;

    public ChangeDeploymentTenantIdCmd(String deploymentId, String newTenantId) {
        this(deploymentId, newTenantId, MergeMode.VERIFY);
    }

    public ChangeDeploymentTenantIdCmd(String deploymentId, String newTenantId, MergeMode mergeMode) {
        this.deploymentId = deploymentId;
        this.newTenantId = newTenantId;
        switch (mergeMode) {
            case VERIFY:
                deploymentMergeStrategy = new VerifyDeploymentMergeStrategy();
                break;
            case AS_NEW:
                deploymentMergeStrategy = new AddAsNewDeploymentMergeStrategy();
                break;
            case AS_OLD:
                deploymentMergeStrategy = new AddAsOldDeploymentMergeStrategy();
                break;
            case BY_DATE:
                deploymentMergeStrategy = new MergeByDateDeploymentMergeStrategy();
                break;
            default:
                throw new FlowableException("Merge mode '" + mergeMode + "' not found.");
        }
    }

    public ChangeDeploymentTenantIdCmd(String deploymentId, String newTenantId, DeploymentMergeStrategy deploymentMergeStrategy) {
        this.deploymentId = deploymentId;
        this.newTenantId = newTenantId;
        this.deploymentMergeStrategy = deploymentMergeStrategy;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        if (deploymentId == null) {
            throw new FlowableIllegalArgumentException("deploymentId is null");
        }

        // Update all entities
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        DeploymentEntity deployment = processEngineConfiguration.getDeploymentEntityManager().findById(deploymentId);
        if (deployment == null) {
            throw new FlowableObjectNotFoundException("Could not find deployment with id " + deploymentId, Deployment.class);
        }

        if (Flowable5Util.isFlowable5Deployment(deployment, commandContext)) {
            processEngineConfiguration.getFlowable5CompatibilityHandler().changeDeploymentTenantId(deploymentId, newTenantId);
            return null;
        }

        deploymentMergeStrategy.prepareMerge(commandContext, deploymentId, newTenantId);
        String oldTenantId = deployment.getTenantId();
        deployment.setTenantId(newTenantId);

        // Doing process instances, executions and tasks with direct SQL updates
        // (otherwise would not be performant)
        processEngineConfiguration.getProcessDefinitionEntityManager().updateProcessDefinitionTenantIdForDeployment(deploymentId, newTenantId);
        processEngineConfiguration.getExecutionEntityManager().updateExecutionTenantIdForDeployment(deploymentId, newTenantId);
        processEngineConfiguration.getTaskServiceConfiguration().getTaskService().updateTaskTenantIdForDeployment(deploymentId, newTenantId);
        JobService jobService = processEngineConfiguration.getJobServiceConfiguration().getJobService();
        jobService.updateAllJobTypesTenantIdForDeployment(deploymentId, newTenantId);
        processEngineConfiguration.getEventSubscriptionServiceConfiguration().getEventSubscriptionService().updateEventSubscriptionTenantId(oldTenantId, newTenantId);

        deploymentMergeStrategy.finalizeMerge(commandContext, deploymentId, newTenantId);

        // Doing process definitions in memory, cause we need to clear the process definition cache
        List<ProcessDefinition> processDefinitions = new ProcessDefinitionQueryImpl().deploymentId(deploymentId).list();
        for (ProcessDefinition processDefinition : processDefinitions) {
            processEngineConfiguration.getProcessDefinitionCache().remove(processDefinition.getId());
        }

        // Clear process definition cache
        processEngineConfiguration.getProcessDefinitionCache().clear();

        return null;

    }

}


text:
<?php

class DemoTest extends TestCase
{

    public function testSomethingIsTrue()
    {
        $this->assertTrue(true);
    }
}


text:
from lino.projects.std.settings import *
SITE = Site(globals(), 'lino_book.projects.quantityfield')


text:
package it.conteit.scoresmanager.control;

public class NotInitializedException extends RuntimeException {
	private static final long serialVersionUID = -2004936359765172295L;

	public NotInitializedException(String message){
		super(message);
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package freestore;

import freestore.messages.FreeStoreMessage;
import freestore.messages.FreeStoreMessageType;
import freestore.messages.InstallSeqMessage;
import freestore.messages.RECVMessage;
import freestore.messages.StateUpdateMessage;
import freestore.viewgenerators.LiveViewGenerator;
import freestore.viewgenerators.SafeViewGenerator;
import freestore.viewgenerators.ViewGenerator;
import freestore.viewgenerators.ViewGeneratorType;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import quorum.communication.MessageType;
import quorum.communication.QuorumMessage;
import quorum.communication.system.CommunicationSystemClientSide;
import quorum.communication.system.CommunicationSystemClientSideFactory;
import quorum.communication.system.ReplyReceiver;
import quorum.core.QuorumReplica;
import quorum.view.ClientViewController;
import quorum.view.View;

/**
 *
 * @author eduardo
 */
public abstract class FreeStoreReplica extends QuorumReplica implements ReplyReceiver {

    private List<RECVMessage> recv = new LinkedList<RECVMessage>();

    private CommunicationSystemClientSide cs;

    ///FALTA LIMPAR DADOS ANTIGOS DESTAS ESTRUTURAS
    private Map<String, List<StateUpdateMessage>> stateMsgs = new HashMap<String, List<StateUpdateMessage>>();
    private Map<String, List<FreeStoreMessage>> viewUpdatedMsgs = new HashMap<String, List<FreeStoreMessage>>();
    private Map<String, ViewGenerator> vg = new HashMap<String, ViewGenerator>();
    private List<InstallSeqMessage> installed = new LinkedList<InstallSeqMessage>();
    ///////////////////////////////////////////////////

    private List<FreeStoreMessage> responses = new LinkedList<FreeStoreMessage>();

    private boolean waitingRecConfirm = false;

    private final ReentrantLock canExecuteLock = new ReentrantLock();
    private final ReentrantLock replyLock = new ReentrantLock();
    private final ReentrantLock recvLock = new ReentrantLock();

    private Semaphore clientOperationLock = new Semaphore(1);
    private boolean alreadyLocked = false;
    private Semaphore joinLeave = new Semaphore(0);

    //Queues used to store requests to be processed by a pool of threads
    private LinkedBlockingQueue<FreeStoreMessage> reconfigQueue = new LinkedBlockingQueue<FreeStoreMessage>();
    private LinkedBlockingQueue<QuorumMessage> clientOperationsQueue = new LinkedBlockingQueue<QuorumMessage>();

    private ViewGeneratorType vgType;

    public FreeStoreReplica(int id, ViewGeneratorType type) {
        this(id, "", 10000, type);
    }

    public FreeStoreReplica(int id, long recPeriod, ViewGeneratorType type) {
        this(id, "", recPeriod, type);
    }

    public FreeStoreReplica(int id, String configHome, long recPeriod, ViewGeneratorType type) {
        super(id, configHome);
        if (!configHome.equals("")) {
            this.cs = CommunicationSystemClientSideFactory.getCommunicationSystemClientSide(this.id, new ClientViewController(id));
        } else {
            this.cs = CommunicationSystemClientSideFactory.getCommunicationSystemClientSide(this.id, new ClientViewController(id, configHome));
        }
        this.cs.setReplyReceiver(this);

        this.vgType = type;

        int t = Runtime.getRuntime().availableProcessors();
        for (int i = 0; i < t; i++) {
            new ReconfigurationWorker(reconfigQueue).start();
            new ClientOperationWorker(clientOperationsQueue).start();
        }
        if (!this.SVController.getCurrentView().isMember(id)) {
            try {
                this.clientOperationLock.acquire(); //disable the execution of client operations
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            join();
            do {
                try {
                    this.joinLeave.acquire(); //wait until the reconfiguration occurs
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            } while (!this.SVController.getCurrentView().isMember(id));
        }
        (new Timer()).scheduleAtFixedRate(new TimerTask() {
            public void run() {
                startReconfiguration();
            }
        }, recPeriod, recPeriod);

        /*(new Timer()).scheduleAtFixedRate(new TimerTask() {
         public void run() {
         if(id != 1){
         System.out.println("vai enviar o leave");
         leave();
          }
         }
         }, recPeriod*2, recPeriod*50);*/
    }

    public abstract int getTimestamp();

    public abstract Object getValue();

    public abstract void updateState(int timestamp, Object value);

    public abstract QuorumMessage executeProtocolRequest(QuorumMessage msg);

    /**
     * The join method (used in the constructor when a replica is not in the
     * current view)
     */
    public void join() {
        String host = "";
        int port = 12000;
        try {
            host = InetAddress.getLocalHost().getHostAddress();
            boolean free = false;
            ServerSocket ss = null;
            do {
                try {
                    ss = new ServerSocket(port);
                    free = true;
                } catch (IOException ex) {
                    port++;
                } finally {
                    try {
                        if (ss != null) {
                            ss.close();
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            } while (!free);
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
        this.init(host, port);
        waitingRecConfirm = true;
        do {
            QuorumMessage joinRequest = new QuorumMessage(MessageType.RECONFIGURATION_MESSAGE,
                    new RECVMessage(new InetSocketAddress(host, port),
                            FreeStoreMessageType.RECONFIG, id, this.getSVController().getCurrentView()), id);
            responses.clear();
            multicast(joinRequest, this.cs.getController().getCurrentView().getMembership(), this.cs.getController().getCurrentView());
            try {
                if (!this.joinLeave.tryAcquire(5000, TimeUnit.MILLISECONDS)) {
                    System.out.println("TIMEOUT FOR THE JOIN REQUEST");
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        } while (responses.size() < this.cs.getController().getCurrentView().getQuorum());
    }

    /**
     * The leave method
     */
    public void leave() {
        waitingRecConfirm = true;
        do {
            QuorumMessage leaveRequest = new QuorumMessage(MessageType.RECONFIGURATION_MESSAGE,
                    new RECVMessage(null, FreeStoreMessageType.RECONFIG, -id, this.getSVController().getCurrentView()), id);
            responses.clear();
            multicast(leaveRequest, this.cs.getController().getCurrentView().getMembership(), this.cs.getController().getCurrentView());
            try {
                if (!this.joinLeave.tryAcquire(5000, TimeUnit.MILLISECONDS)) {
                    System.out.println("TIMEOUT FOR THE LEAVE REQUEST");
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        } while (responses.size() < cs.getController().getCurrentView().getQuorum());
    }

    /**
     * Called by the netty system to execute a client operation
     *
     * @param msg
     * @return
     */
    @Override
    public QuorumMessage executeRequest(QuorumMessage msg) {
        try {
            this.clientOperationsQueue.put(msg);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * Called by the netty system to execute a reconfiguration request
     *
     * @param msg
     * @return
     */
    @Override
    public QuorumMessage executeReconfigurationMessage(QuorumMessage msg) {//Processamento de Mensagens de Reconfiguração do FreeStore

        FreeStoreMessage recMsg = (FreeStoreMessage) msg.getMsg();
        if (recMsg.type == FreeStoreMessageType.RECONFIG) {
            //System.out.println("recebeu reconfig");
            if (this.getSVController().getCurrentView().equalsByHash(recMsg.view.getHash())) {//view up-to-date
                // System.out.println("vai pegar o lock");
                recvLock.lock();
                // System.out.println("passou pelo lock");
                if (!this.getSVController().getCurrentView().containsUpdate(Integer.parseInt(recMsg.getValue().toString()))) {

                    if (!recv.contains((RECVMessage) recMsg)) {
                        // System.out.println("Adicionou "+recMsg.value);
                        recv.add((RECVMessage) recMsg);
                    }//else{
                    // System.out.println("Não adicionou "+recMsg.value);
                    //}
                }//else{
                // System.out.println("Não adicionou pq current view contém update "+recMsg.value);
                // }
                recvLock.unlock();
                return new QuorumMessage(MessageType.RECONFIGURATION_MESSAGE,
                        new FreeStoreMessage(FreeStoreMessageType.REC_CONFIRM, null, this.getSVController().getCurrentView()), id);
            } else {//view outdated
                //recvLock.unlock();
                // System.out.println("visão desatualizada");
                return new QuorumMessage(MessageType.RECONFIGURATION_MESSAGE,
                        new FreeStoreMessage(FreeStoreMessageType.REC_CONFIRM, this.getSVController().getCurrentView(), null), id);
            }
        } else {
            try {
                //System.out.println("recebeu uma msg do tipo " + msg.getType() + " from: " + msg.getSender());
                this.reconfigQueue.put(recMsg);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            return null;
        }
    }

    /**
     * Called by the client netty system to inform that a reply (from a
     * join/leave request) was received
     *
     * @param reply
     */
    @Override
    public void replyReceived(QuorumMessage reply) {//Processamento de respostas para Join e Leave
        replyLock.lock();
        FreeStoreMessage recMsg = (FreeStoreMessage) reply.getMsg();
        if (recMsg.type == FreeStoreMessageType.REC_CONFIRM && waitingRecConfirm) {//conta mais um rec confirm como nas operações de clientes
            if (recMsg.getValue() != null) { //view is outdated
                View v = (View) recMsg.getValue();
                this.SVController.reconfigureTo(v);
                cs.getController().reconfigureTo(v);
                responses.clear(); //sinaliza a reexecução da fase
                this.joinLeave.release();
            } else { // view is the most up-to-date
                responses.add(recMsg);
                if (responses.size() == cs.getController().getCurrentView().getQuorum()) {
                    waitingRecConfirm = false;
                    this.joinLeave.release();
                }
            }
        }
        replyLock.unlock();
    }

    /**
     * Periodically, starts a reconfiguration periodically if there are updates
     * to be processed
     */
    private void startReconfiguration() {
        recvLock.lock();
        if (recv.size() > 0) { //começar uma reconfiguração para current view
            //System.out.println("Vai iniciar uma reconfiguração: " + recv.get(0));
            int[] updates = new int[getSVController().getCurrentView().getUpdates().length + recv.size()];
            for (int i = 0; i < updates.length; i++) {
                if (i < getSVController().getCurrentView().getUpdates().length) {
                    updates[i] = getSVController().getCurrentView().getUpdates()[i];
                } else {
                    updates[i] = Integer.parseInt(recv.get(i - getSVController().getCurrentView().getUpdates().length).value.toString());
                }
            }
            View vp = new View(updates, null);
            Map<Integer, InetSocketAddress> addr = new HashMap<Integer, InetSocketAddress>();
            for (int i = 0; i < vp.getMembership().length; i++) {
                if (getSVController().getCurrentView().isMember(vp.getMembership()[i])) {
                    addr.put(vp.getMembership()[i], getSVController().getCurrentView().getAddress(vp.getMembership()[i]));
                } else {//esta em rcev
                    for (int j = 0; j < recv.size(); j++) {
                        if (Integer.parseInt(recv.get(j).value.toString()) == vp.getMembership()[i]) {
                            addr.put(vp.getMembership()[i], recv.get(j).addr);
                        }
                    }
                }
            }
            vp.setAddresses(addr);
            List<View> proposal = new LinkedList<View>();
            proposal.add(vp);
            //System.out.println("Vai propor view " + proposal.get(0));
            this.getVG(SVController.getCurrentView()).generateView(proposal);

        } else {
            System.out.println("NAO Vai iniciar uma reconfiguração.");
        }
        recvLock.unlock();
    }

    /**
     * A callback from the view generator to inform that a sequence was
     * generated
     *
     * @param seq
     * @param associatedView
     */
    public void newView(List<View> seq, View associatedView) {
        View w = getLeastUpdated(seq);
        StringBuffer b = new StringBuffer("");
        for (int i = 0; i < seq.size() - 1; i++) {
            b.append(seq.get(i) + ",");
        }
        b.append(seq.get(seq.size() - 1));
        System.out.println("Sequencia gerada: " + b.toString());
        InstallSeqMessage inst = new InstallSeqMessage(w, FreeStoreMessageType.INSTALL_SEQ, seq, associatedView);
        QuorumMessage qm = new QuorumMessage(MessageType.RECONFIGURATION_MESSAGE, inst, id);
        this.cs.send(associatedView.getMembership(), qm, associatedView);
    }

    /**
     * Processing of INSTALL_SEQ message
     *
     * @param m
     */
    private void installSeq(FreeStoreMessage m) {//execução da reconfiguração propriamente dita!!! Não estou implementando o R_Multicast!!! Tem que verificar se ja enviou e cano não enviou enviar também antes de executar
        InstallSeqMessage msg = (InstallSeqMessage) m;
        if (!alreadyInstalled(msg)) {
            this.installed.add(msg);
            View ov = msg.view;
            View w = msg.getW();
            System.out.println("Installing view " + w + " to update " + ov);
            if (ov.isMember(id)) {
                if (w.isMostUpToDateThan(this.SVController.getCurrentView())) {

                    if (!alreadyLocked) {
                        alreadyLocked = true;
                        try {
                            //System.out.println("vai bloquear"); //usar um atomicboolean para ver se já esta locked
                            this.clientOperationLock.acquire();
                            //System.out.println("passou");
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                }
                List<View> genSeq = (List<View>) msg.getValue();
                StateUpdateMessage su = null;
                if (genSeq.size() > 1) { //there are more views to propose
                    genSeq.remove(w);
                    su = new StateUpdateMessage(recv, getTimestamp(), FreeStoreMessageType.STATE_UPDATE, getValue(), ov, w, genSeq);
                } else {
                    su = new StateUpdateMessage(recv, getTimestamp(), FreeStoreMessageType.STATE_UPDATE, getValue(), ov, w, null);
                }
                if (w.getMembership().length > 0) {
                    this.cs.connectToView(w);
                    this.cs.send(w.getMembership(),
                            new QuorumMessage(MessageType.RECONFIGURATION_MESSAGE, su, id), w);//enviar state_update para servidores em w
                } else {//Última réplica sainda (não precisa fazer mais nada)
                    System.exit(0);
                }
            }
        }
    }

    /**
     * Processing of STATE_UPDATE message
     *
     * @param msg
     */
    private void stateUpdateMessage(FreeStoreMessage msg) {
        StateUpdateMessage sum = (StateUpdateMessage) msg;
        View ov = sum.view;
        List<StateUpdateMessage> msgs = this.getStateMessages(ov);
        //System.out.println(sum.w+" SM: " + sum.view + " TM: " + msgs.size());
        int count = 1;
        for (int i = 0; i < msgs.size(); i++) {
            if (msgs.get(i).w.equals(sum.w)) {
                count++;
            }
        }
        msgs.add(sum);
        if (count == sum.view.getQuorum()) {
            // System.out.println("ENTROU SM: " + sum.view + " TM: " + msgs.size());
            if (sum.w.isMostUpToDateThan(this.SVController.getCurrentView())) {
                if (sum.w.isMember(id)) {
                    //System.out.println("UPDATE STATE SM: " + sum.view + " TM: " + msgs.size());
                    updateState(getStateMessages(ov), sum.w);//atualiza value, timestamp e RECV
                    this.SVController.reconfigureTo(sum.w);
                    cs.getController().reconfigureTo(sum.w);
                    if (!ov.isMember(id)) { //esperando o processamento do JOIN (da pra fazer diferente tb)
                        joinLeave.release();//enable operations? libera a thread que criou e executou join!!!
                    }

                    FreeStoreMessage wu = new FreeStoreMessage(FreeStoreMessageType.VIEW_UPDATED, null, sum.w);//enviar view_updated
                    for (int i = 0; i < ov.getMembership().length; i++) {
                        if (!sum.w.isMember(ov.getMembership()[i])) { //leave
                            //System.out.println("ENVIANDO VIEW UPDATED SM: " + sum.view + " TM: " + msgs.size());
                            this.cs.send(new int[]{ov.getMembership()[i]}, new QuorumMessage(MessageType.RECONFIGURATION_MESSAGE, wu, id), ov);
                        }
                    }
                    List<View> newProposal = new LinkedList<View>();
                    if (sum.generatedSeq != null) {
                        for (int i = 0; i < sum.generatedSeq.size(); i++) {
                            if (sum.generatedSeq.get(i).isMostUpToDateThan(sum.w)) {
                                newProposal.add(sum.generatedSeq.get(i));
                            }
                        }
                    }
                    if (newProposal.size() > 0) {
                        //System.out.println(sum.w+" propondo novamente");
                        this.getVG(sum.w).generateView(newProposal);
                    } else {
                        //System.out.println(sum.w+" liberando lock");
                        boolean reconfigInProcess = false;
                        for(int i = 0; i < this.installed.size();i++){
                            if(this.installed.get(i).getW().isMostUpToDateThan(sum.w)){
                                reconfigInProcess = true;
                            }
                        }
                        if(!reconfigInProcess){
                            this.alreadyLocked = false;
                            this.clientOperationLock.release(); //unlok the execution of client operations
                        }
                    }
                }
            }
        }
    }

    /**
     * A method to update the replica's state (register value and timestamp) and
     * recv
     *
     * @param msgs
     * @param w
     */
    private void updateState(List<StateUpdateMessage> msgs, View w) {
        StateUpdateMessage max = msgs.get(0);
        for (int i = 1; i < msgs.size(); i++) {
            if (msgs.get(i).timestamp > max.timestamp) {
                max = msgs.get(i);
            }
        }
        this.updateState(max.timestamp, max.getValue());
        List<RECVMessage> newUpdates = new LinkedList<RECVMessage>();
        for (int i = 0; i < msgs.size(); i++) {
            for (int j = 0; j < msgs.get(i).rec.size(); j++) {
                if (!w.containsUpdate(Integer.parseInt(msgs.get(i).rec.get(j).value.toString()))) {
                    if (!newUpdates.contains(msgs.get(i).rec.get(j))) {
                        newUpdates.add(msgs.get(i).rec.get(j));
                    }
                }
            }

        }
        recvLock.lock();
        for (int j = 0; j < recv.size(); j++) {
            if (!w.containsUpdate(Integer.parseInt(recv.get(j).value.toString()))) {
                if (!newUpdates.contains(recv.get(j))) {
                    newUpdates.add(recv.get(j));
                }
            }
        }
        this.recv = newUpdates;
        recvLock.unlock();
    }

    /**
     * Processing of VIEW_UPDATED message
     *
     * @param msg
     */
    private void viewUpdatedMessage(FreeStoreMessage msg) {
        List<FreeStoreMessage> msgs = getVUMessages(msg.view);
        msgs.add(msg);
        if (msgs.size() == msg.view.getQuorum()) {
            //HALT
            this.cs.close();

            System.exit(0);
        }
    }

    /**
     * Aux method to verify if a INSTALL_SEQ message already was processed
     *
     * @param m
     * @return
     */
    private boolean alreadyInstalled(InstallSeqMessage m) {
        for (int i = 0; i < this.installed.size(); i++) {
            if (this.installed.get(i).equals(m)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Aux method to get the least updated view of some sequence
     *
     * @param s
     * @return
     */
    private View getLeastUpdated(List<View> s) {
        View ret = s.get(0);
        for (int i = 1; i < s.size(); i++) {
            if (ret.isMostUpToDateThan(s.get(i))) {
                ret = s.get(i);
            }
        }

        return ret;
    }

    /**
     * Aux method to multicast a message to servers using the client
     * communication system
     *
     * @param sm
     * @param servers
     */
    public void multicast(QuorumMessage sm, int[] servers, View v) {
        cs.send(servers, sm, v);
    }

    //Falta: remover as reconfigurações passadas (testar pela current view quando da instalação)
    private ViewGenerator getVG(View view) {
        ViewGenerator ret = this.vg.get(view.toString());
        if (ret == null) {
            if(this.vgType == ViewGeneratorType.LIVE){
                ret = new LiveViewGenerator(view, this);
            }else if (this.vgType == ViewGeneratorType.SAFE){
                ret = new SafeViewGenerator(view, this);
            }
            this.vg.put(view.toString(), ret);
        }
        return ret;
    }

    //Falta: remover as das visões passadas (depois de instalar uma visão)
    private List<StateUpdateMessage> getStateMessages(View view) {
        List<StateUpdateMessage> ret = this.stateMsgs.get(view.toString());
        if (ret == null) {
            ret = new LinkedList<StateUpdateMessage>();
            this.stateMsgs.put(view.toString(), ret);
        }
        return ret;
    }

    //Falta: remover as das visões passadas (depois de instalar uma visão)
    private List<FreeStoreMessage> getVUMessages(View view) {
        List<FreeStoreMessage> ret = this.viewUpdatedMsgs.get(view.toString());
        if (ret == null) {
            ret = new LinkedList<FreeStoreMessage>();
            this.viewUpdatedMsgs.put(view.toString(), ret);
        }
        return ret;
    }

    /**
     * Pool of threads used to process reconfiguration requests
     */
    private class ReconfigurationWorker extends Thread {

        private LinkedBlockingQueue<FreeStoreMessage> requests;

        public ReconfigurationWorker(LinkedBlockingQueue<FreeStoreMessage> requests) {
            this.requests = requests;
        }

        public void run() {
            FreeStoreMessage msg = null;
            while (true) {
                try {
                    msg = this.requests.take();
                    //System.out.println("recebeu uma msg do tipo " + msg.type + " view: " + msg.view);
                    if (msg.type == FreeStoreMessageType.INSTALL_SEQ) {
                        canExecuteLock.lock();
                        installSeq(msg);
                        canExecuteLock.unlock();
                    } /*else if (msg.type == FreeStoreMessageType.L_SEQ_CONV || msg.type == FreeStoreMessageType.L_SEQ_VIEW ||
                            msg.type == FreeStoreMessageType.S_ACCEPT || msg.type == FreeStoreMessageType.S_PREPARE ||
                            msg.type == FreeStoreMessageType.S_PREPARE_REPLY) {
                        getVG(msg.view).execMessage(msg);
                    } */else if (msg.type == FreeStoreMessageType.STATE_UPDATE) {
                        canExecuteLock.lock();
                        stateUpdateMessage(msg);
                        canExecuteLock.unlock();
                    } else if (msg.type == FreeStoreMessageType.VIEW_UPDATED) {
                        canExecuteLock.lock();
                        viewUpdatedMessage(msg);
                        canExecuteLock.unlock();
                    } else {
                        //System.out.println("MENSAGEM DE TIPO NENHUM!!!");
                        getVG(msg.view).execMessage(msg);
                    }

                } catch (Exception ie) {
                    ie.printStackTrace();
                    continue;
                }
            }
        }
    }

    /**
     * Pool of threads used to process client operations
     */
    private class ClientOperationWorker extends Thread {

        private LinkedBlockingQueue<QuorumMessage> requests;

        public ClientOperationWorker(LinkedBlockingQueue<QuorumMessage> requests) {
            this.requests = requests;
        }

        public void run() {
            QuorumMessage msg = null;
            while (true) {
                try {
                    msg = this.requests.take();
                    clientOperationLock.acquire();
                    QuorumMessage resp = executeProtocolRequest(msg);
                    clientOperationLock.release();
                    sendReply(new int[]{msg.getSender()}, resp);
                } catch (Exception ie) {
                    ie.printStackTrace();
                    continue;
                }
            }
        }
    }

}


text:
ROOT := ../../..

#
# Customize the build
#

INSTALL := yes
DEPENDENCIES := ../../cpl.i $(ROOT)/include/cpl.h $(ROOT)/include/cplxx.h

#
# Include the magic script
#

include $(ROOT)/make/perl-module-swig.mk


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<meta name="generator" content="joDoc">
<title>Apache Cordova API Documentation</title>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
<link rel="stylesheet" type="text/css" href="prettify/prettify.css">

Apache Cordova Documentation

                <select><optgroup label="English" value="en">
<option value="edge">edge</option>
<option value="2.9.0rc1">2.9.0rc1</option>
<option value="2.9.0">2.9.0</option>
<option value="2.8.0">2.8.0</option>
<option value="2.7.0rc1">2.7.0rc1</option>
<option value="2.7.0">2.7.0</option>
<option value="2.6.0rc1">2.6.0rc1</option>
<option value="2.6.0">2.6.0</option>
<option value="2.5.0rc1">2.5.0rc1</option>
<option value="2.5.0">2.5.0</option>
<option value="2.4.0rc1">2.4.0rc1</option>
<option value="2.4.0">2.4.0</option>
<option value="2.3.0rc2">2.3.0rc2</option>
<option value="2.3.0rc1">2.3.0rc1</option>
<option value="2.3.0">2.3.0</option>
<option value="2.2.0rc2">2.2.0rc2</option>
<option selected value="2.2.0rc1">2.2.0rc1</option>
<option value="2.2.0">2.2.0</option>
<option value="2.1.0rc2">2.1.0rc2</option>
<option value="2.1.0rc1">2.1.0rc1</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0rc1">2.0.0rc1</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0rc1">1.9.0rc1</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.8.0rc1">1.8.0rc1</option>
<option value="1.8.0">1.8.0</option>
<option value="1.7.0rc1">1.7.0rc1</option>
<option value="1.7.0">1.7.0</option>
<option value="1.6.1">1.6.1</option>
<option value="1.6.0rc1">1.6.0rc1</option>
<option value="1.6.0">1.6.0</option>
<option value="1.5.0rc1">1.5.0rc1</option>
<option value="1.5.0">1.5.0</option>
</optgroup>
<optgroup label="Japanese" value="jp">
<option value="2.2.0">2.2.0</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.7.0">1.7.0</option>
</optgroup>
<optgroup label="Korean" value="kr"><option value="2.0.0">2.0.0</option></optgroup></select>

Getting Started with iOS

            <select><option value="Getting%2520Started%2520with%2520iOS">Getting Started with iOS</option>
<option value="Getting%20Started%20with%20iOS_requirements">      - Requirements</option>
<option value="Getting%20Started%20with%20iOS_install_the_ios_sdk_and_apache_cordova">      - Install the iOS SDK and Apache Cordova</option>
<option value="Getting%20Started%20with%20iOS_install_cordovalib">      - Install CordovaLib </option>
<option value="Getting%20Started%20with%20iOS_create_a_new_project">      - Create a New Project</option>
<option value="Getting%20Started%20with%20iOS_deploy_to_simulator">      - Deploy to Simulator</option>
<option value="Getting%20Started%20with%20iOS_deploy_to_device">      - Deploy to Device
</option>
<option value="Getting%20Started%20with%20iOS_results">      - Results</option>
<option value="Getting%20Started%20with%20iOS_problems_in_xcode">      - Problems in Xcode</option>
<option value="Getting%20Started%20with%20iOS_build_your_app">      - Build Your App</option>
<option value="Getting%20Started%20with%20iOS_problems_in_the_command_line_tools">      - Problems in the Command Line Tools</option></select>

API Reference

Accelerometer

Camera

Capture

Compass

Connection

Contacts

Device

Events

File

Geolocation

Globalization

Media

Notification

Storage

Guides

Getting Started Guides

Command-Line Usage

Upgrading Guides

Project Settings

Plugin Development Guide

Domain Whitelist Guide

Embedding WebView

Keyword Index

Getting Started with iOS

This guide describes how to set up your development environment for Apache Cordova and run a sample Apache Cordova application.

Requirements

Xcode 4.3+

Xcode Command Line Tools

Intel-based computer with Mac OS X Lion or greater (10.7+)

Necessary for installing on device:

Apple iOS device (iPhone, iPad, iPod Touch)

iOS developer certificate

Install the iOS SDK and Apache Cordova

Install Xcode from the Mac App Store or Apple Developer Downloads

Install the Xcode Command Line Tools (Xcode Preferences -> Downloads -> Components -> Command Line Tools -> Install).

Download the latest release of Apache Cordova

extract its contents

Apache Cordova iOS is found under lib/ios

Install CordovaLib

Download the Cordova source

Extract to source to their final permanent location on your hard drive (for example, to ~/Documents/CordovaLib-2.X.X)

There is no step 3

Create a New Project

Launch Terminal.app

Drag the bin folder (located in the permanent folder location of Cordova, from the "Install CordovaLib" section above) to the Terminal.app icon in your Dock, it should launch a new Terminal window

Type in ./create <project_folder_path> <package_name> <project_name> then press "Enter"

<project_folder_path> is the path to your new Cordova iOS project (it must be empty if it exists)
<package_name> is the package name, following reverse-domain style convention
<project_name> is the project name

Locate your new project folder that you just created

Launch the .xcodeproj file in the folder

Deploy to Simulator

Change the Target in the Scheme drop-down menu on the toolbar to "HelloWorld" (your project name)

Change the Active SDK in the Scheme drop-down menu on the toolbar to iOS [version] Simulator

Select the Run button in your project window's toolbar

Deploy to Device

Open HelloWorld-Info.plist, under the Resources group

Change BundleIdentifier to the identifier provided by Apple or your own bundle identifier

If you have a developer license, you can run the Assistant to register your app

Change the Target in the Scheme drop-down menu on the toolbar to "HelloWorld" (your project name)

Change the Active SDK in the Scheme drop-down menu on the toolbar to [Your Device Name]

You will need to have your device connected via USB

Select the Run button in your project window's toolbar

Results

You should see the screen below, with a pulsating green "device is ready" message

Problems in Xcode

If you have compilation problems related to missing headers, the build products should build into the same build directory. You may need to set the preference "Xcode Preferences -> Locations -> Derived Data -> Advanced…" to "Unique". This is the default setting for Xcode on a fresh new install, if you upgraded from older versions of Xcode, you might have a legacy preference in there that you need to update.

Build Your App

You now have an Xcode project setup and you can build and run on the Simulator and device.
It is important to understand that you do not need to use Xcode to write your web application.
You can use your favourite text editor and simply rebuild your project using Xcode, or the command-line tools in your project folder (under the cordova sub-folder)
Xcode will automatically detect the files that are changed in www.

Problems in the Command Line Tools

If you see this error: "Error: No developer directory found at /Developer. Run /usr/bin/xcode-select to update the developer directory path." Run this to set your Developer folder:

    sudo /usr/bin/xcode-select -switch /Applications/Xcode.app/Contents/Developer


text:
<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>Demoiselle JDBI Maven Webapp</display-name>

	<!-- Auto scan REST service -->
	<context-param>
		<param-name>resteasy.scan</param-name>
		<param-value>true</param-value>
	</context-param>

	<!-- this need same with resteasy servlet url-pattern -->
	<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/rest</param-value>
	</context-param>

	<listener>
		<listener-class>
			org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
		</listener-class>
	</listener>

	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
		</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>resteasy-servlet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>

</web-app>


text: Dreamy is about to become an informative and beatiful daydream app for your android phone.


text:
#ifndef GGTABBAR_H
#define GGTABBAR_H

#include <QScrollArea>
#include <QTabBar>
#include <QToolButton>
#include <QVariant>
#include <QLineEdit>

/* ------------------------------------------------------------------------- */

#define GG_TABBAR_MAX_SCROLL_SPEED 15

/* ------------------------------------------------------------------------- */

/**
 * Basic Tab Bar whose tabs are closed when clicking with the middle button.
 * Its default tabsClosable value is true.
 *
 * It also provides a isDragging() method to know if a tab is currently being dragged.
 */
class GGTabBar : public QTabBar
{
    Q_OBJECT
public:
    GGTabBar(QWidget* parent = nullptr);
    ~GGTabBar();

    inline bool isDragging() { return m_bDragging; }
    inline bool renameOnDoubleClick() { return m_bRenameOnDoubleClick; }
    inline void setRenameOnDoubleClick(bool b) { m_bRenameOnDoubleClick = b; }

signals:
    void tabDoubleClicked(int);

protected:
    virtual void mousePressEvent        (QMouseEvent* e);
    virtual void mouseMoveEvent         (QMouseEvent* e);
    virtual void mouseReleaseEvent      (QMouseEvent* e);
    virtual void mouseDoubleClickEvent  (QMouseEvent* e);

private:
    void startRename(int);

private:
    QLineEdit * m_pTabNameEdit;
    int m_iEditedTabIndex;
    bool m_bDragging;
    bool m_bRenameOnDoubleClick;

private slots:
    void finishRename();
};

/**
 * Scrollable Tab Bar is a "scrollable" GGTabBar.
 * Its tabs are movable and when moving a tab outside of the TabBar, the tabBar is scrolled.
 *
 * The height of the GGScrollableTabBar is automatically adjusted to its content.
 * Therefore, it will not be displayed when there is no tab.
 *
 * When focusing a tab, the GGScrollableTabBar will automatically scroll to make it visible.
 *
 * The methods of GGTabBar are directly accessible through GGScrollableTabBar.
 */
class GGScrollableTabBar : public QScrollArea
{
    Q_OBJECT

public:
    GGScrollableTabBar(QWidget* parent = nullptr);
    ~GGScrollableTabBar();

    bool blockSignals(bool block); //Also blocks the GGTabBar signals.

    inline int addTab(const QString& text) { return m_pTabBar->addTab(text); }
    inline int addTab(const QIcon &icon, const QString &text) { return m_pTabBar->addTab(icon, text); }
    inline bool autoHide() const { return m_pTabBar->autoHide(); }
    inline int currentIndex() const { return m_pTabBar->currentIndex(); }
    inline int count() const { return m_pTabBar->count(); }
    inline bool documentMode() const { return m_pTabBar->documentMode(); }
    inline Qt::TextElideMode elideMode() const { return m_pTabBar->elideMode(); }
    inline bool expanding() const { return m_pTabBar->expanding(); }
    inline QSize iconSize() const { return m_pTabBar->iconSize(); }
    inline int insertTab(int index, const QString &text) { return m_pTabBar->insertTab(index, text); }
    inline int insertTab(int index, const QIcon&icon, const QString &text) { return m_pTabBar->insertTab(index, icon, text); }
    inline bool isTabEnabled(int index) const { return m_pTabBar->isTabEnabled(index); }
    inline void moveTab(int from, int to) { m_pTabBar->moveTab(from, to); }
    inline void removeTab(int index) { m_pTabBar->removeTab(index); }
    inline void setAutoHide(bool hide) { m_pTabBar->setAutoHide(hide); }
    inline void setDocumentMode(bool set) { m_pTabBar->setDocumentMode(set); }
    inline void setElideMode(Qt::TextElideMode elideMode) { m_pTabBar->setElideMode(elideMode); }
    inline void setExpanding(bool enabled) { m_pTabBar->setExpanding(enabled); }
    inline void setIconSize(const QSize &size) { m_pTabBar->setIconSize(size); }
    inline void setTabButton(int index, QTabBar::ButtonPosition position, QWidget *widget) { m_pTabBar->setTabButton(index, position, widget); }
    inline void setTabsClosable(bool closable) { m_pTabBar->setTabsClosable(closable); }
    inline void setTabData(int index, const QVariant& data) { m_pTabBar->setTabData(index, data); }
    inline void setTabEnabled(int index, bool bEnabled) { m_pTabBar->setTabEnabled(index, bEnabled); }
    inline void setTabIcon(int index, const QIcon &icon) { m_pTabBar->setTabIcon(index, icon); }
    inline void setTabText(int index, const QString&  text) { m_pTabBar->setTabText(index, text); }
    inline void setTabTextColor(int index, const QColor &color) { m_pTabBar->setTabTextColor(index, color); }
    inline int tabAt(const QPoint &pos) const;
    inline QWidget* tabButton(int index, QTabBar::ButtonPosition position) const { return m_pTabBar->tabButton(index, position); }
    inline bool tabsClosable() const { return m_pTabBar->tabsClosable(); }
    inline QVariant tabData(int index) const { return m_pTabBar->tabData(index); }
    inline QIcon tabIcon(int index) const { return m_pTabBar->tabIcon(index); }
    inline QRect tabRect(int index) const { return m_pTabBar->tabRect(index); }
    inline QString tabText(int index) const { return m_pTabBar->tabText(index); }
    inline QColor tabTextColor(int index) const { return m_pTabBar->tabTextColor(index); }

#ifndef QT_NO_TOOLTIP
    inline void setTabToolTip(int index, const QString &tip) { m_pTabBar->setTabToolTip(index, tip); }
    inline QString tabToolTip(int index) const { return m_pTabBar->tabToolTip(index); }
#endif

#ifndef QT_NO_WHATSTHIS
    inline void setTabWhatsThis(int index, const QString &text) { m_pTabBar->setTabWhatsThis(index, text); }
    inline QString tabWhatsThis(int index) const { return m_pTabBar->tabWhatsThis(index); }
#endif

signals:
    void currentChanged(int index);
    void tabCloseRequested(int index);
    void tabMoved(int from, int to);
    void tabBarClicked(int index);
    void tabBarDoubleClicked(int index);

public slots:
    inline void setCurrentIndex(int index) { m_pTabBar->setCurrentIndex(index); }

protected:
    virtual bool eventFilter(QObject* o, QEvent* e);
    virtual void mouseMoveEvent     (QMouseEvent* e);
    virtual void mouseReleaseEvent  (QMouseEvent* e);
    virtual void resizeEvent        (QResizeEvent* e);

protected slots:
    inline void makeCurrentVisible() { this->makeVisible(m_pTabBar->currentIndex()); }
    void makeVisible(int index);
    void adjustHeight();
    inline void onCurrentChanged    (int index) { makeVisible(index); emit currentChanged(index); }
    inline void onTabCloseRequested (int index) { emit tabCloseRequested(index); }
    inline void onTabMoved          (int from, int to) { emit tabMoved(from, to); }
    inline void onTabBarClicked     (int index) { emit tabBarClicked(index); }
    inline void onTabBarDoubleClicked(int index) { emit tabBarDoubleClicked(index); }

private:
    void scroll(int dx);

private:
    GGTabBar*       m_pTabBar;
};

/**
 * GGTabBarWidget handles a GGScrollableTabBar and a button that displays a Menu
 * containing direct links to all the tabs when clicked.
 * The actions in the Menu are sorted by alphabetical order.
 *
 * By default, the button is not displayed when there is no tab.
 *
 * The methods of GGScrollableTabBar are directly accessible through GGTabBarWidget.
 */
class GGTabBarWidget : public QWidget
{
    Q_OBJECT

public:
    GGTabBarWidget(QWidget* parent = nullptr);
    ~GGTabBarWidget();

    bool blockSignals(bool block); //Also blocks the GGScrollableTabBar signals.

    inline int addTab(const QString& text)                    { m_pMenuButton->show(); return m_pScrollableTabBar->addTab(text); }
    inline int addTab(const QIcon &icon, const QString &text) { m_pMenuButton->show(); return m_pScrollableTabBar->addTab(icon, text); }
    inline void removeTab(int index) { m_pScrollableTabBar->removeTab(index); if( 0 == this->count() ) { m_pMenuButton->hide(); } }

    inline bool autoHide() const { return m_pScrollableTabBar->autoHide(); }
    inline int currentIndex() const { return m_pScrollableTabBar->currentIndex(); }
    inline int count() const { return m_pScrollableTabBar->count(); }
    inline bool documentMode() const { return m_pScrollableTabBar->documentMode(); }
    inline Qt::TextElideMode elideMode() const { return m_pScrollableTabBar->elideMode(); }
    inline bool expanding() const { return m_pScrollableTabBar->expanding(); }
    inline QSize iconSize() const { return m_pScrollableTabBar->iconSize(); }
    inline int insertTab(int index, const QString &text) { return m_pScrollableTabBar->insertTab(index, text); }
    inline int insertTab(int index, const QIcon&icon, const QString &text) { return m_pScrollableTabBar->insertTab(index, icon, text); }
    inline bool isTabEnabled(int index) const { return m_pScrollableTabBar->isTabEnabled(index); }
    inline void moveTab(int from, int to) { m_pScrollableTabBar->moveTab(from, to); }
    inline void setAutoHide(bool hide) { m_pScrollableTabBar->setAutoHide(hide); }
    inline void setDocumentMode(bool set) { m_pScrollableTabBar->setDocumentMode(set); }
    inline void setElideMode(Qt::TextElideMode elideMode) { m_pScrollableTabBar->setElideMode(elideMode); }
    inline void setExpanding(bool enabled) { m_pScrollableTabBar->setExpanding(enabled); }
    inline void setIconSize(const QSize &size) { m_pScrollableTabBar->setIconSize(size); }
    inline void setTabButton(int index, QTabBar::ButtonPosition position, QWidget *widget) { m_pScrollableTabBar->setTabButton(index, position, widget); }
    inline void setTabsClosable(bool closable) { m_pScrollableTabBar->setTabsClosable(closable); }
    inline void setTabData(int index, const QVariant& data) { m_pScrollableTabBar->setTabData(index, data); }
    inline void setTabEnabled(int index, bool bEnabled) { m_pScrollableTabBar->setTabEnabled(index, bEnabled); }
    inline void setTabIcon(int index, const QIcon &icon) { m_pScrollableTabBar->setTabIcon(index, icon); }
    inline void setTabText(int index, const QString&  text) { m_pScrollableTabBar->setTabText(index, text); }
    inline void setTabTextColor(int index, const QColor &color) { m_pScrollableTabBar->setTabTextColor(index, color); }
    inline int tabAt(const QPoint &pos) const;
    inline QWidget* tabButton(int index, QTabBar::ButtonPosition position) const { return m_pScrollableTabBar->tabButton(index, position); }
    inline bool tabsClosable() const { return m_pScrollableTabBar->tabsClosable(); }
    inline QVariant tabData(int index) const { return m_pScrollableTabBar->tabData(index); }
    inline QIcon tabIcon(int index) const { return m_pScrollableTabBar->tabIcon(index); }
    inline QRect tabRect(int index) const { return m_pScrollableTabBar->tabRect(index); }
    inline QString tabText(int index) const { return m_pScrollableTabBar->tabText(index); }
    inline QColor tabTextColor(int index) const { return m_pScrollableTabBar->tabTextColor(index); }

#ifndef QT_NO_TOOLTIP
    inline void setTabToolTip(int index, const QString &tip) { m_pScrollableTabBar->setTabToolTip(index, tip); }
    inline QString tabToolTip(int index) const { return m_pScrollableTabBar->tabToolTip(index); }
#endif

#ifndef QT_NO_WHATSTHIS
    inline void setTabWhatsThis(int index, const QString &text) { m_pScrollableTabBar->setTabWhatsThis(index, text); }
    inline QString tabWhatsThis(int index) const { return m_pScrollableTabBar->tabWhatsThis(index); }
#endif

signals:
    void currentChanged(int index);
    void tabCloseRequested(int index);
    void tabMoved(int from, int to);
    void tabBarClicked(int index);
    void tabBarDoubleClicked(int index);

public slots:
    inline void setCurrentIndex(int index) { m_pScrollableTabBar->setCurrentIndex(index); }

protected slots:
    void displayMenu();
    void onMenuAction(QAction* pAction);
    inline void onCurrentChanged    (int index) { emit currentChanged(index); }
    inline void onTabCloseRequested (int index) { emit tabCloseRequested(index); }
    inline void onTabMoved          (int from, int to) { emit tabMoved(from, to); }
    inline void onTabBarClicked     (int index) { emit tabBarClicked(index); }
    inline void onTabBarDoubleClicked(int index) { emit tabBarDoubleClicked(index); }

private:
    QToolButton*        m_pMenuButton;
    GGScrollableTabBar* m_pScrollableTabBar;
};

/* ------------------------------------------------------------------------- */

#endif /* GGTabBar_H */


text:
package com.lieverandiver.thesisproject;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ToggleButton;

import com.lieverandiver.thesisproject.adapter.ClassAdapter;
import com.lieverandiver.thesisproject.fragment.Home_Student_Slidebar_Fragment;
import com.lieverandiver.thesisproject.fragment.SliderClassFragment;
import com.lieverandiver.thesisproject.fragment.SliderScheduleFragment;
import com.lieverandiver.thesisproject.fragment.SliderSettingFragment;
import com.remswork.project.alice.model.Teacher;

import java.util.ArrayList;
import java.util.List;

@Deprecated
public class Home_Activity extends AppCompatActivity implements ClassAdapter.ClassAdapterListener,
        SliderSettingFragment.OnProfileClickListener{

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private Button btnBack;
    private ToggleButton btnSearch;
    private Button btnSearchOk;
    private Button btnSearchCancel;
    private EditText editTextSearch;
    private FrameLayout frameLayoutSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        btnSearch = (ToggleButton)findViewById(R.id.btn_search_class);
        btnSearchOk = (Button)findViewById(R.id._btn_search_ok_class);
        btnBack = (Button) findViewById(R.id.btn_back_student);
        editTextSearch =(EditText)findViewById(R.id.etxt_search_class);
        frameLayoutSearch = (FrameLayout)findViewById(R.id.frame_search_class);

        frameLayoutSearch.setVisibility(View.GONE);

        btnSearch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    frameLayoutSearch.setVisibility(View.VISIBLE);
                    tabLayout.setVisibility(View.GONE);
                } else {
                    frameLayoutSearch.setVisibility(View.GONE);
                    tabLayout.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new SliderScheduleFragment(), "Shedule");
        adapter.addFragment(new SliderClassFragment(), "Class");
        adapter.addFragment(new Home_Student_Slidebar_Fragment(), "Student");
        adapter.addFragment(new SliderSettingFragment(), "Setting");
        viewPager.setAdapter(adapter);
    }

    @Override
    public void showClassView(final long classId) {
        Intent intent = new Intent(this, ClassViewActivity.class);
        intent.putExtra("classId", classId);
        startActivity(intent);
    }

    @Override
    public void viewProfile(Teacher teacher) {
        Intent intent = new Intent(this, TeacherViewActivity.class);
        intent.putExtra("teacherId", teacher.getId());
        startActivity(intent);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}


text:
import functools
from unittest import mock

import fixtures
from oslo_utils.fixture import uuidsentinel as uuids
from oslo_utils import timeutils

from nova.api.openstack.compute import lock_server
from nova.compute import vm_states
import nova.conf
from nova import exception
from nova.policies import base as base_policy
from nova.policies import lock_server as ls_policies
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance
from nova.tests.unit.policies import base

CONF = nova.conf.CONF

class LockServerPolicyTest(base.BasePolicyTest):
    """Test Lock server APIs policies with all possible context.
    This class defines the set of context with different roles
    which are allowed and not allowed to pass the policy checks.
    With those set of context, it will call the API operation and
    verify the expected behaviour.
    """

    def setUp(self):
        super(LockServerPolicyTest, self).setUp()
        self.controller = lock_server.LockServerController()
        self.req = fakes.HTTPRequest.blank('')
        user_id = self.req.environ['nova.context'].user_id
        self.mock_get = self.useFixture(
            fixtures.MockPatch('nova.api.openstack.common.get_instance')).mock
        uuid = uuids.fake_id
        self.instance = fake_instance.fake_instance_obj(
                self.project_member_context,
                id=1, uuid=uuid, project_id=self.project_id,
                user_id=user_id, vm_state=vm_states.ACTIVE,
                task_state=None, launched_at=timeutils.utcnow())
        self.mock_get.return_value = self.instance

        # With legacy rule and no scope checks, all admin, project members
        # project reader or other project role(because legacy rule allow server
        # owner- having same project id and no role check) is able to lock,
        # unlock the server.
        self.project_action_authorized_contexts = [
            self.legacy_admin_context, self.system_admin_context,
            self.project_admin_context, self.project_member_context,
            self.project_reader_context, self.project_foo_context]

        # By default, legacy rule are enable and scope check is disabled.
        # system admin, legacy admin, and project admin is able to override
        # unlock, regardless who locked the server.
        self.project_admin_authorized_contexts = [
            self.legacy_admin_context, self.system_admin_context,
            self.project_admin_context]

    @mock.patch('nova.compute.api.API.lock')
    def test_lock_server_policy(self, mock_lock):
        rule_name = ls_policies.POLICY_ROOT % 'lock'
        self.common_policy_auth(self.project_action_authorized_contexts,
                                rule_name,
                                self.controller._lock,
                                self.req, self.instance.uuid,
                                body={'lock': {}})

    @mock.patch('nova.compute.api.API.unlock')
    def test_unlock_server_policy(self, mock_unlock):
        rule_name = ls_policies.POLICY_ROOT % 'unlock'
        self.common_policy_auth(self.project_action_authorized_contexts,
                                rule_name,
                                self.controller._unlock,
                                self.req, self.instance.uuid,
                                body={'unlock': {}})

    @mock.patch('nova.compute.api.API.unlock')
    @mock.patch('nova.compute.api.API.is_expected_locked_by')
    def test_unlock_override_server_policy(self, mock_expected, mock_unlock):
        mock_expected.return_value = False
        rule = ls_policies.POLICY_ROOT % 'unlock'
        self.policy.set_rules({rule: "@"}, overwrite=False)
        rule_name = ls_policies.POLICY_ROOT % 'unlock:unlock_override'
        if not CONF.oslo_policy.enforce_scope:
            check_rule = rule_name
        else:
            check_rule = functools.partial(base.rule_if_system,
                rule, rule_name)
        self.common_policy_auth(self.project_admin_authorized_contexts,
                                check_rule,
                                self.controller._unlock,
                                self.req, self.instance.uuid,
                                body={'unlock': {}})

    def test_lock_server_policy_failed_with_other_user(self):
        # Change the user_id in request context.
        req = fakes.HTTPRequest.blank('')
        req.environ['nova.context'].user_id = 'other-user'
        rule_name = ls_policies.POLICY_ROOT % 'lock'
        self.policy.set_rules({rule_name: "user_id:%(user_id)s"})
        exc = self.assertRaises(
            exception.PolicyNotAuthorized, self.controller._lock,
            req, fakes.FAKE_UUID, body={'lock': {}})
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

    @mock.patch('nova.compute.api.API.lock')
    def test_lock_server_overridden_policy_pass_with_same_user(
        self, mock_lock):
        rule_name = ls_policies.POLICY_ROOT % 'lock'
        self.policy.set_rules({rule_name: "user_id:%(user_id)s"})
        self.controller._lock(self.req,
                              fakes.FAKE_UUID,
                              body={'lock': {}})

class LockServerNoLegacyNoScopePolicyTest(LockServerPolicyTest):
    """Test lock/unlock server APIs policies with no legacy deprecated rules
    and no scope checks which means new defaults only.

    """

    without_deprecated_rules = True

    def setUp(self):
        super(LockServerNoLegacyNoScopePolicyTest, self).setUp()
        # With no legacy rule, only project admin or member will be
        # able to lock/unlock the server.
        self.project_action_authorized_contexts = (
            self.project_member_or_admin_with_no_scope_no_legacy)

class LockServerScopeTypePolicyTest(LockServerPolicyTest):
    """Test Lock Server APIs policies with system scope enabled.
    This class set the nova.conf [oslo_policy] enforce_scope to True
    so that we can switch on the scope checking on oslo policy side.
    It defines the set of context with scoped token
    which are allowed and not allowed to pass the policy checks.
    With those set of context, it will run the API operation and
    verify the expected behaviour.
    """

    def setUp(self):
        super(LockServerScopeTypePolicyTest, self).setUp()
        self.flags(enforce_scope=True, group="oslo_policy")
        # Scope enable will not allow system admin to lock/unlock the server.
        self.project_action_authorized_contexts = (
            self.project_m_r_or_admin_with_scope_and_legacy)
        self.project_admin_authorized_contexts = [
            self.legacy_admin_context, self.project_admin_context]

class LockServerScopeTypeNoLegacyPolicyTest(LockServerScopeTypePolicyTest):
    """Test Lock Server APIs policies with system scope enabled,
    and no more deprecated rules.
    """
    without_deprecated_rules = True

    def setUp(self):
        super(LockServerScopeTypeNoLegacyPolicyTest, self).setUp()
        # With scope enable and no legacy rule, only project admin/member
        # will be able to lock/unlock the server.
        self.project_action_authorized_contexts = (
            self.project_member_or_admin_with_scope_no_legacy)

class LockServerOverridePolicyTest(LockServerScopeTypeNoLegacyPolicyTest):
    """Test Lock Server APIs policies with system and project scoped
    but default to system roles only are allowed for project roles
    if override by operators. This test is with system scope enable
    and no more deprecated rules.
    """

    def setUp(self):
        super(LockServerOverridePolicyTest, self).setUp()
        # We are overriding the 'unlock:unlock_override' policy
        # to PROJECT_MEMBER so testing it with both admin as well
        # as project member as allowed context.
        self.project_admin_authorized_contexts = [
            self.project_admin_context, self.project_member_context]

    def test_unlock_override_server_policy(self):
        rule = ls_policies.POLICY_ROOT % 'unlock:unlock_override'
        self.policy.set_rules({
        # make unlock allowed for everyone so that we can check unlock
        # override policy.
        ls_policies.POLICY_ROOT % 'unlock': "@",
        rule: base_policy.PROJECT_MEMBER}, overwrite=False)
        super(LockServerOverridePolicyTest,
              self).test_unlock_override_server_policy()