text:
using BuildIt.States.Interfaces;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace BuildIt.Forms
{
    /// <summary>
    /// A control that allows developers to force visual state changes.
    /// </summary>
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DesignTimeControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DesignTimeControl"/> class.
        /// </summary>
        public DesignTimeControl()
        {
            // Only show the design time control if the debugger is attached
            if (!Debugger.IsAttached)
            {
                return;
            }

            InitializeComponent();
        }

        private enum DesignStates
        {
            Base,
            GroupsHidden,
            GroupsVisible,
        }

        /// <summary>
        /// Handles the selection changed event for design actions.
        /// </summary>
        /// <param name="sender">The listview containing design actions.</param>
        /// <param name="e">The selection change.</param>
        public async void DesignActionSelectionChanged(object sender, SelectedItemChangedEventArgs e)
        {
            try
            {
                await HideGroups();

                var action = e.SelectedItem as Tuple<string, Action>;
                $"Running design action {action?.Item1}".LogFormsInfo();
                action?.Item2();

                if (sender is ListView lv)
                {
                    lv.SelectedItem = null;
                }
            }
            catch (Exception ex)
            {
                ex.LogFormsException();
            }
        }

        /// <summary>
        /// Handles the selection changed event for groups.
        /// </summary>
        /// <param name="sender">The listview containing groups.</param>
        /// <param name="e">The selection change.</param>
        public void GroupSelectionChanged(object sender, SelectedItemChangedEventArgs e)
        {
            try
            {
                "StateGroupList selection changed".LogFormsInfo();

                if (e.SelectedItem == null)
                {
                    "StateGroupList no selection".LogFormsInfo();
                    States.IsVisible = false;
                    return;
                }

                var design = (sender as Element)?.BindingContext as DesignInfo;
                var group = e.SelectedItem as IStateGroup;
                if (design == null || group == null)
                {
                    "no context or group".LogFormsInfo();
                    return;
                }

                ("Group: " + group.GroupName).LogFormsInfo();
                design.SelectedGroup = group;
                States.IsVisible = true;

                "SateGroupList selection changed - END".LogFormsInfo();
            }
            catch (Exception ex)
            {
                ex.LogFormsException();
            }
        }

        /// <summary>
        /// The selection changed handler for states.
        /// </summary>
        /// <param name="sender">The listview of states.</param>
        /// <param name="e">The selection change.</param>
        public async void StateSelectionChanged(object sender, SelectedItemChangedEventArgs e)
        {
            try
            {
                "StateList selection changed".LogFormsInfo();

                if (e.SelectedItem == null)
                {
                    "StateList no selection".LogFormsInfo();
                    return;
                }

                var design = (sender as Element)?.BindingContext as DesignInfo;
                var state = e.SelectedItem as IStateDefinition;

                StatesList.SelectedItem = null;

                StateGroupList.SelectedItem = null;
                await HideGroups();

                if (design == null || state == null)
                {
                    "No context or state".LogFormsInfo();
                    return;
                }

                ("State: " + state.StateName).LogFormsInfo();
                await VisualStateManager.GoToState(design.Element, state.StateName);
                "SateList selection changed - END".LogFormsInfo();
            }
            catch (Exception ex)
            {
                ex.LogFormsException();
            }
        }

        /// <summary>
        /// Exits the state picker.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The event args.</param>
        protected async void ExitDesignTime(object sender, TouchActionEventArgs args)
        {
            try
            {
                var touchArgs = args as TouchActionEventArgs;
                if (touchArgs == null ||
                    (touchArgs.Type != TouchActionType.Pressed && touchArgs.Type != TouchActionType.Released))
                {
                    return;
                }

                StatesList.SelectedItem = null;

                StateGroupList.SelectedItem = null;
                await HideGroups();
            }
            catch (Exception ex)
            {
                ex.LogFormsException();
            }
        }

        /// <summary>
        /// Launches the Built to Roam website.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The event args.</param>
        protected async void LaunchBuiltToRoamWebsite(object sender, TouchActionEventArgs args)
        {
            try
            {
                var touchArgs = args as TouchActionEventArgs;
                if (touchArgs == null ||
                    (touchArgs.Type != TouchActionType.Pressed && touchArgs.Type != TouchActionType.Released))
                {
                    return;
                }

                await Launcher.OpenAsync(new Uri("https://www.builttoroam.com"));
            }
            catch (Exception ex)
            {
                ex.LogFormsException();
            }
        }

        /// <summary>
        /// Launches the state picker.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The event args.</param>
        protected async void LaunchDesignTime(object sender, TouchActionEventArgs args)
        {
            try
            {
                var touchArgs = args as TouchActionEventArgs;
                if (touchArgs == null ||
                    (touchArgs.Type != TouchActionType.Pressed && touchArgs.Type != TouchActionType.Released))
                {
                    return;
                }

                "Launching".LogFormsInfo();
                await ShowGroups();
            }
            catch (Exception ex)
            {
                ex.LogFormsException();
            }
        }

        private async Task HideGroups()
        {
            await VisualStateManager.GoToState(this, DesignStates.GroupsHidden.ToString());
            this.HorizontalOptions = LayoutOptions.Start;
            this.VerticalOptions = LayoutOptions.End;
        }

        private async Task ShowGroups()
        {
            this.HorizontalOptions = LayoutOptions.Fill;
            this.VerticalOptions = LayoutOptions.Fill;
            await VisualStateManager.GoToState(this, DesignStates.GroupsVisible.ToString());
        }
    }
}


text:
function(process_file_recurse input_file)
  set(input_file_full_path)
  if(IS_ABSOLUTE "${input_file}" AND EXISTS "${input_file}")
    set(input_file_full_path ${input_file})
    if(PKG_DEBUG)
      message("Found '${input_file}' (return)")
    endif()
  else()
    search_library(${input_file} PKG_SEARCHDIRS input_file_full_path)
  endif()
  if(NOT input_file_full_path)
    if(LINUX)
      setif_value_in_list(is_gtk_lib "${input_file}" ALLOWED_SYSTEM_DLLS)
      if(is_gtk_lib)
        search_library(${input_file} PKG_GTK_SEARCHDIRS input_file_full_path)
        if( NOT input_file_full_path)
          message(FATAL_ERROR "${input_file} not found. searched in ${PKG_GTK_SEARCHDIRS}")
        endif()
      endif()
    endif(LINUX)
  endif() #if(NOT input_file_full_path)

  if( NOT input_file_full_path)
    message(FATAL_ERROR "${input_file} not found. searched in ${PKG_SEARCHDIRS}")
  endif()

  get_filename_component(bn_name ${input_file_full_path} NAME)
  if(${bn_name}_RESOLVED)
    # item already resolved
    return()
  endif()

  if(NOT PKG_DEBUG)
    message("Processing ${input_file_full_path}")
  endif()

  # Install the file with install_rule().
  # This function has specific "rules" to decide whether and where to install file
  install_rule(${input_file_full_path})

  set(raw_items)

  execute_process(
    COMMAND ${LOADER_PROGRAM} ${LOADER_ARGS} "${input_file_full_path}"
    RESULT_VARIABLE loader_rv
    OUTPUT_VARIABLE loader_ov
    ERROR_VARIABLE loader_ev
    )

  if(loader_rv)
    message(FATAL_ERROR "loader_ev=${loader_ev}\n PACKAGE-OTB: result_variable is '${loader_rv}'")
  endif()

  string(REPLACE ";" "\\;" candidates "${loader_ov}")
  string(REPLACE "\n" "${LOADER_REGEX_EOL};" candidates "${candidates}")

  set(${bn_name}_USED TRUE CACHE INTERNAL "")

  if(PKG_DEBUG)
    message("Processing ${input_file} started. Set ${bn_name}_USED=${${bn_name}_USED}")
  endif()

  foreach(candidate ${candidates})
    if(NOT candidate)
      continue()
    endif()

    if(NOT "${candidate}" MATCHES "${LOADER_REGEX}")
      continue()
    endif()

    string(REGEX REPLACE "${LOADER_REGEX}" "\\1" raw_item "${candidate}")

    if(NOT raw_item)
      continue()
    endif()

    string(STRIP ${raw_item} raw_item)
    set(is_system FALSE)
    setif_value_in_list(is_system "${raw_item}" SYSTEM_DLLS)
    if(APPLE AND NOT is_system)
      if(("${input_file_full_path}" MATCHES "/plugins/") AND ("${raw_item}" MATCHES "${input_file}"))
        # ignore the check for @rpath on plugins for the library own name
      else()
        if("${raw_item}" MATCHES "@rpath")
          string(REGEX REPLACE "@rpath." "" raw_item "${raw_item}")
        else()
          message(FATAL_ERROR "'${raw_item}' does not have @rpath")
        endif()
      endif()
    endif()

    if(PKG_DEBUG AND ${raw_item}_RESOLVED)
      message("${raw_item} is already resolved [${raw_item}_RESOLVED=${${raw_item}_RESOLVED}]")
    endif()

    if(PKG_DEBUG)
      message("raw_item='${raw_item}'\tis_system='${is_system}'")
    endif()
    if(is_system OR ${raw_item}_RESOLVED OR ${raw_item}_USED)
      continue()
    endif()

    list(APPEND raw_items ${raw_item})

  endforeach()

  if(PKG_DEBUG)
    string(REPLACE ";" "\n" raw_items_pretty_print "${raw_items}")
    # message(FATAL_ERROR "raw_items=${raw_items_pretty_print}")
  endif(PKG_DEBUG)

  if(raw_items)
    list(REVERSE raw_items)
    foreach(item ${raw_items})
      search_library(${item} PKG_SEARCHDIRS item_full_path)
      set(is_a_symlink FALSE)
      set(item_target_file)
      isfile_symlink("${item_full_path}" is_a_symlink item_target_file)
      if(is_a_symlink)
        set(${item}_RESOLVED TRUE CACHE INTERNAL "")
        set(item ${item_target_file})
      endif()
      if(PKG_DEBUG)
        message("${bn_name} depends on '${item}'. So we now process '${item}'") # [ ${item}_USED=${${item}_USED} ${item}_RESOLVED=${${item}_RESOLVED}]")
      endif()
      process_file_recurse(${item})
    endforeach()
  endif()

  set(${bn_name}_RESOLVED TRUE CACHE INTERNAL "")
   if(PKG_DEBUG)
     message("All dependencies of ${bn_name} are processed. Install file and set ${bn_name}_RESOLVED=${${bn_name}_RESOLVED}")
   endif()

   #install_rule(${input_file_full_path})

endfunction() #function(process_file_recurse infile)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">
  <link rel="shortcut icon" href="../images/favicon.png" type="image/png">

  <title>Bracket Responsive Bootstrap3 Admin</title>

  <link href="../css/style.default.css" rel="stylesheet">
  <link href="../css/prettyPhoto.css" rel="stylesheet">

  <link href="../css/style.default-rtl.css" rel="stylesheet">

[ bracket ]

John Doe

                    "Life is so..."

Account

 Profile

 Account Settings

 Help

 Sign Out

Navigation

 Dashboard

2 Email

 Forms

 General Forms

 Form Layouts

 Form Validation

 Form Wizards

 Text Editor

 Code Editor

 UI Elements

 Buttons

 Icons

 Typography

 Alerts & Notifications

 Modals

 Tabs & Accordions

 Sliders

 Graphs & Charts

 Panels & Widgets

 Extras

 Tables

 Bug Tracker

 Summary

 Issues

 View Issue

 Maps

 Pages

 Calendar

 Media Manager

 Timeline

 Blog List

 Blog Single

 People Directory

 Profile

 Invoice

 Search Results

 Blank Page

 404 Page

 Locked Screen

 Sign In

 Sign Up

Information Summary

                    Daily Traffic

630, 201

                    Average Users

1, 332, 801

                    Disk Usage

82.2%

                    CPU Usage

140.05 - 32

                    Memory Usage

32.2%

      <form class="searchform" action="index.html" method="post">
        <input type="text" class="form-control" name="keyword" placeholder="Search here..." />
      </form>

              <button class="btn btn-default dropdown-toggle tp-icon" data-toggle="dropdown">

                2
              </button>

2 Newly Registered Users

Draniem Daamul (@draniem) new

Zaham Sindilmaca (@zaham) new

Weno Carasbong (@wenocar)

Nusja Nawancali (@nusja)

Lane Kitmari (@lane_kitmare)

See All Users

              <button class="btn btn-default dropdown-toggle tp-icon" data-toggle="dropdown">

                1
              </button>

You Have 1 New Message

                      Draniem Daamul new
                      Lorem ipsum dolor sit amet...

                      Nusja Nawancali
                      Lorem ipsum dolor sit amet...

                      Weno Carasbong
                      Lorem ipsum dolor sit amet...

                      Zaham Sindilmaca
                      Lorem ipsum dolor sit amet...

                      Veno Leongal
                      Lorem ipsum dolor sit amet...

Read All Messages

              <button class="btn btn-default dropdown-toggle tp-icon" data-toggle="dropdown">

                5
              </button>

You Have 5 New Notifications

                      Zaham Sindilmaca new
                      is now following you

                      Weno Carasbong new
                      is now following you

                      Veno Leongal new
                      likes your recent status

                      Nusja Nawancali new
                      downloaded your work

                      Nusja Nawancali new
                      send you 2 messages

See All Notifications

              <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

                John Doe

              </button>

 My Profile

 Account Settings

 Help

 Log Out

            <button id="chatview" class="btn btn-default tp-icon chat-icon">

            </button>

 Media Manager Subtitle goes here...

        You are here:

Bracket

Pages

Media Manager

            <input type="checkbox" id="selectall" value="1" />
            Select All

           Email

           Download

           Edit

           Delete

          Show:
          All
          Documents
          Audio
          Images
          Videos

                  <input type="checkbox" id="check1" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

MyDocuments.doc

                Added: Jan 03, 2014

                  <input type="checkbox" id="check2" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

Vegetarian.png

                Added: Jan 02, 2014

                  <input type="checkbox" id="check3" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

DogAnimation.mp4

                Added: Jan 02, 2014

                  <input type="checkbox" id="check7" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

WreckingBall.mp3

                Added: Jan 01, 2014

                  <input type="checkbox" id="check4" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

MyFirstArt.png

                Added: Jan 01, 2014

                  <input type="checkbox" id="check5" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

MyResume.docx

                Added: Jan 01, 2014

                  <input type="checkbox" id="check6" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

MyFirstMovie.mp4

                Added: Jan 01, 2014

                  <input type="checkbox" id="check13" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

MeAndFriends.png

                Added: Jan 01, 2014

                  <input type="checkbox" id="check8" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

IWillSurvive.mp3

                Added: Dec 31, 2013

                  <input type="checkbox" id="check9" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

MyDocuments.doc

                Added: Dec 31, 2013

                  <input type="checkbox" id="check10" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

GreatCity.png

                Added: Dec 30, 2013

                  <input type="checkbox" id="check11" value="1" />

                    <button type="button" class="btn btn-default dropdown-toggle fm-toggle" data-toggle="dropdown">

                    </button>

 Share

 Email

 Edit

 Download

 Delete

InTheSea.mp4

                Added: Dec 30, 2013

            <button class="btn btn-primary btn-block">Upload Files</button>

Folders + Add New Folder

 My Pictures

 Facebook Photos

 My Collection

 Illustrations

 TV Series

 Downloaded Movies

 E-book

Tags

Animation

Design

Trailer

Short Film

Dubstep

Soundtrack

Photography

Macro

Tuturials

Documentation

Online Users

                            Eileen Sideways
                            Los Angeles, CA

                            2
                            Zaham Sindilmaca
                            San Francisco, CA

                            Nusja Nawancali
                            Bangkok, Thailand

                            Renov Leongal
                            Cebu City, Philippines

                            Weno Carasbong
                            Tokyo, Japan

Offline Users

                            Eileen Sideways
                            Los Angeles, CA

                            Zaham Sindilmaca
                            San Francisco, CA

                            Nusja Nawancali
                            Bangkok, Thailand

                            Renov Leongal
                            Cebu City, Philippines

                            Weno Carasbong
                            Tokyo, Japan

                            Renov Leongal
                            Cebu City, Philippines

                            Weno Carasbong
                            Tokyo, Japan

Favorites

                            Eileen Sideways
                            Los Angeles, CA

                            Zaham Sindilmaca
                            San Francisco, CA

                            Nusja Nawancali
                            Bangkok, Thailand

                            Renov Leongal
                            Cebu City, Philippines

                            Weno Carasbong
                            Tokyo, Japan

History

                            Eileen Sideways
                            Hi hello, ctc?... would you mind if I go to your...

                            Zaham Sindilmaca
                            This is to inform you that your product that we...

                            Nusja Nawancali
                            Are you willing to have a long term relat...

Settings

                Show Offline Users

                Enable History

                Show Full Name

                Show Location


text:
<form name="loginForm" ng-submit="vm.submit(loginForm)" novalidate>

        Username
        <input type="text" ng-model="vm.user.username" />

        Password
        <input type="password" ng-model="vm.user.password" />

    <button type="submit">Login</button>
</form>


text:
package gov.hhs.fha.nhinc.docsubmission.inbound;

import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;
import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;

/**
 * @author akong
 *
 */
public interface InboundDocSubmission {

    public RegistryResponseType documentRepositoryProvideAndRegisterDocumentSetB(
            ProvideAndRegisterDocumentSetRequestType body, AssertionType assertion);

}


text:
using Xamarin.Forms;

namespace OnetugMobile.Views
{
    internal static class Styles
    {
        #region Colors

        private static Color Black => Color.Black;

        private static Color LightGray => Color.FromRgb(166, 170, 175);

        private static Color White => Color.White;

        #endregion

        #region Color Mappings

        internal static Color ButtonBackgroundColor => White;

        internal static Color HeaderFooterBackgroundColor => White;

        internal static Color LabelForegroundColor => Black;

        internal static Color NeutralBackgroundColor => LightGray;

        #endregion

        #region Font sizes

        //private static double MediumLabelFontSize =>
        //    Device.GetNamedSize(NamedSize.Medium, typeof(Label));
        internal static double MediumLabelFontSize => 17;

        internal static double LargeLabelFontSize => MediumLabelFontSize * 1.2;

        internal static double SmallLabelFontSize => MediumLabelFontSize / 1.2;

        internal static double ExtraLargeLabelFontSize => LargeLabelFontSize * 1.2;

        internal static double ExtraSmallLabelFontSize => SmallLabelFontSize / 1.2;

        #endregion

        #region Line heights

        internal static double MediumLabelLineHeight => MediumLabelFontSize * 4 / 3;

        internal static double LargeLabelLineHeight => MediumLabelLineHeight * 1.2;

        internal static double SmallLabelLineHeight => MediumLabelLineHeight / 1.2;

        internal static double ExtraLargeLabelLineHeight => LargeLabelLineHeight * 1.2;

        internal static double ExtraSmallLabelLineHeight => SmallLabelLineHeight / 1.2;

        #endregion

        #region Buttons

        internal static Style ButtonStyle => new Style(typeof(Button))
        {
            Setters =
            {
                new Setter
                {
                    // Drop interior border on Windows and Windows Phone
                    Property = Button.BorderColorProperty,
                    Value = Color.Transparent
                },
                new Setter
                {
                    Property = Button.FontSizeProperty,
                    Value = LargeLabelFontSize
                },
                new Setter
                {
                    Property = Button.TextColorProperty,
                    Value = LabelForegroundColor
                },
                new Setter
                {
                    Property = View.HorizontalOptionsProperty,
                    Value = LayoutOptions.Center
                },
                new Setter
                {
                    Property = View.VerticalOptionsProperty,
                    Value = LayoutOptions.Center
                },
                new Setter
                {
                    Property = VisualElement.BackgroundColorProperty,
                    Value = ButtonBackgroundColor
                },
                new Setter
                {
                    Property = VisualElement.HeightRequestProperty,
                    Value = 100     // TODO Make this dynamic
                },
                new Setter
                {
                    Property = VisualElement.WidthRequestProperty,
                    Value = 200     // TODO Make this dynamic
                }
            }
        };

        #endregion

        #region Labels

        private static Style LabelStyle => new Style(typeof (Label))
        {
            Setters =
            {
                new Setter
                {
                    Property = Label.TextColorProperty,
                    Value = LabelForegroundColor
                }
            }
        };

        internal static Style MediumLabelStyle => new Style(typeof (Label))
        {
            BasedOn = LabelStyle,
            Setters =
            {
                new Setter
                {
                    Property = Label.FontSizeProperty,
                    Value = MediumLabelFontSize
                }
            }
        };

        internal static Style LargeLabelStyle => new Style(typeof (Label))
        {
            BasedOn = LabelStyle,
            Setters =
            {
                new Setter
                {
                    Property = Label.FontSizeProperty,
                    Value = LargeLabelFontSize
                }
            }
        };

        internal static Style LargeBoldLabelStyle => new Style(typeof (Label))
        {
            BasedOn = LargeLabelStyle,
            Setters =
            {
                new Setter
                {
                    Property = Label.FontAttributesProperty,
                    Value = FontAttributes.Bold
                }
            }
        };

        #endregion

        #region StackLayout

        internal static Style ContentStackStyle => new Style(typeof (StackLayout))
        {
            Setters =
            {
                new Setter
                {
                    Property = StackLayout.SpacingProperty,
                    Value = 0
                },
                new Setter
                {
                    Property = VisualElement.BackgroundColorProperty,
                    Value = NeutralBackgroundColor
                }
            }
        };

        private static Style HeaderFooterStackStyle => new Style(typeof (StackLayout))
        {
            Setters =
            {
                new Setter
                {
                    Property = StackLayout.OrientationProperty,
                    Value = StackOrientation.Horizontal
                }
            }
        };

        internal static Style HeaderFooterInnerStackStyle => new Style(typeof (StackLayout))
        {
            BasedOn = HeaderFooterStackStyle,
            Setters =
            {
                new Setter
                {
                    Property = View.HorizontalOptionsProperty,
                    Value = LayoutOptions.CenterAndExpand
                },
                new Setter
                {
                    Property = View.VerticalOptionsProperty,
                    Value = LayoutOptions.CenterAndExpand
                }
            }
        };

        internal static Style HeaderFooterOuterStackStyle => new Style(typeof (StackLayout))
        {
            BasedOn = HeaderFooterStackStyle,
            Setters =
            {
                new Setter
                {
                    Property = View.HorizontalOptionsProperty,
                    Value = LayoutOptions.FillAndExpand
                },
                new Setter
                {
                    Property = VisualElement.BackgroundColorProperty,
                    Value = HeaderFooterBackgroundColor
                }
            }
        };

        internal static Style FooterOuterStackStyle => new Style(typeof (StackLayout))
        {
            BasedOn = HeaderFooterOuterStackStyle,
            Setters =
            {
                new Setter
                {
                    Property = View.VerticalOptionsProperty,
                    Value = LayoutOptions.End
                }
            }
        };

        internal static Style HeaderOuterStackStyle => new Style(typeof (StackLayout))
        {
            BasedOn = HeaderFooterOuterStackStyle,
            Setters =
            {
                new Setter
                {
                    Property = View.VerticalOptionsProperty,
                    Value = LayoutOptions.Start
                }
            }
        };

        #endregion
    }
}


text:
var detective = require('detective');
var resolve = require('resolve');
var fs = require('fs');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var complexityCost = require('./lib/complexity');
var syntaxError = require('syntax-error');
var commondir = require('commondir');

module.exports = function (dirs, cb) {
    if (!Array.isArray(dirs)) dirs = [ dirs ];

    dirs = dirs.map(function (d) {
        return path.resolve(d);
    });
    var dir = commondir(dirs);

    var emitter = new EventEmitter;

    emitter.total = 0;

    if (typeof cb === 'function') {
        var gotErrors = false;
        emitter.once('error', function (err) {
            gotErrors = true;
            cb(err);
        });

        emitter.on('end', function () {
            if (!gotErrors) cb(null, emitter.total);
        });
    }

    function record (price, desc) {
        emitter.total += price;
        emitter.emit('price', price, desc);
        emitter.emit('total', emitter.total);
    }

    var files = dirs.map(function (d) {
        return require.resolve(/\.js$/.test(d) ? d : d + '/')
    });

    process.nextTick(function (file) {
        record(100, 'initial stipend');

        (function next () {
            if (files.length === 0) {
                emitter.emit('end', emitter.total);
            }
            else walk(files.shift(), next)
        })();
    });

    var walked = {};

    function walk (file, fn) {
        if (walked[file]) return fn();
        walked[file] = true;

        fs.readFile(file, 'utf8', function (err, src) {
            if (err) return emitter.emit('error', err);
            src = src.replace(/^#![^\n]*/, '');
            src = '(function(){' + src + '})()';

            var e = syntaxError(src, file);
            if (e) return emitter.emit('error', e);

            var rel = path.relative(dir, file);
            var costs = complexityCost(src);

            var sum = Object.keys(costs).sort().reduce(function (acc, key) {
                record(costs[key], key + ' cost for ' + rel);
                return acc + costs[key];
            }, 0);

            var deps = detective.find(src);

            deps.expressions.forEach(function (s) {
                record(-10, 'require(' + s + ') in ' + rel);
                emitter.emit('error', 'expression: require(' + s + ')'
                    + ' in file ' + file
                );
            });

            emitter.emit('file', sum, rel);

            var ds = deps.strings
                .filter(function (s) {
                    return /^[\.\/]/.test(s) && !/\.json$/.test(s)
                })
                .map(function (s) {
                    try {
                        return resolve.sync(s, {
                            basedir : path.dirname(file)
                        });
                    }
                    catch (err) {
                        emitter.emit('error', err + ' in file ' + file);
                        record(-100, 'path resolution error for '
                            + s + ' in ' + rel
                        );
                        return;
                    }
                })
                .filter(Boolean)
                .filter(function (s) { return !walked[s] })
            ;
            (function next () {
                if (ds.length === 0) fn()
                else walk(ds.shift(), next);
            })();
        });
    }

    return emitter;
};


text:
var restify = require('./express-restify-mongoose.js');
var AllowedUser = require('../models/user.js').AllowedUser;

// this function should be called in app.js as userRestify(app, config)
module.exports = function(app, config) {

  restify.serve(app, AllowedUser, {

    // only admin is allowed for all type of requests except GET
    prereq: function(req) {
      if(req.isAuthenticated()) {
        if(config.admins && config.admins.indexOf(req.user.email) !== -1) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },

    contextFilter: function(model, req, callback) {

      if(req.user) {
        if(config.admins && config.admins.indexOf(req.user.email) !== -1) {
          callback(model);
        } else {
          callback(model.find({
            isPublic: true
          }));
        }
      } else {
        callback(model.find({
          isPublic: true
        }));
      }

    }

  });

}


text:
package vektah.rust.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface RustTraitImplements extends PsiElement {

  @NotNull
  List<RustFunctionType> getFunctionTypeList();

  @NotNull
  List<RustTypeBasic> getTypeBasicList();

  @NotNull
  List<RustTypeClosure> getTypeClosureList();

  @NotNull
  List<RustTypeProc> getTypeProcList();

  @NotNull
  List<RustTypeTuple> getTypeTupleList();

  @NotNull
  List<RustTypeUnit> getTypeUnitList();

  @NotNull
  List<RustTypeVector> getTypeVectorList();

}


text:
/*-----------------------------------------------------------------------/
/  Low level disk interface modlue include file   (C)ChaN, 2013          /
/-----------------------------------------------------------------------*/

#ifndef _DISKIO_DEFINED
#define _DISKIO_DEFINED

#define _USE_WRITE	1	/* 1: Enable disk_write function */
#define _USE_IOCTL	1	/* 1: Enable disk_ioctl fucntion */

#include "integer.h"
#include "defines.h"
#include "attributes.h"
#include "ffconf.h"

/* Status of Disk Functions */
typedef BYTE DSTATUS;

/* Results of Disk Functions */
typedef enum {
	RES_OK = 0,		/* 0: Successful */
	RES_ERROR,		/* 1: R/W Error */
	RES_WRPRT,		/* 2: Write Protected */
	RES_NOTRDY,		/* 3: Not Ready */
	RES_PARERR		/* 4: Invalid Parameter */
} DRESULT;

/*---------------------------------------*/
/* Prototypes for disk control functions */

/* FATFS related */
DSTATUS disk_initialize(BYTE pdrv);
DSTATUS disk_status(BYTE pdrv);
DRESULT disk_read(BYTE pdrv, BYTE* buff, DWORD sector, UINT count);
DRESULT disk_write(BYTE pdrv, const BYTE* buff, DWORD sector, UINT count);
DRESULT disk_ioctl(BYTE pdrv, BYTE cmd, void* buff);

/* Driver related functions */
typedef struct {
	DSTATUS (*disk_initialize)(void);
	DSTATUS (*disk_status)(void);
	DRESULT (*disk_ioctl)(BYTE, void *);
	DRESULT (*disk_write)(const BYTE *, DWORD, UINT);
	DRESULT (*disk_read)(BYTE *, DWORD, UINT);
} DISKIO_LowLevelDriver_t;

/**
 * @brief  Custom drivers for fatfs
 */
typedef enum {
	TM_FATFS_Driver_USER1 = 0x07, /*!< Use USER1: when mounting and other stuff to access to this driver. USER1 is a logical string name of your drive */
	TM_FATFS_Driver_USER2 = 0x08  /*!< User USER2: when mounting and other stuff to access to this driver. USER2 is a logical string name of your drive */
} TM_FATFS_Driver_t;

/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT		0x01	/* Drive not initialized */
#define STA_NODISK		0x02	/* No medium in the drive */
#define STA_PROTECT		0x04	/* Write protected */

/* Command code for disk_ioctrl function */
/* Generic command (used by FatFs) */
#define CTRL_SYNC			0	/* Flush disk cache (for write functions) */
#define GET_SECTOR_COUNT	1	/* Get media size (for only f_mkfs()) */
#define GET_SECTOR_SIZE		2	/* Get sector size (for multiple sector size (_MAX_SS >= 1024)) */
#define GET_BLOCK_SIZE		3	/* Get erase block size (for only f_mkfs()) */
#define CTRL_ERASE_SECTOR	4	/* Force erased a block of sectors (for only _USE_ERASE) */

/* Generic command (not used by FatFs) */
#define CTRL_POWER			5	/* Get/Set power status */
#define CTRL_LOCK			6	/* Lock/Unlock media removal */
#define CTRL_EJECT			7	/* Eject media */
#define CTRL_FORMAT			8	/* Create physical format on the media */

/* MMC/SDC specific ioctl command */
#define MMC_GET_TYPE		10	/* Get card type */
#define MMC_GET_CSD			11	/* Get CSD */
#define MMC_GET_CID			12	/* Get CID */
#define MMC_GET_OCR			13	/* Get OCR */
#define MMC_GET_SDSTAT		14	/* Get SD status */

/* ATA/CF specific ioctl command */
#define ATA_GET_REV			20	/* Get F/W revision */
#define ATA_GET_MODEL		21	/* Get model name */
#define ATA_GET_SN			22	/* Get serial number */

/* MMC card type flags (MMC_GET_TYPE) */
#define CT_MMC		0x01		/* MMC ver 3 */
#define CT_SD1		0x02		/* SD ver 1 */
#define CT_SD2		0x04		/* SD ver 2 */
#define CT_SDC		(CT_SD1|CT_SD2)	/* SD */
#define CT_BLOCK	0x08		/* Block addressing */

/* SDCARD block size */
#define SD_BLOCK_SIZE     512

/**
 * @brief  Adds new driver for DISKIO fatfs structure
 * @param  *Driver: Pointer to @ref DISKIO_LowLevelDriver_t with filled structure
 * @param  DriverName: User can use 2 custom drivers. This parameter can be a value of @ref TM_FATFS_Driver_t enumeration
 * @retval None
 */
void TM_FATFS_AddDriver(DISKIO_LowLevelDriver_t* Driver, TM_FATFS_Driver_t DriverName);

/* Drivers function declarations */
DSTATUS TM_FATFS_SD_SDIO_disk_initialize(void);
DSTATUS TM_FATFS_SD_disk_initialize(void);
DSTATUS TM_FATFS_USBFS_disk_initialize(void);
DSTATUS TM_FATFS_USBHS_disk_initialize(void);
DSTATUS TM_FATFS_SDRAM_disk_initialize(void);
DSTATUS TM_FATFS_SPI_FLASH_disk_initialize(void);

DSTATUS TM_FATFS_SD_SDIO_disk_status(void);
DSTATUS TM_FATFS_SD_disk_status(void);
DSTATUS TM_FATFS_USBFS_disk_status(void);
DSTATUS TM_FATFS_USBHS_disk_status(void);
DSTATUS TM_FATFS_SDRAM_disk_status(void);
DSTATUS TM_FATFS_SPI_FLASH_disk_status(void);

DRESULT TM_FATFS_SD_SDIO_disk_ioctl(BYTE cmd, void *buff);
DRESULT TM_FATFS_SD_disk_ioctl(BYTE cmd, void *buff);
DRESULT TM_FATFS_USBFS_disk_ioctl(BYTE cmd, void *buff);
DRESULT TM_FATFS_USBHS_disk_ioctl(BYTE cmd, void *buff);
DRESULT TM_FATFS_SDRAM_disk_ioctl(BYTE cmd, void *buff);
DRESULT TM_FATFS_SPI_FLASH_disk_ioctl(BYTE cmd, void *buff);

DRESULT TM_FATFS_SD_SDIO_disk_read(BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_SD_disk_read(BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_USBFS_disk_read(BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_USBHS_disk_read(BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_SDRAM_disk_read(BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_SPI_FLASH_disk_read(BYTE *buff, DWORD sector, UINT count);

DRESULT TM_FATFS_SD_SDIO_disk_write(const BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_SD_disk_write(const BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_USBFS_disk_write(const BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_USBHS_disk_write(const BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_SDRAM_disk_write(const BYTE *buff, DWORD sector, UINT count);
DRESULT TM_FATFS_SPI_FLASH_disk_write(const BYTE *buff, DWORD sector, UINT count);

#endif


text:
cask "modern-csv" do
  version "1.3.23"
  sha256 "bdd88d974d317daadc8fb129de8f059c5ae66da57628be87c0bfe636e507c058"

  url "https://www.moderncsv.com/release/ModernCSV-Mac-v#{version}.dmg"
  appcast "https://www.moderncsv.com/latest-version/"
  name "Modern CSV"
  desc "CSV editor"
  homepage "https://www.moderncsv.com/"

  app "Modern CSV.app"

  zap trash: "~/Library/Application Support/Modern CSV"
end


text:
package com.flaptor.indextank.index.scorer;

import java.util.Collection;

import com.flaptor.indextank.index.DocId;
import com.flaptor.indextank.index.scorer.DynamicDataManager.DynamicData;
import com.flaptor.indextank.query.QueryVariables;
import com.flaptor.util.Pair;
import com.google.common.collect.Multimap;

public class VariablesRangeFilter implements MatchFilter {
	private DynamicDataManager dynamicDataManager;
	/**
	 * The ranges apply considering both ends as inclusive and using OR to
	 * join filters for the same variable and AND for different variables.
	 */
	private Multimap<Integer, Pair<Float, Float>> ranges;
	public static MatchFilter NO_FILTER = new NoneMatchFilter();

	public VariablesRangeFilter(DynamicDataManager dynamicDataManager,	Multimap<Integer, Pair<Float, Float>> ranges) {
		this.dynamicDataManager = dynamicDataManager;
		this.ranges = ranges;
	}

	@Override
	public boolean matches(DocId documentId, double textualScore, int now, QueryVariables queryVars) {
		DynamicData dynamicData = dynamicDataManager.getDynamicData(documentId);
		for (Integer variable : ranges.keySet()) {
			if (!checkVariable(dynamicData.getBoost(variable), ranges.get(variable))) {
				return false;
			}
		}
		return true;
	}

	private boolean checkVariable(Float value, Collection<Pair<Float, Float>> ranges) {
		for (Pair<Float, Float> range : ranges) {
			if ((range.first() == null || value >= range.first()) && (range.last() == null || value <= range.last())) {
				return true;
			}
		}
		return false;
	}
}


text:
const clone = require('lodash/clone');
const cloneDeep = require('lodash/cloneDeep');

describe('clone', () => {
  it('should clone objects', () => {
    let object = {
      a: 1,
      b: 2,
      c: {
        d: 0,
      }
    };
    let result = clone(object);
    expect(result).toEqual(object);
    expect(result).not.toBe(object);
    expect(result.c).toBe(object.c);

    result = cloneDeep(object);
    expect(result).toEqual(object);
    expect(result).not.toBe(object);
    expect(result.c).not.toBe(object.c);
  });
});


text:
package org.apache.xmlbeans.impl.schema;

import org.apache.xmlbeans.*;
import org.apache.xmlbeans.impl.common.NameUtil;

import javax.xml.namespace.QName;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import static org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.*;

class SchemaTypePool {
    private final SchemaTypeSystemImpl typeSystem;
    private final Map<String, SchemaComponent.Ref> _handlesToRefs = new LinkedHashMap<>();
    // populated on write
    private final Map<SchemaComponent, String> _componentsToHandles = new LinkedHashMap<>();
    private boolean _started;

    /**
     * Constructs an empty HandlePool to be populated.
     */
    SchemaTypePool(SchemaTypeSystemImpl typeSystem) {
        this.typeSystem = typeSystem;
    }

    private String addUniqueHandle(SchemaComponent obj, String base) {
        // we lowercase handles because of case-insensitive Windows filenames!!!
        base = base.toLowerCase(Locale.ROOT);
        String handle = base;
        for (int index = 2; _handlesToRefs.containsKey(handle); index++) {
            handle = base + index;
        }
        _handlesToRefs.put(handle, obj.getComponentRef());
        _componentsToHandles.put(obj, handle);
        return handle;
    }

    String handleForComponent(SchemaComponent comp) {
        if (comp == null) {
            return null;
        }
        if (comp.getTypeSystem() != typeSystem) {
            throw new IllegalArgumentException("Cannot supply handles for types from another type system");
        }
        if (comp instanceof SchemaType) {
            return handleForType((SchemaType) comp);
        }
        if (comp instanceof SchemaGlobalElement) {
            return handleForElement((SchemaGlobalElement) comp);
        }
        if (comp instanceof SchemaGlobalAttribute) {
            return handleForAttribute((SchemaGlobalAttribute) comp);
        }
        if (comp instanceof SchemaModelGroup) {
            return handleForModelGroup((SchemaModelGroup) comp);
        }
        if (comp instanceof SchemaAttributeGroup) {
            return handleForAttributeGroup((SchemaAttributeGroup) comp);
        }
        if (comp instanceof SchemaIdentityConstraint) {
            return handleForIdentityConstraint((SchemaIdentityConstraint) comp);
        }
        throw new IllegalStateException("Component type cannot have a handle");
    }

    String handleForElement(SchemaGlobalElement element) {
        if (element == null) {
            return null;
        }
        if (element.getTypeSystem() != typeSystem) {
            throw new IllegalArgumentException("Cannot supply handles for types from another type system");
        }
        String handle = _componentsToHandles.get(element);
        if (handle == null) {
            handle = addUniqueHandle(element, NameUtil.upperCamelCase(element.getName().getLocalPart()) + "Element");
        }
        return handle;
    }

    String handleForAttribute(SchemaGlobalAttribute attribute) {
        if (attribute == null) {
            return null;
        }
        if (attribute.getTypeSystem() != typeSystem) {
            throw new IllegalArgumentException("Cannot supply handles for types from another type system");
        }
        String handle = _componentsToHandles.get(attribute);
        if (handle == null) {
            handle = addUniqueHandle(attribute, NameUtil.upperCamelCase(attribute.getName().getLocalPart()) + "Attribute");
        }
        return handle;
    }

    String handleForModelGroup(SchemaModelGroup group) {
        if (group == null) {
            return null;
        }
        if (group.getTypeSystem() != typeSystem) {
            throw new IllegalArgumentException("Cannot supply handles for types from another type system");
        }
        String handle = _componentsToHandles.get(group);
        if (handle == null) {
            handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "ModelGroup");
        }
        return handle;
    }

    String handleForAttributeGroup(SchemaAttributeGroup group) {
        if (group == null) {
            return null;
        }
        if (group.getTypeSystem() != typeSystem) {
            throw new IllegalArgumentException("Cannot supply handles for types from another type system");
        }
        String handle = _componentsToHandles.get(group);
        if (handle == null) {
            handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "AttributeGroup");
        }
        return handle;
    }

    String handleForIdentityConstraint(SchemaIdentityConstraint idc) {
        if (idc == null) {
            return null;
        }
        if (idc.getTypeSystem() != typeSystem) {
            throw new IllegalArgumentException("Cannot supply handles for types from another type system");
        }
        String handle = _componentsToHandles.get(idc);
        if (handle == null) {
            handle = addUniqueHandle(idc, NameUtil.upperCamelCase(idc.getName().getLocalPart()) + "IdentityConstraint");
        }
        return handle;
    }

    String handleForType(SchemaType type) {
        if (type == null) {
            return null;
        }
        if (type.getTypeSystem() != typeSystem) {
            throw new IllegalArgumentException("Cannot supply handles for types from another type system");
        }
        String handle = _componentsToHandles.get(type);
        if (handle == null) {
            QName name = type.getName();
            String suffix = "";
            if (name == null) {
                if (type.isDocumentType()) {
                    name = type.getDocumentElementName();
                    suffix = "Doc";
                } else if (type.isAttributeType()) {
                    name = type.getAttributeTypeAttributeName();
                    suffix = "AttrType";
                } else if (type.getContainerField() != null) {
                    name = type.getContainerField().getName();
                    suffix = type.getContainerField().isAttribute() ? "Attr" : "Elem";
                }
            }

            String baseName;
            String uniq = Integer.toHexString(type.toString().hashCode() | 0x80000000).substring(4).toUpperCase(Locale.ROOT);
            if (name == null) {
                baseName = "Anon" + uniq + "Type";
            } else {
                baseName = NameUtil.upperCamelCase(name.getLocalPart()) + uniq + suffix + "Type";
            }

            handle = addUniqueHandle(type, baseName);
        }

        return handle;
    }

    SchemaComponent.Ref refForHandle(String handle) {
        if (handle == null) {
            return null;
        }

        return _handlesToRefs.get(handle);
    }

    void startWriteMode() {
        _started = true;
        _componentsToHandles.clear();
        for (String handle : _handlesToRefs.keySet()) {
            SchemaComponent comp = _handlesToRefs.get(handle).getComponent();
            _componentsToHandles.put(comp, handle);
        }
    }

    void writeHandlePool(XsbReader reader) {
        reader.writeShort(_componentsToHandles.size());
        _componentsToHandles.forEach((comp, handle) -> {
            reader.writeString(handle);
            reader.writeShort(fileTypeFromComponentType(comp.getComponentType()));
        });
    }

    int fileTypeFromComponentType(int componentType) {
        switch (componentType) {
            case SchemaComponent.TYPE:
                return SchemaTypeSystemImpl.FILETYPE_SCHEMATYPE;
            case SchemaComponent.ELEMENT:
                return SchemaTypeSystemImpl.FILETYPE_SCHEMAELEMENT;
            case SchemaComponent.ATTRIBUTE:
                return SchemaTypeSystemImpl.FILETYPE_SCHEMAATTRIBUTE;
            case SchemaComponent.MODEL_GROUP:
                return SchemaTypeSystemImpl.FILETYPE_SCHEMAMODELGROUP;
            case SchemaComponent.ATTRIBUTE_GROUP:
                return SchemaTypeSystemImpl.FILETYPE_SCHEMAATTRIBUTEGROUP;
            case SchemaComponent.IDENTITY_CONSTRAINT:
                return SchemaTypeSystemImpl.FILETYPE_SCHEMAIDENTITYCONSTRAINT;
            default:
                throw new IllegalStateException("Unexpected component type");
        }
    }

    void readHandlePool(XsbReader reader) {
        if (_handlesToRefs.size() != 0 || _started) {
            throw new IllegalStateException("Nonempty handle set before read");
        }

        int size = reader.readShort();
        for (int i = 0; i < size; i++) {
            String handle = reader.readString();
            int code = reader.readShort();
            SchemaComponent.Ref result;
            switch (code) {
                case FILETYPE_SCHEMATYPE:
                    result = new SchemaType.Ref(typeSystem, handle);
                    break;
                case FILETYPE_SCHEMAELEMENT:
                    result = new SchemaGlobalElement.Ref(typeSystem, handle);
                    break;
                case FILETYPE_SCHEMAATTRIBUTE:
                    result = new SchemaGlobalAttribute.Ref(typeSystem, handle);
                    break;
                case FILETYPE_SCHEMAMODELGROUP:
                    result = new SchemaModelGroup.Ref(typeSystem, handle);
                    break;
                case FILETYPE_SCHEMAATTRIBUTEGROUP:
                    result = new SchemaAttributeGroup.Ref(typeSystem, handle);
                    break;
                case FILETYPE_SCHEMAIDENTITYCONSTRAINT:
                    result = new SchemaIdentityConstraint.Ref(typeSystem, handle);
                    break;
                default:
                    throw new SchemaTypeLoaderException("Schema index has an unrecognized entry of type " + code, typeSystem.getName(), handle, SchemaTypeLoaderException.UNRECOGNIZED_INDEX_ENTRY);
            }
            _handlesToRefs.put(handle, result);
        }
    }
}


text:
import {StorageProvider} from '../storage-provider';
import {WindowStorageProvider} from '../window-storage-provider';

export const localStorageProviderName = 'localStorage';

export class LocalStorageProvider extends WindowStorageProvider implements StorageProvider {
  protected providerName: string = localStorageProviderName;
}


text:
            <?php foundationPress_top_bar_l(); ?>
            <?php foundationPress_top_bar_r(); ?>

                <a href="<?php echo home_url(); ?>">


text:
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
  var app = new EmberApp({
    inlineContent: {
      'something-inline': {content: "THIS SHOULD SHOW UP IN THE BUILT INDEX"}
    }
  });

  /*
    This build file specifes the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  return app.toTree();
};


text:
using namespace mcld;
using namespace elf_dynamic;

//===----------------------------------------------------------------------===//
// elf_dynamic::EntryIF
//===----------------------------------------------------------------------===//
EntryIF::EntryIF()
{
}

EntryIF::~EntryIF()
{
}

//===----------------------------------------------------------------------===//
// ELFDynamic
//===----------------------------------------------------------------------===//
ELFDynamic::ELFDynamic(const GNULDBackend& pParent,
                       const LinkerConfig& pConfig)
  : m_pEntryFactory(NULL), m_Backend(pParent), m_Config(pConfig), m_Idx(0) {
  // FIXME: support big-endian machine.
  if (m_Config.targets().is32Bits()) {
    if (m_Config.targets().isLittleEndian())
      m_pEntryFactory = new Entry<32, true>();
  } else if (m_Config.targets().is64Bits()) {
    if (m_Config.targets().isLittleEndian())
      m_pEntryFactory = new Entry<64, true>();
  } else {
    fatal(diag::unsupported_bitclass) << m_Config.targets().triple().str()
                                      << m_Config.targets().bitclass();
  }
}

ELFDynamic::~ELFDynamic()
{
  if (NULL != m_pEntryFactory)
    delete m_pEntryFactory;

  EntryListType::iterator entry, entryEnd = m_EntryList.end();
  for (entry = m_EntryList.begin(); entry != entryEnd; ++entry) {
    if (NULL != *entry)
      delete (*entry);
  }

  entryEnd = m_NeedList.end();
  for (entry = m_NeedList.begin(); entry != entryEnd; ++entry) {
    if (NULL != *entry)
      delete (*entry);
  }
}

size_t ELFDynamic::size() const
{
  return (m_NeedList.size() + m_EntryList.size());
}

size_t ELFDynamic::numOfBytes() const
{
  return size()*entrySize();
}

size_t ELFDynamic::entrySize() const
{
  return m_pEntryFactory->size();
}

void ELFDynamic::reserveOne(uint64_t pTag)
{
  assert(NULL != m_pEntryFactory);
  m_EntryList.push_back(m_pEntryFactory->clone());
}

void ELFDynamic::applyOne(uint64_t pTag, uint64_t pValue)
{
  assert(m_Idx < m_EntryList.size());
  m_EntryList[m_Idx]->setValue(pTag, pValue);
  ++m_Idx;
}

/// reserveEntries - reserve entries
void ELFDynamic::reserveEntries(const ELFFileFormat& pFormat)
{
  if (LinkerConfig::DynObj == m_Config.codeGenType()) {
    reserveOne(llvm::ELF::DT_SONAME); // DT_SONAME

    if (m_Config.options().Bsymbolic())
      reserveOne(llvm::ELF::DT_SYMBOLIC); // DT_SYMBOLIC
  }

  if (pFormat.hasInit())
    reserveOne(llvm::ELF::DT_INIT); // DT_INIT

  if (pFormat.hasFini())
    reserveOne(llvm::ELF::DT_FINI); // DT_FINI

  if (pFormat.hasInitArray()) {
    reserveOne(llvm::ELF::DT_INIT_ARRAY); // DT_INIT_ARRAY
    reserveOne(llvm::ELF::DT_INIT_ARRAYSZ); // DT_INIT_ARRAYSZ
  }

  if (pFormat.hasFiniArray()) {
    reserveOne(llvm::ELF::DT_FINI_ARRAY); // DT_FINI_ARRAY
    reserveOne(llvm::ELF::DT_FINI_ARRAYSZ); // DT_FINI_ARRAYSZ
  }

  if (pFormat.hasHashTab())
    reserveOne(llvm::ELF::DT_HASH); // DT_HASH

  // FIXME: use llvm enum constant
  if (pFormat.hasGNUHashTab())
    reserveOne(0x6ffffef5); // DT_GNU_HASH

  if (pFormat.hasDynSymTab()) {
    reserveOne(llvm::ELF::DT_SYMTAB); // DT_SYMTAB
    reserveOne(llvm::ELF::DT_SYMENT); // DT_SYMENT
  }

  if (pFormat.hasDynStrTab()) {
    reserveOne(llvm::ELF::DT_STRTAB); // DT_STRTAB
    reserveOne(llvm::ELF::DT_STRSZ); // DT_STRSZ
  }

  reserveTargetEntries(pFormat); // DT_PLTGOT

  if (pFormat.hasRelPlt() || pFormat.hasRelaPlt())
    reserveOne(llvm::ELF::DT_PLTREL); // DT_PLTREL

  if (pFormat.hasPLT()) {
    reserveOne(llvm::ELF::DT_JMPREL); // DT_JMPREL
    reserveOne(llvm::ELF::DT_PLTRELSZ); // DT_PLTRELSZ
  }

  if (pFormat.hasRelDyn()) {
    reserveOne(llvm::ELF::DT_REL); // DT_REL
    reserveOne(llvm::ELF::DT_RELSZ); // DT_RELSZ
    reserveOne(llvm::ELF::DT_RELENT); // DT_RELENT
  }

  if (pFormat.hasRelaDyn()) {
    reserveOne(llvm::ELF::DT_RELA); // DT_RELA
    reserveOne(llvm::ELF::DT_RELASZ); // DT_RELASZ
    reserveOne(llvm::ELF::DT_RELAENT); // DT_RELAENT
  }

  uint64_t dt_flags = 0x0;
  if (m_Config.options().hasOrigin())
    dt_flags |= llvm::ELF::DF_ORIGIN;
  if (m_Config.options().Bsymbolic())
    dt_flags |= llvm::ELF::DF_SYMBOLIC;
  if (m_Config.options().hasNow())
    dt_flags |= llvm::ELF::DF_BIND_NOW;
  if (m_Backend.hasTextRel())
    dt_flags |= llvm::ELF::DF_TEXTREL;
  if (m_Backend.hasStaticTLS() &&
      (LinkerConfig::DynObj == m_Config.codeGenType()))
    dt_flags |= llvm::ELF::DF_STATIC_TLS;

  if ((m_Config.options().hasNewDTags() && 0x0 != dt_flags) ||
      0 != (dt_flags & llvm::ELF::DF_STATIC_TLS))
    reserveOne(llvm::ELF::DT_FLAGS); // DT_FLAGS

  if (m_Backend.hasTextRel())
    reserveOne(llvm::ELF::DT_TEXTREL); // DT_TEXTREL

  if (m_Config.options().hasNow()          ||
      m_Config.options().hasLoadFltr()     ||
      m_Config.options().hasOrigin()       ||
      m_Config.options().hasInterPose()    ||
      m_Config.options().hasNoDefaultLib() ||
      m_Config.options().hasNoDump()       ||
      m_Config.options().Bgroup()          ||
      ((LinkerConfig::DynObj == m_Config.codeGenType()) &&
       (m_Config.options().hasNoDelete()  ||
        m_Config.options().hasInitFirst() ||
        m_Config.options().hasNoDLOpen()))) {
    reserveOne(llvm::ELF::DT_FLAGS_1); // DT_FLAGS_1
  }

  reserveOne(llvm::ELF::DT_NULL); // for DT_NULL
}

/// applyEntries - apply entries
void ELFDynamic::applyEntries(const ELFFileFormat& pFormat)
{
  if (LinkerConfig::DynObj == m_Config.codeGenType() &&
      m_Config.options().Bsymbolic()) {
      applyOne(llvm::ELF::DT_SYMBOLIC, 0x0); // DT_SYMBOLIC
  }

  if (pFormat.hasInit())
    applyOne(llvm::ELF::DT_INIT, pFormat.getInit().addr()); // DT_INIT

  if (pFormat.hasFini())
    applyOne(llvm::ELF::DT_FINI, pFormat.getFini().addr()); // DT_FINI

  if (pFormat.hasInitArray()) {
    // DT_INIT_ARRAY
    applyOne(llvm::ELF::DT_INIT_ARRAY, pFormat.getInitArray().addr());

    // DT_INIT_ARRAYSZ
    applyOne(llvm::ELF::DT_INIT_ARRAYSZ, pFormat.getInitArray().size());
  }

  if (pFormat.hasFiniArray()) {
    // DT_FINI_ARRAY
    applyOne(llvm::ELF::DT_FINI_ARRAY, pFormat.getFiniArray().addr());

    // DT_FINI_ARRAYSZ
    applyOne(llvm::ELF::DT_FINI_ARRAYSZ, pFormat.getFiniArray().size());
  }

  if (pFormat.hasHashTab())
    applyOne(llvm::ELF::DT_HASH, pFormat.getHashTab().addr()); // DT_HASH

  // FIXME: use llvm enum constant
  if (pFormat.hasGNUHashTab())
    applyOne(0x6ffffef5, pFormat.getGNUHashTab().addr()); // DT_GNU_HASH

  if (pFormat.hasDynSymTab()) {
    applyOne(llvm::ELF::DT_SYMTAB, pFormat.getDynSymTab().addr()); // DT_SYMTAB
    applyOne(llvm::ELF::DT_SYMENT, symbolSize()); // DT_SYMENT
  }

  if (pFormat.hasDynStrTab()) {
    applyOne(llvm::ELF::DT_STRTAB, pFormat.getDynStrTab().addr()); // DT_STRTAB
    applyOne(llvm::ELF::DT_STRSZ, pFormat.getDynStrTab().size()); // DT_STRSZ
  }

  applyTargetEntries(pFormat); // DT_PLTGOT

  if (pFormat.hasRelPlt()) {
    applyOne(llvm::ELF::DT_PLTREL, llvm::ELF::DT_REL); // DT_PLTREL
    applyOne(llvm::ELF::DT_JMPREL, pFormat.getRelPlt().addr()); // DT_JMPREL
    applyOne(llvm::ELF::DT_PLTRELSZ, pFormat.getRelPlt().size()); // DT_PLTRELSZ
  }
  else if (pFormat.hasRelaPlt()) {
    applyOne(llvm::ELF::DT_PLTREL, llvm::ELF::DT_RELA); // DT_PLTREL
    applyOne(llvm::ELF::DT_JMPREL, pFormat.getRelaPlt().addr()); // DT_JMPREL
    applyOne(llvm::ELF::DT_PLTRELSZ, pFormat.getRelaPlt().size()); // DT_PLTRELSZ
  }

  if (pFormat.hasRelDyn()) {
    applyOne(llvm::ELF::DT_REL, pFormat.getRelDyn().addr()); // DT_REL
    applyOne(llvm::ELF::DT_RELSZ, pFormat.getRelDyn().size()); // DT_RELSZ
    applyOne(llvm::ELF::DT_RELENT, m_pEntryFactory->relSize()); // DT_RELENT
  }

  if (pFormat.hasRelaDyn()) {
    applyOne(llvm::ELF::DT_RELA, pFormat.getRelaDyn().addr()); // DT_RELA
    applyOne(llvm::ELF::DT_RELASZ, pFormat.getRelaDyn().size()); // DT_RELASZ
    applyOne(llvm::ELF::DT_RELAENT, m_pEntryFactory->relaSize()); // DT_RELAENT
  }

  if (m_Backend.hasTextRel()) {
    applyOne(llvm::ELF::DT_TEXTREL, 0x0); // DT_TEXTREL

    if (m_Config.options().warnSharedTextrel() &&
        LinkerConfig::DynObj == m_Config.codeGenType())
      mcld::warning(mcld::diag::warn_shared_textrel);
  }

  uint64_t dt_flags = 0x0;
  if (m_Config.options().hasOrigin())
    dt_flags |= llvm::ELF::DF_ORIGIN;
  if (m_Config.options().Bsymbolic())
    dt_flags |= llvm::ELF::DF_SYMBOLIC;
  if (m_Config.options().hasNow())
    dt_flags |= llvm::ELF::DF_BIND_NOW;
  if (m_Backend.hasTextRel())
    dt_flags |= llvm::ELF::DF_TEXTREL;
  if (m_Backend.hasStaticTLS() &&
      (LinkerConfig::DynObj == m_Config.codeGenType()))
    dt_flags |= llvm::ELF::DF_STATIC_TLS;

  if ((m_Config.options().hasNewDTags() && 0x0 != dt_flags) ||
      0 != (dt_flags & llvm::ELF::DF_STATIC_TLS))
    applyOne(llvm::ELF::DT_FLAGS, dt_flags); // DT_FLAGS

  uint64_t dt_flags_1 = 0x0;
  if (m_Config.options().hasNow())
    dt_flags_1 |= llvm::ELF::DF_1_NOW;
  if (m_Config.options().hasLoadFltr())
    dt_flags_1 |= llvm::ELF::DF_1_LOADFLTR;
  if (m_Config.options().hasOrigin())
    dt_flags_1 |= llvm::ELF::DF_1_ORIGIN;
  if (m_Config.options().hasInterPose())
    dt_flags_1 |= llvm::ELF::DF_1_INTERPOSE;
  if (m_Config.options().hasNoDefaultLib())
    dt_flags_1 |= llvm::ELF::DF_1_NODEFLIB;
  if (m_Config.options().hasNoDump())
    dt_flags_1 |= llvm::ELF::DF_1_NODUMP;
  if (m_Config.options().Bgroup())
    dt_flags_1 |= llvm::ELF::DF_1_GROUP;
  if (LinkerConfig::DynObj == m_Config.codeGenType()) {
    if (m_Config.options().hasNoDelete())
      dt_flags_1 |= llvm::ELF::DF_1_NODELETE;
    if (m_Config.options().hasInitFirst())
      dt_flags_1 |= llvm::ELF::DF_1_INITFIRST;
    if (m_Config.options().hasNoDLOpen())
      dt_flags_1 |= llvm::ELF::DF_1_NOOPEN;
  }
  if (0x0 != dt_flags_1)
    applyOne(llvm::ELF::DT_FLAGS_1, dt_flags_1); // DT_FLAGS_1

  applyOne(llvm::ELF::DT_NULL, 0x0); // for DT_NULL
}

/// symbolSize
size_t ELFDynamic::symbolSize() const
{
  return m_pEntryFactory->symbolSize();
}

/// reserveNeedEntry - reserve on DT_NEED entry.
void ELFDynamic::reserveNeedEntry()
{
  m_NeedList.push_back(m_pEntryFactory->clone());
}

/// emit
void ELFDynamic::emit(const LDSection& pSection, MemoryRegion& pRegion) const
{
  if (pRegion.size() < pSection.size()) {
    llvm::report_fatal_error(llvm::Twine("the given memory is smaller") +
                             llvm::Twine(" than the section's demaind.\n"));
  }

  uint8_t* address = (uint8_t*)pRegion.start();
  EntryListType::const_iterator entry, entryEnd = m_NeedList.end();
  for (entry = m_NeedList.begin(); entry != entryEnd; ++entry)
    address += (*entry)->emit(address);

  entryEnd = m_EntryList.end();
  for (entry = m_EntryList.begin(); entry != entryEnd; ++entry)
    address += (*entry)->emit(address);
}

void ELFDynamic::applySoname(uint64_t pStrTabIdx)
{
  applyOne(llvm::ELF::DT_SONAME, pStrTabIdx); // DT_SONAME
}


text:
import os
import sys
import boto
import boto.cloudformation
import pytest

from f5_aws.config import Config

config = Config().config
region_for_tests = config['regions'][0]

# dynamically get the cfts we want to test
local_cft_path = '/roles/infra/files/'
cfts = [(config['install_path'] + local_cft_path + f) for f in os.listdir(config['install_path']+local_cft_path)]

# scope=module => this setup function will be run once before
#  executing all the test methods in this module
@pytest.fixture(scope="module", params=cfts)
def testenv(request):
    testenv = dict()
    testenv['cf_conn'] = boto.cloudformation.connect_to_region(region_for_tests)
    testenv['cft'] = request.param
    return testenv

def test_cft(testenv):
	template_loc = '' + testenv['cft']
	content = open(template_loc,'r').read()
	testenv['cf_conn'].validate_template(template_body=content)

	# if we got to hear, boto did not throw an exception
	assert True


text:
class SalesforceOrg < ActiveRecord::Base
  default_scope { order('name Asc') }
  attr_accessible :name, :packaged, :password, :sandbox, :token, :username, :disabled, :error_message, :organization_id, :email_addresses, :client_id, :client_secret

  attr_encrypted :username, :attribute => 'username_encrypted', :key => (Rails.application ? Rails.application.config.db_encryption_key : 'r0-wfojomLCbsLqYxDBsHjnEDEMWTo')
  attr_encrypted :password, :attribute => 'password_encrypted', :key => (Rails.application ? Rails.application.config.db_encryption_key : 'r0-wfojomLCbsLqYxDBsHjnEDEMWTo')
  attr_encrypted :token,    :attribute => 'token_encrypted',    :key => (Rails.application ? Rails.application.config.db_encryption_key : 'r0-wfojomLCbsLqYxDBsHjnEDEMWTo')
  attr_encrypted :client_secret,    :attribute => 'client_secret_encrypted',    :key => (Rails.application ? Rails.application.config.db_encryption_key : 'r0-wfojomLCbsLqYxDBsHjnEDEMWTo')

  def disabled=(disabled)
    write_attribute(:error_message, nil) if disabled == '0'
    write_attribute(:disabled, disabled)
  end
end


text:
cask 'dosbox' do
  version '0.74-2'
  sha256 '582d17a29666cc36f9a2bb3804bcba2fadf4d26712ce801b7fbcf3c02f659348'

  # sourceforge.net/dosbox was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/dosbox/dosbox/#{version}/DOSBox-#{version}_Universal.dmg"
  appcast 'https://sourceforge.net/projects/dosbox/rss?path=/dosbox'
  name 'DOSBox'
  homepage 'https://www.dosbox.com/'

  app 'DOSBox.app'

  zap trash: '~/Library/Preferences/DOSBox*'
end


text:
import os
import json
import shutil

from StringIO import StringIO

from cloudify_rest_client.constants import VISIBILITY_EXCEPT_PRIVATE
from cloudify_rest_client.exceptions import (
    DeploymentPluginNotFound,
    UnknownDeploymentInputError,
    UnknownDeploymentSecretError,
    MissingRequiredDeploymentInputError,
    UnsupportedDeploymentGetSecretError,
    CloudifyClientError
)
from . import blueprints
from ..local import load_env
from ..table import print_data, print_single, print_details
from ..cli import cfy, helptexts
from ..logger import get_events_logger, get_global_json_output
from .. import execution_events_fetcher, utils
from ..constants import DEFAULT_BLUEPRINT_PATH, DELETE_DEP
from ..blueprint import get_blueprint_path_and_id
from ..exceptions import (CloudifyCliError,
                          SuppressedCloudifyCliError,
                          ExecutionTimeoutError)
from ..utils import (prettify_client_error,
                     get_visibility,
                     validate_visibility,
                     get_deployment_environment_execution)

DEPLOYMENT_COLUMNS = ['id', 'blueprint_id', 'created_at', 'updated_at',
                      'visibility', 'tenant_name', 'created_by']
DEPLOYMENT_UPDATE_COLUMNS = ['id', 'deployment_id', 'tenant_name', 'state',
                             'execution_id', 'created_at', 'visibility',
                             'old_blueprint_id', 'new_blueprint_id']
TENANT_HELP_MESSAGE = 'The name of the tenant of the deployment'

@cfy.group(name='deployments')
@cfy.options.common_options
def deployments():
    """Handle deployments on the Manager
    """
    pass

@cfy.command(name='list', short_help='List deployments [manager only]')
@cfy.options.blueprint_id()
@cfy.options.sort_by()
@cfy.options.descending
@cfy.options.tenant_name_for_list(
    required=False, resource_name_for_help='deployment')
@cfy.options.all_tenants
@cfy.options.search
@cfy.options.pagination_offset
@cfy.options.pagination_size
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_list(blueprint_id,
                 sort_by,
                 descending,
                 all_tenants,
                 search,
                 pagination_offset,
                 pagination_size,
                 logger,
                 client,
                 tenant_name):
    """List deployments

    If `--blueprint-id` is provided, list deployments for that blueprint.
    Otherwise, list deployments for all blueprints.
    """
    utils.explicit_tenant_name_message(tenant_name, logger)
    if blueprint_id:
        logger.info('Listing deployments for blueprint {0}...'.format(
            blueprint_id))
    else:
        logger.info('Listing all deployments...')

    deployments = client.deployments.list(sort=sort_by,
                                          is_descending=descending,
                                          _all_tenants=all_tenants,
                                          _search=search,
                                          _offset=pagination_offset,
                                          _size=pagination_size,
                                          blueprint_id=blueprint_id)
    total = deployments.metadata.pagination.total
    print_data(DEPLOYMENT_COLUMNS, deployments, 'Deployments:')
    logger.info('Showing {0} of {1} deployments'.format(len(deployments),
                                                        total))

@cfy.command(name='history', short_help='List deployment updates '
                                        '[manager only]')
@cfy.options.deployment_id()
@cfy.options.sort_by()
@cfy.options.descending
@cfy.options.tenant_name_for_list(
    required=False, resource_name_for_help='deployment update')
@cfy.options.all_tenants
@cfy.options.search
@cfy.options.pagination_offset
@cfy.options.pagination_size
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_history(deployment_id,
                    sort_by,
                    descending,
                    all_tenants,
                    search,
                    pagination_offset,
                    pagination_size,
                    logger,
                    client,
                    tenant_name):
    """Show deployment history by listing deployment updates

    If `--deployment-id` is provided, list deployment updates for that
    deployment. Otherwise, list deployment updates for all deployments.
    """
    utils.explicit_tenant_name_message(tenant_name, logger)
    if deployment_id:
        logger.info('Listing deployment updates for deployment {0}...'.format(
            deployment_id))
    else:
        logger.info('Listing all deployment updates...')

    deployment_updates = client.deployment_updates.list(
        sort=sort_by,
        is_descending=descending,
        _all_tenants=all_tenants,
        _search=search,
        _offset=pagination_offset,
        _size=pagination_size,
        deployment_id=deployment_id
    )
    total = deployment_updates.metadata.pagination.total
    print_data(
        DEPLOYMENT_UPDATE_COLUMNS, deployment_updates, 'Deployment updates:')
    logger.info('Showing {0} of {1} deployment updates'.format(
        len(deployment_updates), total))

@cfy.command(
    name='get-update',
    short_help='Retrieve deployment update information [manager only]'
)
@cfy.argument('deployment-update-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False,
                         resource_name_for_help='deployment update')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_get_update(deployment_update_id, logger, client, tenant_name):
    """Retrieve information for a specific deployment update

    `DEPLOYMENT_UPDATE_ID` is the id of the deployment update to get
    information on.
    """
    utils.explicit_tenant_name_message(tenant_name, logger)
    logger.info(
        'Retrieving deployment update {0}...'.format(deployment_update_id))
    deployment_update_dict = client.deployment_updates.get(
        deployment_update_id)
    columns = DEPLOYMENT_UPDATE_COLUMNS
    if get_global_json_output():
        columns += ['old_inputs', 'new_inputs']
    print_single(columns,
                 deployment_update_dict,
                 'Deployment Update:',
                 max_width=50)

    if not get_global_json_output():
        print_details(deployment_update_dict['old_inputs'] or {},
                      'Old inputs:')
        print_details(deployment_update_dict['new_inputs'] or {},
                      'New inputs:')

@cfy.command(name='update', short_help='Update a deployment [manager only]')
@cfy.argument('deployment-id')
@cfy.options.blueprint_path()
@cfy.options.blueprint_filename(' [DEPRECATED]')
@cfy.options.blueprint_id()
@cfy.options.inputs
@cfy.options.reinstall_list
@cfy.options.workflow_id()
@cfy.options.skip_install
@cfy.options.skip_uninstall
@cfy.options.skip_reinstall
@cfy.options.ignore_failure
@cfy.options.install_first
@cfy.options.force(help=helptexts.FORCE_UPDATE)
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.options.visibility(mutually_exclusive_required=False)
@cfy.options.validate
@cfy.options.include_logs
@cfy.options.json_output
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
@cfy.pass_context
def manager_update(ctx,
                   deployment_id,
                   blueprint_path,
                   inputs,
                   reinstall_list,
                   blueprint_filename,
                   skip_install,
                   skip_uninstall,
                   skip_reinstall,
                   ignore_failure,
                   install_first,
                   workflow_id,
                   force,
                   include_logs,
                   json_output,
                   logger,
                   client,
                   tenant_name,
                   blueprint_id,
                   visibility,
                   validate):
    """Update a specified deployment according to the specified blueprint.
    The blueprint can be supplied as an id of a blueprint that already exists
    in the system (recommended).
    The other way (not recommended) is to supply a blueprint to upload and
    use it to update the deployment [DEPRECATED]
    Note: using the deprecated way will upload the blueprint and then use it
    to update the deployment. So doing it twice with the same blueprint may
    fail because the blueprint id in the system will already exist. In this
    case it is better to use the first and recommended way, and simply pass
    the blueprint id.

    `DEPLOYMENT_ID` is the deployment's id to update.
    """
    if not any([blueprint_id, blueprint_path, inputs]):
        raise CloudifyCliError(
            'Must supply either a blueprint (by id of an existing blueprint, '
            'or a path to a new blueprint), or new inputs')
    if (not blueprint_path or not utils.is_archive(blueprint_path)) \
            and blueprint_filename not in (DEFAULT_BLUEPRINT_PATH,
                                           blueprint_path):
        raise CloudifyCliError(
            '--blueprint-filename param should be passed only when updating '
            'from an archive, so --blueprint-path must be passed as a path to '
            'a blueprint archive'
        )

    if blueprint_path:
        logger.warn(
            'DEPRECATED: passing a path to blueprint for deployment update '
            'is deprecated, and it is recommended instead to pass an id of '
            'a blueprint that is already in the system. Note that '
            'the blueprint passed will be added to the system and '
            'then deployment update will start.'
        )
        processed_blueprint_path, blueprint_id = get_blueprint_path_and_id(
            blueprint_path, blueprint_filename, blueprint_id)
        try:
            ctx.invoke(blueprints.upload,
                       blueprint_path=processed_blueprint_path,
                       blueprint_id=blueprint_id,
                       blueprint_filename=blueprint_filename,
                       validate=validate,
                       visibility=visibility,
                       tenant_name=tenant_name)
        finally:
            # Every situation other than the user providing a path of a local
            # yaml means a temp folder will be created that should be later
            # removed.
            if processed_blueprint_path != blueprint_path:
                shutil.rmtree(os.path.dirname(os.path.dirname(
                    processed_blueprint_path)))
    elif tenant_name:
        logger.info('Explicitly using tenant `{0}`'.format(tenant_name))

    msg = 'Updating deployment {0}'.format(deployment_id)
    if inputs:
        msg += ' with new inputs'
    if blueprint_id:
        msg += ', using blueprint {0}'.format(blueprint_id)
    logger.info(msg)
    deployment_update = \
        client.deployment_updates.update_with_existing_blueprint(
            deployment_id,
            blueprint_id,
            inputs,
            skip_install,
            skip_uninstall,
            skip_reinstall,
            workflow_id,
            force,
            ignore_failure,
            install_first,
            list(reinstall_list)
        )
    events_logger = get_events_logger(json_output)
    execution = execution_events_fetcher.wait_for_execution(
        client,
        client.executions.get(deployment_update.execution_id),
        events_handler=events_logger,
        include_logs=include_logs,
        timeout=None  # don't timeout ever
    )

    if execution.error:
        logger.info("Execution of workflow '{0}' for deployment "
                    "'{1}' failed. [error={2}]"
                    .format(execution.workflow_id,
                            execution.deployment_id,
                            execution.error))
        logger.info('Failed updating deployment {dep_id}. Deployment update '
                    'id: {depup_id}. Execution id: {exec_id}'
                    .format(depup_id=deployment_update.id,
                            dep_id=deployment_id,
                            exec_id=execution.id))
        raise SuppressedCloudifyCliError()
    else:
        logger.info("Finished executing workflow '{0}' on deployment "
                    "'{1}'".format(execution.workflow_id,
                                   execution.deployment_id))
        logger.info('Successfully updated deployment {dep_id}. '
                    'Deployment update id: {depup_id}. Execution id: {exec_id}'
                    .format(depup_id=deployment_update.id,
                            dep_id=deployment_id,
                            exec_id=execution.id))

@cfy.command(name='create',
             short_help='Create a deployment [manager only]')
@cfy.argument('deployment-id', required=False, callback=cfy.validate_name)
@cfy.options.blueprint_id(required=True)
@cfy.options.inputs
@cfy.options.private_resource
@cfy.options.visibility()
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
@cfy.options.skip_plugins_validation
def manager_create(blueprint_id,
                   deployment_id,
                   inputs,
                   private_resource,
                   visibility,
                   logger,
                   client,
                   tenant_name,
                   skip_plugins_validation):
    """Create a deployment on the manager.

    `DEPLOYMENT_ID` is the id of the deployment you'd like to create.

    """
    utils.explicit_tenant_name_message(tenant_name, logger)
    logger.info('Creating new deployment from blueprint {0}...'.format(
        blueprint_id))
    deployment_id = deployment_id or blueprint_id
    visibility = get_visibility(private_resource, visibility, logger)

    try:
        deployment = client.deployments.create(
            blueprint_id,
            deployment_id,
            inputs=inputs,
            visibility=visibility,
            skip_plugins_validation=skip_plugins_validation
        )
    except (MissingRequiredDeploymentInputError,
            UnknownDeploymentInputError) as e:
        logger.error('Unable to create deployment: {0}'.format(e.message))
        raise SuppressedCloudifyCliError(str(e))
    except DeploymentPluginNotFound as e:
        logger.info("Unable to create deployment. Not all "
                    "deployment plugins are installed on the Manager.{}"
                    "* Use 'cfy plugins upload' to upload the missing plugins"
                    " to the Manager, or use 'cfy deployments create' with "
                    "the '--skip-plugins-validation' flag "
                    " to skip this validation.".format(os.linesep))
        raise CloudifyCliError(str(e))
    except (UnknownDeploymentSecretError,
            UnsupportedDeploymentGetSecretError) as e:
        logger.info('Unable to create deployment due to invalid secret')
        raise CloudifyCliError(str(e))

    logger.info("Deployment created. The deployment's id is {0}".format(
        deployment.id))

@cfy.command(name='delete',
             short_help='Delete a deployment [manager only]')
@cfy.argument('deployment-id')
@cfy.options.force(help=helptexts.IGNORE_LIVE_NODES)
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_delete(deployment_id, force, logger, client, tenant_name):
    """Delete a deployment from the manager

    `DEPLOYMENT_ID` is the id of the deployment to delete.
    """

    utils.explicit_tenant_name_message(tenant_name, logger)
    logger.info('Trying to delete deployment {0}...'.format(deployment_id))
    client.deployments.delete(deployment_id, force)
    try:
        execution = get_deployment_environment_execution(
            client, deployment_id, DELETE_DEP)
        if execution:
            execution_events_fetcher.wait_for_execution(
                client, execution, timeout=18, logger=logger)

    except ExecutionTimeoutError:
        raise CloudifyCliError(
            'Timed out waiting for deployment `{0}` to be deleted. Please '
            'execute `cfy deployments list` to check whether the '
            'deployment has been deleted.'.format(deployment_id))

    # The deployemnt might be deleted from the DB before we are able to
    # retrieve it, and that's fine
    except CloudifyClientError as e:
        if ('`Deployment` with ID `{0}` was not found'.format(deployment_id)
                in e.message):
            pass

    logger.info("Deployment deleted")

@cfy.command(name='outputs',
             short_help='Show deployment outputs [manager only]')
@cfy.argument('deployment-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_outputs(deployment_id, logger, client, tenant_name):
    """Retrieve outputs for a specific deployment

    `DEPLOYMENT_ID` is the id of the deployment to print outputs for.
    """
    _present_outputs_or_capabilities(
        'outputs',
        deployment_id,
        tenant_name,
        logger,
        client
    )

@cfy.command(name='capabilities',
             short_help='Show deployment capabilities [manager only]')
@cfy.argument('deployment-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_capabilities(deployment_id, logger, client, tenant_name):
    """Retrieve capabilities for a specific deployment

    `DEPLOYMENT_ID` is the id of the deployment to print capabilities for.
    """
    _present_outputs_or_capabilities(
        'capabilities',
        deployment_id,
        tenant_name,
        logger,
        client
    )

def _present_outputs_or_capabilities(
        resource, deployment_id, tenant_name, logger, client
):
    # resource is either "outputs" or "capabilities"

    utils.explicit_tenant_name_message(tenant_name, logger)
    logger.info(
        'Retrieving {0} for deployment {1}...'.format(resource, deployment_id)
    )
    dep = client.deployments.get(deployment_id, _include=[resource])
    definitions = getattr(dep, resource)
    client_api = getattr(client.deployments, resource)
    response = client_api.get(deployment_id)
    values_dict = getattr(response, resource)
    if get_global_json_output():
        values = {out: {
            'value': val,
            'description': definitions[out].get('description')
        } for out, val in values_dict.items()}
        print_details(values, 'Deployment {0}:'.format(resource))
    else:
        values = StringIO()
        for elem_name, elem in values_dict.items():
            values.write(' - "{0}":{1}'.format(elem_name, os.linesep))
            description = definitions[elem_name].get('description', '')
            values.write('     Description: {0}{1}'.format(description,
                                                           os.linesep))
            values.write(
                '     Value: {0}{1}'.format(elem, os.linesep))
        logger.info(values.getvalue())

@cfy.command(name='inputs',
             short_help='Show deployment inputs [manager only]')
@cfy.argument('deployment-id')
@cfy.options.common_options
@cfy.options.tenant_name(required=False, resource_name_for_help='deployment')
@cfy.assert_manager_active()
@cfy.pass_client()
@cfy.pass_logger
def manager_inputs(deployment_id, logger, client, tenant_name):
    """Retrieve inputs for a specific deployment

    `DEPLOYMENT_ID` is the id of the deployment to print inputs for.
    """
    utils.explicit_tenant_name_message(tenant_name, logger)
    logger.info('Retrieving inputs for deployment {0}...'.format(
        deployment_id))
    dep = client.deployments.get(deployment_id, _include=['inputs'])
    if get_global_json_output():
        print_details(dep.inputs, 'Deployment inputs:')
    else:
        inputs_ = StringIO()
        for input_name, input in dep.inputs.items():
            inputs_.write(' - "{0}":{1}'.format(input_name, os.linesep))
            inputs_.write('     Value: {0}{1}'.format(input, os.linesep))
        logger.info(inputs_.getvalue())

@cfy.command(name='set-visibility',
             short_help="Set the deployment's visibility [manager only]")
@cfy.argument('deployment-id')
@cfy.options.visibility(required=True, valid_values=VISIBILITY_EXCEPT_PRIVATE)
@cfy.options.common_options
@cfy.assert_manager_active()
@cfy.pass_client(use_tenant_in_header=True)
@cfy.pass_logger
def manager_set_visibility(deployment_id, visibility, logger, client):
    """Set the deployment's visibility to tenant

    `DEPLOYMENT_ID` is the id of the deployment to update
    """
    validate_visibility(visibility, valid_values=VISIBILITY_EXCEPT_PRIVATE)
    status_codes = [400, 403, 404]
    with prettify_client_error(status_codes, logger):
        client.deployments.set_visibility(deployment_id, visibility)
        logger.info('Deployment `{0}` was set to {1}'.format(deployment_id,
                                                             visibility))

@cfy.command(name='inputs', short_help='Show deployment inputs [locally]')
@cfy.options.common_options
@cfy.options.blueprint_id(required=True, multiple_blueprints=True)
@cfy.pass_logger
def local_inputs(blueprint_id, logger):
    """Display inputs for the execution
    """
    env = load_env(blueprint_id)
    logger.info(json.dumps(env.plan['inputs'] or {}, sort_keys=True, indent=2))

@cfy.command(name='outputs', short_help='Show deployment outputs [locally]')
@cfy.options.common_options
@cfy.options.blueprint_id(required=True, multiple_blueprints=True)
@cfy.pass_logger
def local_outputs(blueprint_id, logger):
    """Display outputs for the execution
    """
    env = load_env(blueprint_id)
    logger.info(json.dumps(env.outputs() or {}, sort_keys=True, indent=2))


text:
<?php
require_once('tools.php');
//echo "http://".$_SERVER['HTTP_HOST'];

?>


text:
layout: post
title: Machine Learning Ex3 - Multivariate Linear Regression
category: statistics
tags:
  - machinelearning
  - R
  - statistics
intro: "Implementation using the normal equations instead of the gradient descent algorithm"
---

<script type="text/javascript" src="http://www.mathjax.org/mathjax/MathJax.js">
    MathJax.Hub.Config({
            jax: ["input/TeX", "output/HTML-CSS"],
        extensions: ["tex2jax.js","TeX/AMSmath.js","TeX/AMSsymbols.js",
                     "TeX/noUndefined.js"],
        tex2jax: {
            inlineMath: [ ["\\(","\\)"] ],
            displayMath: [ ['$$','$$'], ["\\[","\\]"], ["\\begin{displaymath}","\\end{displaymath}"] ],
            skipTags: ["script","noscript","style","textarea","pre","code"],
            ignoreClass: "tex2jax_ignore",
            processEscapes: false,
            processEnvironments: true,
            preview: "TeX"
        },
        showProcessingMessages: true,
        displayAlign: "left",
        displayIndent: "2em",

        "HTML-CSS": {
             scale: 100,
             availableFonts: ["STIX","TeX"],
             preferredFont: "TeX",
             webFont: "TeX",
             imageFont: "TeX",
             showMathMenu: true,
        },
        MMLorHTML: {
             prefer: {
                 MSIE:    "MML",
                 Firefox: "MML",
                 Opera:   "HTML",
                 other:   "HTML"
             }
        }
    });
</script>

[Exercise 3][1] is about multivariate linear regression. Start by finding a
good learning rate (alpha) and then implement linear regression using the
normal equations instead of the gradient descent algorithm.

With implementation in R.

## Data

As usual hosted in google docs:

    google.spreadsheet <- function (key) {
      library(RCurl)
      # ssl validation off
      ssl.verifypeer <- FALSE

      tt <- getForm("https://spreadsheets.google.com/spreadsheet/pub",
                    hl ="en_GB",
                    key = key,
                    single = "true", gid ="0",
                    output = "csv",
                    .opts = list(followlocation = TRUE, verbose = TRUE))

      read.csv(textConnection(tt), header = TRUE)
    }

    # load the data
    mydata = google.spreadsheet("0AnypY27pPCJydExfUzdtVXZuUWphM19vdVBidnFFSWc")

## Feature Scaling

When applying the gradient descent, we need to make sure that features values
are in the same order of magnitudes, otherwise it will not converge well, so
here's a helper function to scale features:

    # given a data frame and the column names i want to scale
    # creates new columns: feature.scale = (feature - mean)/std
    feature.scale = function (dta, cols) {
      for (col in cols) {
        sigma = sd(dta[col])
        mu = mean(dta[col])
        dta[paste(names(dta[col]), ".scale", sep = "")] = (dta[col] - mu)/sigma
      }
      return(dta)
    }

    dta = feature.scale(mydata, c("area", "bedrooms"))
    tail(dta, 5)

       area bedrooms  price area.scale bedrooms.scale
    43 2567        4 314000  0.7126179      1.0904165
    44 1200        3 299000 -1.0075229     -0.2236752
    45  852        2 179900 -1.4454227     -1.5377669
    46 1852        4 299900 -0.1870900      1.0904165
    47 1203        3 239500 -1.0037479     -0.2236752

## Finding Alpha

Recall from [ex2][2] that the gradient descent equation for the updates of
theta is:

<script type="math/tex; mode=display">
\theta := \theta - \alpha \frac{1}{m} x^T (x\theta^T - y)
</script>

For finding a good alpha(\\(\\alpha\\)) we will use a trial and error approach.
The idea is look at how the Cost value \\(J(\\alpha)\\) drops with the number of
iterations, the fastest the drop the better, but if goes up then the alpha
value is already too large.

The Cost is given by(in vectorized form):

<script type="math/tex; mode=display">
J(\theta) = \frac{1}{2m} (X\theta - y)^T (X\theta - y)
</script>

See the lessons on details how to reach that equation.

Implementing:

    # lets try out a few alpha's
    alpha = c(0.03, 0.1, 0.3, 1, 1.3, 2)

    # store the J values over the iterations
    J = array(0,c(50,length(alpha)))
    m = length(dta$price)
    theta = matrix(c(0,0,0), nrow=1)
    x = matrix(c(rep(1,m), dta$area.scale, dta$bedrooms.scale), ncol=3)
    y = matrix(dta$price, ncol=1)

    # the delta updates
    delta = function(x,y,th) {
      delta = (t(x) %*% ((x %*% t(th)) - y))
      return(t(delta))
    }

    # the cost for a given theta
    cost = function(x,y,th,m) {
      prt = ((x %*% t(th)) - y)
      return(1/m * (t(prt) %*% prt))
    }

    # run J for 50x, on each alpha
    for (j in 1:length(alpha)) {
      for (i in 1:50) {
        J[i,j] = cost(x,y,theta,m) # capture the Cost
        theta = theta - alpha[j] * 1/m * delta(x,y,theta)
      }
    }

    # lets have a look
    par(mfrow=c(3,2))
    for (j in 1:length(alpha)) {
      plot(J[,j], type="l", xlab=paste("alpha", alpha[j]), ylab=expression(J(theta)))
    }

![http://al3xandr3.github.com/img/ml-ex3-alpha.png][3]

alpha 1 seems to be the best.

Setting \\(\\alpha=1\\) and running until convergence:

    # running until convergence
    for (i in 1:50000) {
      theta = theta - 1 * 1/m * delta(x,y,theta)
      if (abs(delta(x,y,theta)[2]) < 0.0000001) {
        break # to interrupt updates
      }
    }

    # 1. The final values of theta
    print("Theta:")
    print(theta)

    # 2. The predicted price of a house with 1650 square feet and 3 bedrooms.
    # Don't forget to scale your features when you make this prediction!
    print("Prediction for a house with 1650 square feet and 3 bedrooms:")
    print(theta %*% c(1, (1650 - mean(dta["area"]))/sd(dta["area"]), (3 - mean(dta["bedrooms"]))/sd(dta["bedrooms"])))

     Warning message:
    closing unused connection 3 (tt)
    [1] "Theta:"
             [,1]     [,2]      [,3]
    [1,] 340412.7 110631.1 -6649.474
    [1] "Prediction for a house with 1650 square feet and 3 bedrooms:"
             [,1]
    [1,] 293081.5

## Normal Equations

Given the cost function:

<script type="math/tex; mode=display">
J(\theta) = \frac{1}{2m} \sum_{i=1}^m (h_\theta(x^{(i)}) - y^{(i)})^2
</script>

Recall that this function returns how big is the error of our model vs the
data. Thus our goal is to minimize it. And in order to find its minimum there
is also a more direct approach (instead of using gradient descent) we can just
calculate its derivative set it to 0 and find the value of theta:

<script type="math/tex; mode=display">
\frac{\delta}{\delta \theta_j} J(\theta_j) = 0
</script>

thats for \\(\\theta_j\\). We need of course to account for every j.

If we write it down into matrix notation, calculate its derivatives and set it
to 0, then the value of theta will be obtained with:

<script type="math/tex; mode=display">
\theta =  (X^T X)^{-1} (X^T y)
</script>

That can be easily implemented like so:

    x = matrix(c(rep(1,m), mydata$area, mydata$bedrooms), ncol=3)
    y = matrix(mydata$price, ncol=1)
    theta.normal = solve(t(x) %*% x) %*% (t(x) %*% y)

    # 1. In your program, use the formula above to calculate. Remember that
    # while you don't need to scale your features, you still need to add
    # an intercept term.
    print("Theta:")
    print(theta.normal)

    # 2. Once you have found  from this method, use it to make a price prediction
    # for a 1650-square-foot house with 3 bedrooms. Did you get the same price
    # that you found through gradient descent?
    print("Price prediction for a 1650-square-foot house with 3 bedrooms")
    t(theta.normal) %*%  c(1, 1650, 3)

    [1] "Theta:"
               [,1]
    [1,] 89597.9095
    [2,]   139.2107
    [3,] -8738.0191
    [1] "Price prediction for a 1650-square-foot house with 3 bedrooms"
             [,1]
    [1,] 293081.5

Normal equations are more direct but also more costly than gradient descent to
run, so depending on situation you might need to choose one or the other.

## References

- [OpenClassroom Machine Learning][4]
- [Exercise 3: Multivariate Linear Regression][1]
- Thanks to Andrew Ng and [OpenClassRoom][5] for the great lessons.

   [1]: http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex3/ex3.html
   [2]: http://al3xandr3.github.com/2011/02/24/ml-ex2-linear-regression.html
   [3]: http://al3xandr3.github.com/img/ml-ex3-alpha.png
   [4]: http://openclassroom.stanford.edu/MainFolder/CoursePage.php?course=MachineLearning
   [5]: http://openclassroom.stanford.edu/MainFolder/HomePage.php