text:
class AssetsController < AssetAwareController

  before_action :set_paper_trail_whodunnit, only: [:create, :update], if: :paper_trail_enabled?

  add_breadcrumb "Home", :root_path

  # Set the view variabless form the params @asset_type, @asset_subtype, @search_text, @spatial_filter, @view
  before_action :set_view_vars,     :only => [:index, :map]
  # set the @asset variable before any actions are invoked
  before_action :get_asset,         :only => [:tag, :show, :edit, :copy, :update, :destroy, :summary_info, :add_to_group, :remove_from_group, :popup, :get_dependents, :add_dependents, :get_dependent_subform, :get_subheader]
  before_action :reformat_date_fields,  :only => [:create, :update]
  # Update the vendor_id param if the user is using the vendor_name parameter
  before_action :update_vendor_param,  :only => [:create, :update]

  # Lock down the controller
  authorize_resource only: [:index, :show, :new, :create, :edit, :update, :destroy]

  STRING_TOKENIZER          = '|'

  # Session Variables
  INDEX_KEY_LIST_VAR        = "asset_key_list_cache_var"

  # Returns a JSON array of matching asset subtypes based on a typeahead name or description
  def filter(klass=Rails.application.config.asset_base_class_name.constantize)

    query = params[:query]
    query_str = "%" + query + "%"
    Rails.logger.debug query_str

    matches = []
    assets = klass.where(organization_id: current_user.viewable_organization_ids)
                  .where(params[:search_params])
                  .where("(asset_tag LIKE ? OR object_key LIKE ? OR description LIKE ?)", query_str, query_str, query_str)

    assets.each do |asset|
      matches << {
          "id" => asset.object_key,
          "name" => "#{asset.to_s}: #{asset.description}"
      }
    end

    respond_to do |format|
      format.js { render :json => matches.to_json }
      format.json { render :json => matches.to_json }
    end

  end

  # Adds the asset to the specified group
  def add_to_group
    asset_group = AssetGroup.find_by_object_key(params[:asset_group])
    if asset_group.nil?
      notify_user(:alert, "Can't find the asset group selected.")
    else
      if @asset.asset_groups.exists? asset_group.id
        notify_user(:alert, "Asset #{@asset} is already a member of '#{asset_group}'.")
      else
        @asset.asset_groups << asset_group
        notify_user(:notice, "Asset #{@asset} was added to '#{asset_group}'.")
      end
    end

    # Always display the last view
    redirect_back(fallback_location: root_path)
  end

  # Removes the asset from the specified group
  def remove_from_group
    asset_group = AssetGroup.find_by_object_key(params[:asset_group])
    if asset_group.nil?
      notify_user(:alert, "Can't find the asset group selected.")
    else
      if @asset.asset_groups.exists? asset_group.id
        @asset.asset_groups.delete asset_group
        notify_user(:notice, "Asset #{@asset} was removed from '#{asset_group}'.")
      else
        notify_user(:alert, "Asset #{@asset} is not a member of '#{asset_group}'.")
      end
    end

    # Always display the last view
    redirect_back(fallback_location: root_path)
  end

  # NOT USED
  def parent
    parent_asset = @organization.assets.find_by_object_key(params[:parent_key])
    respond_to do |format|
      format.js   {render :partial => 'assets/asset_details', :locals => { :asset => parent_asset} }
    end
  end

  def get_summary
    asset_type_id = params[:asset_type_id]

    if asset_type_id.blank?
      results = ActiveRecord::Base.connection.exec_query(Rails.application.config.asset_base_class_name.constantize.operational.select('organization_id, asset_subtypes.asset_type_id, organizations.short_name AS org_short_name, asset_types.name AS subtype_name, COUNT(*) AS assets_count, SUM(purchase_cost) AS sum_purchase_cost').joins(:organization, asset_subtype: :asset_type).where(organization_id: @organization_list).group(:organization_id, :asset_type_id).to_sql)
      level = 'type'
    else
      asset_subtype_ids = AssetType.includes(:asset_subtypes).find_by(id: asset_type_id).asset_subtypes.ids
      results = ActiveRecord::Base.connection.exec_query(Rails.application.config.asset_base_class_name.constantize.operational.select('organization_id, asset_subtype_id, organizations.short_name AS org_short_name, asset_subtypes.name AS subtype_name, COUNT(*) AS assets_count, SUM(purchase_cost) AS sum_purchase_cost').joins(:organization, :asset_subtype).where(organization_id: (params[:org] || @organization_list), asset_subtype_id: asset_subtype_ids).group(:organization_id, :asset_subtype_id).to_sql)
      level = 'subtype'
    end

    respond_to do |format|
      format.js {
        if params[:org]
          render partial: 'dashboards/assets_widget_table_rows', locals: {results: results, level: level }
        else
          render partial: 'dashboards/assets_widget_table', locals: {results: results, level: level }
        end
      }
    end
  end

  # renders either a table or map view of a selected list of assets
  #
  # Parameters include asset_type, asset_subtype, id_list, box, or search_text
  #
  def index

    add_index_breadcrumbs

    # disable any spatial filters for this view
    @spatial_filter = nil

    @assets = get_assets

    terminal_crumb = nil
    if @early_disposition
      terminal_crumb = "Early Disposition Proposed"
    elsif @transferred_assets
      terminal_crumb = "Transferred Assets"
    elsif @asset_group.present?
      asset_group = AssetGroup.find_by_object_key(@asset_group)
      terminal_crumb = asset_group
    elsif @search_text.present?
      terminal_crumb = "Search '#{@search_text}'"
    elsif @asset_subtype > 0
      subtype = AssetSubtype.find(@asset_subtype)
      add_breadcrumb subtype.asset_type.name.pluralize(2), inventory_index_path(:asset_type => subtype.asset_type, :asset_subtype => 0)
      terminal_crumb = subtype.name
    elsif @manufacturer_id > 0
      add_breadcrumb "Manufacturers", manufacturers_path
      manufacturer = Manufacturer.find(@manufacturer_id)
      terminal_crumb = manufacturer.name
    elsif @asset_type > 0
      asset_type = AssetType.find(@asset_type)
      terminal_crumb = asset_type.name.pluralize(2)

    end
    add_breadcrumb terminal_crumb if terminal_crumb

    respond_to do |format|
      format.html
      format.js
      format.json {
        render :json => {
          :total => @assets.count,
          :rows =>  index_rows_as_json
          }
        }
      format.xls do
        filename = (terminal_crumb || "unknown").gsub(" ", "_").underscore
        response.headers['Content-Disposition'] = "attachment; filename=#{filename}.xls"
      end
      format.xlsx do
        filename = (terminal_crumb || "unknown").gsub(" ", "_").underscore
        response.headers['Content-Disposition'] = "attachment; filename=#{filename}.xlsx"
      end
    end
  end

  def index_rows_as_json
    multi_sort = params[:multiSort]

    unless (multi_sort.nil?)
      sorting_string = ""

      multi_sort.each { |x|
        sorting_string = sorting_string + "#{x[0]}: :#{x[1]}" if x.all?
      }

    else
      sorting_string = "#{params[:sort]} #{params[:order]}" if [params[:sort], params[:order]].all?
    end

    cache_list(@assets.order(sorting_string), INDEX_KEY_LIST_VAR)

    @assets.order(sorting_string).limit(params[:limit]).offset(params[:offset]).as_json(user: current_user, include_early_disposition: @early_disposition)

  end

  def fire_asset_event_workflow_events

    event_name = params[:event]
    asset_event_type = AssetEventType.find_by(id: params[:asset_event_type_id])

    if asset_event_type && params[:targets]

      notification_enabled = asset_event_type.class_name.constantize.workflow_notification_enabled?

      events = asset_event_type.class_name.constantize.where(object_key: params[:targets].split(','))

      failed = 0
      events.each do |evt|

        if evt.fire_state_event(event_name)
          workflow_event = WorkflowEvent.new
          workflow_event.creator = current_user
          workflow_event.accountable = evt
          workflow_event.event_type = event_name
          workflow_event.save

          if notification_enabled
            evt.notify_event_by(current_user, event_name)
          end

        else
          failed += 1
        end
      end

    end

    redirect_back(fallback_location: root_path)
  end

  # makes a copy of an asset and renders it. The new asset is not saved
  # and has any identifying chracteristics identified as CLEANSABLE_FIELDS are nilled
  def copy

    # add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
    # add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
    # add_breadcrumb @asset.asset_tag, inventory_path(@asset)
    # add_breadcrumb "Copy"

    # create a copy of the asset and null out all the fields that are identified as cleansable
    new_asset = @asset.copy(true)

    notify_user(:notice, "Complete the master record to copy Asset #{@asset.to_s}.")

    @asset = new_asset

    # render the edit view
    respond_to do |format|
      format.html { render :action => "edit" }
      format.json { render :json => @asset }
    end

  end

  # not used
  def summary_info

    respond_to do |format|
      format.js # show.html.erb
      format.json { render :json => @asset }
    end

  end

  def show

    add_breadcrumbs

    # add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
    # add_breadcrumb @asset.asset_tag, inventory_path(@asset)

    # Set the asset class view var. This can be used to determine which view components
    # are rendered, for example, which tabs and action items the user sees
    @asset_class_name = @asset.class.name.underscore

    # get the @prev_record_path and @next_record_path view vars
    get_next_and_prev_object_keys(@asset, INDEX_KEY_LIST_VAR)
    @prev_record_path = @prev_record_key.nil? ? "#" : inventory_path(@prev_record_key, use_last_tab: 1)
    @next_record_path = @next_record_key.nil? ? "#" : inventory_path(@next_record_key, use_last_tab: 1)

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @asset }
    end

  end

  def edit

    # add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
    # add_breadcrumb "#{@asset.asset_subtype.name}", inventory_index_path(:asset_subtype => @asset.asset_subtype)
    # When editing a newly transferred asset this link is invalid so we don't want to show it.
    if @asset.asset_tag == @asset.object_key
      @asset.asset_tag = nil
    else
      add_breadcrumb @asset.asset_tag, inventory_path(@asset)
    end
    add_breadcrumb "Update master record", edit_inventory_path(@asset)

  end

  def update

    #add_breadcrumb "#{@asset.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
    #add_breadcrumb @asset.name, inventory_path(@asset)
    #add_breadcrumb "Modify", edit_inventory_path(@asset)

    # transfered assets need to remove notification if exists
    # if @asset.asset_tag == @asset.object_key
    #   notification = Notification.where("text = 'A new asset has been transferred to you. Please update the asset.' AND link LIKE ?" , "%#{@asset.object_key}%").first
    #   notification.update(active: false) if notification.present?
    # end

    respond_to do |format|
      if @asset.update(new_form_params(@asset))

        # If the asset was successfully updated, schedule update the condition and disposition asynchronously
        #Delayed::Job.enqueue AssetUpdateJob.new(@asset.asset.object_key), :priority => 0
        # See if this asset has any dependents that use its spatial reference
        if @asset.geometry and @asset.occupants.count > 0
          # schedule an update to the spatial references of the dependent assets
          Delayed::Job.enqueue AssetDependentSpatialReferenceUpdateJob.new(@asset.object_key), :priority => 0
        end
        notify_user(:notice, "Asset #{@asset.to_s} was successfully updated.")
        Rails.cache.delete("inventory_api" + @asset.object_key)

        format.html { redirect_to inventory_url(@asset, use_last_tab: 1) }
        format.js { notify_user(:notice, "#{@asset} successfully updated.") }
        format.json { head :no_content }
      else
        format.html { render :action => "edit" }
        format.js { render :action => "edit" }
        if params[:is_xeditable]
          format.json { render :json => {errors: @asset.errors}, :status => :ok }
        else
          format.json { render :json => @asset.errors, :status => :unprocessable_entity }
        end

      end
    end
  end

  def get_subheader
    respond_to do |format|
      format.js
    end
  end

  def get_dependents
    respond_to do |format|
      format.js
      format.json { render :json => @asset.to_json }
    end
  end

  def add_dependents
    params[:asset][:dependents_attributes].each do |key, val|
      unless val[:id]
        dependent = TransamAsset.find_by(object_key: val[:object_key])
        if dependent
          @asset.dependents << dependent
          @asset.update_condition # might need to change to run full AssetUpdateJob
        end
      end
    end

    redirect_back(fallback_location: root_path)
  end

  def get_dependent_subform
    @dependent_subform_target_model = params[:dependent_subform_target_model]

    @dependent = @dependent_subform_target_model.classify.constantize.find_by(object_key: params[:dependent_object_key])

    @dependent_subform_target = params[:dependent_subform_target]
    @dependent_subform_view = params[:dependent_subform_view]

    respond_to do |format|
      format.js
    end

  end

  def new_asset
    authorize! :new, Rails.application.config.asset_base_class_name.constantize

    add_breadcrumb "Add Asset", new_asset_inventory_index_path

  end

  def new

    asset_class_name = params[:asset_seed_class_name] || 'AssetType'

    @asset_class_instance = asset_class_name.constantize.find_by(id: params[:asset_base_class_id])
    if @asset_class_instance.nil?
      notify_user(:alert, "Asset class '#{params[:asset_base_class_id]}' not found. Can't create new asset!")
      redirect_to(root_url)
      return
    end

    #add_breadcrumb "#{asset_subtype.asset_type.name}".pluralize(2), inventory_index_path(:asset_type => asset_subtype.asset_type)
    #add_breadcrumb "#{asset_subtype.name}", inventory_index_path(:asset_subtype => asset_subtype)
    #add_breadcrumb "New", new_inventory_path(asset_subtype)

    # Use the asset class to create an asset of the correct type
    @asset = Rails.application.config.asset_base_class_name.constantize.new_asset(@asset_class_instance, params)

    # See if the user selected an org to associate the asset with
    if params[:organization_id].present?
      @asset.organization = Organization.find(params[:organization_id])
    else
      @asset.organization_id = @organization_list.first
    end

    if params[:parent_id].present?
      @asset.parent_id = params[:parent_id].to_i
    end

    respond_to do |format|
      format.html # new.html.haml this had been an erb and is now an haml the change should just be caught
      format.json { render :json => @asset }
    end
  end

  def create

    asset_class_name = params[:asset_seed_class_name] || 'AssetType'
    if asset_class_name == 'AssetType' && params[:asset][:asset_type_id].blank?
      asset_subtype = AssetSubtype.find_by(id: params[:asset][:asset_subtype_id])
      @asset_class_instance = asset_class_name.constantize.find_by(id: asset_subtype.try(:asset_type_id))
    else
      @asset_class_instance = asset_class_name.constantize.find_by(id: params[:asset][asset_class_name.foreign_key.to_sym])
    end

    if @asset_class_instance.nil?
      notify_user(:alert, "Asset class '#{params[:asset][asset_class_name.foreign_key.to_sym]}' not found. Can't create new asset!")
      redirect_to(root_url)
      return
    end

    # Use the asset class to create an asset of the correct type
    @asset = Rails.application.config.asset_base_class_name.constantize.new_asset(@asset_class_instance, params)
    @asset.attributes = new_form_params(@asset)

    # If the asset does not have an org already defined, set to the default for
    # the user
    if @asset.organization.blank?
      @asset.organization_id = @organization_list.first
    end

    #@asset.creator = current_user
    #@asset.updator = current_user

    #Rails.logger.debug @asset.inspect

    # add_breadcrumb "#{asset_type.name}".pluralize(2), inventory_index_path(:asset_type => asset_subtype.asset_type)
    # add_breadcrumb "#{asset_subtype.name}", inventory_index_path(:asset_subtype => asset_subtype)
    # add_breadcrumb "New", new_inventory_path(asset_subtype)

    respond_to do |format|
      if @asset.save

        # If the asset was successfully saved, schedule update the condition and disposition asynchronously
        #Delayed::Job.enqueue AssetUpdateJob.new(@asset.object_key), :priority => 0

        notify_user(:notice, "Asset #{@asset.to_s} was successfully created.")

        format.html { redirect_to inventory_url(@asset) }
        format.json { render :json => @asset, :status => :created, :location => @asset }
      else
        #Rails.logger.debug @asset.errors.inspect
        format.html { render :action => "new" }
        format.json { render :json => @asset.errors, :status => :unprocessable_entity }
      end
    end
  end

  # called when the user wants to delete an asset
  def destroy

    # make sure we can find the asset we are supposed to be removing and that it belongs to us.
    if @asset.nil?
      redirect_to(root_path, :flash => { :alert => t(:error_404) })
      return
    end

    # Destroy this asset, call backs to remove each associated object will be made
    Rails.cache.delete("inventory_api" + @asset.object_key)
    @asset.destroy

    notify_user(:notice, "Asset was successfully removed.")

    respond_to do |format|
      format.html { redirect_to(inventory_index_url(@asset.class.asset_seed_class_name.foreign_key => @asset.send(@asset.class.asset_seed_class_name.foreign_key))) }
      format.json { head :no_content }
    end

  end

  # Adds the assets to the user's tag list or removes it if the asset
  # is already tagged. called by ajax so no response is rendered
  # NOT USED
  def tag

    if @asset.tagged? current_user
      @asset.users.delete current_user
    else
      @asset.tag current_user
    end

    # No response needed
    render :nothing => true

  end

  # Called via AJAX to get dynamic content via AJAX
  # NOT USED (I think)
  def popup

    str = ""
    if @asset
      str = render_to_string(:partial => "popup", :locals => { :asset => @asset })
    end

    render json: str.to_json

  end

  #------------------------------------------------------------------------------
  #
  # Protected Methods
  #
  #------------------------------------------------------------------------------
  protected
  #
  # Sets the view variables. This is used to set up the vars before a call to get_assets
  #   @asset_type
  #   @asset_subtype
  #   @search_text
  #   @id_filter_list
  #   @spatial_filter
  #   @fmt
  #   @view
  #   @asset_class_name
  #   @filter
  #
  def set_view_vars

    # Check to see if we got an asset group to sub select on. This occurs when the user
    # selects an asset group from the menu selector
    if params[:asset_group].nil? or params[:asset_group] == '0'
      @asset_group = ''
    else
      @asset_group = params[:asset_group]
    end

    # Check to see if we got an asset type to sub select on. This occurs when the user
    # selects an asset type from the drop down
    if params[:asset_type].nil?
      @asset_type =  0
    else
      @asset_type = params[:asset_type].to_i
    end

    # Check to see if we got an asset subtype to sub select on. This will happen if an asset type is selected
    # already and the user selected a subtype from the dropdown.
    if params[:asset_subtype].nil?
      @asset_subtype = 0
    else
      @asset_subtype = params[:asset_subtype].to_i
    end

    # Check to see if we got an organization to sub select on.
    if params[:org_id].nil?
      @org_id = 0
    else
      @org_id = params[:org_id].to_i
    end

    # Check to see if we got a manufacturer to sub select on.
    if params[:manufacturer_id].nil?
      @manufacturer_id = 0
    else
      @manufacturer_id = params[:manufacturer_id].to_i
    end

    # Check to see if we got a service status to sub select on.
    if params[:service_status].nil?
      @service_status = 0
    else
      @service_status = params[:service_status].to_i
    end

    # Check to see if we got a search text and search param to filter on
    if params[:search_text].nil?
      # See if one is stored in the session
      @search_text  = session[:search_text].blank? ?  nil : session[:search_text]
      @search_param = session[:search_param].blank? ? nil : session[:search_param]
    else
      @search_text  = params[:search_text]
      @search_param = params[:search_param]
    end

    # Check to see if we got list of assets to filter on
    if params[:ids]
      #Checks to see if the id list is already an array.  Converts a string to
      # an array if necessary.
      if params[:ids].is_a?(Array)
        @id_filter_list = params[:ids]
      else
        @id_filter_list = params[:ids].split("|")
      end

    else
      @id_filter_list = []
    end

    # Check to see if we got spatial filter. This session variable is managed
    # by the spatial_filter method
    @spatial_filter = session[:spatial_filter]

    # Check to see if we got a different format to render
    if params[:format]
      @fmt = params[:format]
    else
      @fmt = 'html'
    end

    # Check to see if search for early disposition proposed assets only
    if params[:early_disposition] == '1'
      @early_disposition = true
    end
    if params[:transferred_assets] == '1'
      @transferred_assets = true
    end

    # If the asset type is not set we default to the asset base class
    if @id_filter_list.present? or (@asset_type == 0)
      # THIS WILL NO LONGER WORK
      # asset base class name should really be seed to pull typed asset class
      # base class here is just Asset or the new TransamAsset
      @asset_class_name = 'TransamAsset'
    elsif @asset_subtype > 0
      # we have an asset subtype so get it and get the asset type from it. We also set the filter form
      # to the name of the selected subtype
      subtype = AssetSubtype.find(@asset_subtype)
      @asset_type = subtype.asset_type.id
      @asset_class_name = subtype.asset_type.class_name
      @filter = subtype.name
    else
      asset_type = AssetType.find(@asset_type)
      @asset_class_name = asset_type.class_name
    end
    @view = "#{@asset_class_name.underscore}_index"

    Rails.logger.debug "@fmt = #{@fmt}"
    Rails.logger.debug "@asset_type = #{@asset_type}"
    Rails.logger.debug "@asset_subtype = #{@asset_subtype}"
    Rails.logger.debug "@asset_class_name = #{@asset_class_name}"
    Rails.logger.debug "@view = #{@view}"
    Rails.logger.debug "@view = #{@fta_asset_class_id}"

  end

  def add_index_breadcrumbs
    # placeholder
  end

  def add_breadcrumbs
    add_breadcrumb "#{@asset.asset_type.name}".pluralize, inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
    add_breadcrumb "#{@asset.asset_type.name.singularize} Profile"
  end

  def add_old_breadcrumbs
    add_breadcrumb "#{@asset.asset_type.name}".pluralize, inventory_index_path(:asset_type => @asset.asset_type, :asset_subtype => 0)
    add_breadcrumb "#{@asset.asset_type.name.singularize} Profile"
  end

  # returns a list of assets for an index view (index, map) based on user selections. Called after
  # a call to set_view_vars
  def get_assets

    # Create a class instance of the asset type which can be used to perform
    # active record queries
    klass = Object.const_get @asset_class_name
    @asset_class = klass.name

    # here we build the query one clause at a time based on the input params
    clauses = {}
    unless @org_id == 0
      clauses[:organization_id] = @org_id
    else
      clauses[:organization_id] = @organization_list
    end

    unless @manufacturer_id == 0
      clauses[:manufacturer_id] = @manufacturer_id
    end

    if @asset_class_name.constantize.new.respond_to? :disposition_date
      if @disposition_year.blank?
        clauses[:disposition_date] = nil
      else
        clauses['YEAR(disposition_date)'] = @disposition_year
      end
    end

    unless @search_text.blank?
      search_clauses = []
      search_values = []
      # get the list of searchable fields from the asset class
      searchable_fields = klass.new.searchable_fields
      # create an OR query for each field
      query_str = []
      first = true
      # parameterize the search based on the selected search parameter
      search_value = get_search_value(@search_text, @search_param)
      # Construct the query based on the searchable fields for the model
      searchable_fields.each do |field|
        if first
          first = false
          query_str << '('
        else
          query_str << ' OR '
        end

        query_str << field
        query_str << ' LIKE ? '
        # add the value in for this sub clause
        search_values << search_value
      end
      query_str << ')' unless searchable_fields.empty?

      search_clauses << [query_str.join]

      klass = klass.where(search_clauses.join(' AND '), *search_values)
    end

    unless @id_filter_list.blank?
      clauses[:object_key] = @id_filter_list
    end

    unless @asset_subtype == 0
      clauses[:asset_subtype_id] = [@asset_subtype]
    end

    unless @asset_type == 0
      clauses[:asset_types] = {id: @asset_type}
    end

    if klass.respond_to? :in_transfer
      klass = @transferred_assets ? klass.in_transfer : klass.not_in_transfer
    end

    unless @spatial_filter.blank?
      gis_service = GisService.new
      search_box = gis_service.search_box_from_bbox(@spatial_filter)
      wkt = "#{search_box.as_wkt}"

      klass = klass.where('MBRContains(GeomFromText("' + wkt + '"), geometry) = ?', 1)
    end

    # See if we got an asset group. If we did then we can
    # use the asset group collection to filter on instead of creating
    # a new query. This is kind of a hack but works!
    unless @asset_group.blank?
      asset_group = AssetGroup.find_by_object_key(@asset_group)
      klass = asset_group.assets unless asset_group.nil?
    end

    # Search for only early dispostion proposed assets if flag is on
    if @early_disposition
      klass = klass.joins(:early_disposition_requests).where(asset_events: {state: 'new'})
    end

    # send the query
    if @asset_class_name == 'TransamAsset'
      klass = klass.includes({asset_subtype: :asset_type},:organization, :manufacturer)
    else
      join_relations = klass.actable_hierarchy
      join_relations[join_relations.key(:transam_asset)] = {transam_asset: [{asset_subtype: :asset_type},:organization, :manufacturer]}
      klass = klass.includes(join_relations)
    end
    klass.where(clauses)
  end

  # stores the just-created list of asset ids in the session
  def cache_assets(assets)
    list = []
    unless assets.nil?
      assets.each do |a|
        list << a.object_key
      end
    end
    cache_objects(ASSET_KEY_LIST_VAR, list)
  end

  #------------------------------------------------------------------------------
  #
  # Private Methods
  #
  #------------------------------------------------------------------------------
  private

  def paper_trail_enabled?
    SystemConfigExtension.find_by(extension_name: 'PaperTrailAssetAware', active: true).present?
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def form_params
    params.require(:asset).permit(asset_allowable_params)
  end

  def new_form_params(asset)
    params.require(:asset).permit(asset.allowable_params)
  end

  #
  # Overrides the utility method in the base class
  #
  def get_selected_asset(convert=true)
    selected_asset = Rails.application.config.asset_base_class_name.constantize.find_by(:organization_id => @organization_list, :object_key => params[:id]) unless params[:id].blank?
    if convert
      asset = Rails.application.config.asset_base_class_name.constantize.get_typed_asset(selected_asset)
    else
      asset = selected_asset
    end

    return asset
  end

  def reformat_date(date_str)
    # See if it's already in iso8601 format first
    return date_str if date_str.match(/\A\d{4}-\d{2}-\d{2}\z/)

    Date.strptime(date_str, '%m/%d/%Y').strftime('%Y-%m-%d')
  end

  def reformat_date_fields
    params[:asset][:purchase_date] = reformat_date(params[:asset][:purchase_date]) unless params[:asset][:purchase_date].blank?
    params[:asset][:in_service_date] = reformat_date(params[:asset][:in_service_date]) unless params[:asset][:in_service_date].blank?
    params[:asset][:warranty_date] = reformat_date(params[:asset][:warranty_date]) unless params[:asset][:warranty_date].blank?

    # generically update any nested date fields
    params[:asset].keys.select{|k| k.to_s.include? '_components_attributes'}.each do |key|
      params[:asset][key].each do |asset_idx, asset_row|
        params[:asset][key][asset_idx][:purchase_date] = reformat_date(params[:asset][key][asset_idx][:purchase_date]) unless params[:asset][key][asset_idx][:purchase_date].blank?
        params[:asset][key][asset_idx][:in_service_date] = reformat_date(params[:asset][key][asset_idx][:in_service_date]) unless params[:asset][key][asset_idx][:in_service_date].blank?
        params[:asset][key][asset_idx][:warranty_date] = reformat_date(params[:asset][key][asset_idx][:warranty_date]) unless params[:asset][key][asset_idx][:warranty_date].blank?
      end
    end
  end

  # Manage the vendor_id/vendor_name
  def update_vendor_param

    # If the vendor_name is set in the params then the model needs to override the
    # vendor_id param. If both the vendor_id and vendor_name are unset then the
    # model needs to remove the vendor. If the vendor_id is set, leave it alone
    if params[:asset][:vendor_name].present?
      vendor = Vendor.find_or_create_by(:name => params[:asset][:vendor_name], :organization => @organization)
      params[:asset][:vendor_id] = vendor.id
    elsif params[:asset][:vendor_id].blank? and params[:asset][:vendor_name].blank?
      params[:asset][:vendor_id] = nil
    end
    # vendor_name has served its purpose (find/set vendor_id), so remove from hash
    params[:asset].delete :vendor_name

  end
end


text:
{generate_api_description(/users/{user_id}/reactivate:post)}

## Usage examples

{start_tabs}
{tab|python}

{generate_code_example(python)|/users/{user_id}/reactivate:post|example}

{tab|curl}

{generate_code_example(curl)|/users/{user_id}/reactivate:post|example}

{end_tabs}

## Parameters

{generate_api_arguments_table|zulip.yaml|/users/{user_id}/reactivate:post}

## Response

#### Example response

A typical successful JSON response may look like:

{generate_code_example|/users/{user_id}/reactivate:post|fixture(200)}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/room_name"
    android:layout_width="match_parent"
    android:layout_height="?android:listPreferredItemHeight"
    android:gravity="center_vertical"
    android:padding="@dimen/single_margin"
    tools:text="Android" />


text:
module Awspec::Type
  class VpnGateway < ResourceBase
    tags_allowed

    def initialize(name)
      super
      @display_name = name
    end

    def resource_via_client
      @resource_via_client ||= find_vpn_gateway(@display_name)
    end

    def id
      @id ||= resource_via_client.vpn_gateway_id if resource_via_client
    end

    STATES = %w(
      pending available deleting deleted
    )

    STATES.each do |state|
      define_method state.tr('-', '_') + '?' do
        resource_via_client.state == state
      end
    end

    def availability_zone
      resource_via_client.availability_zone
    end

    def vpc_attachments
      resource_via_client.vpc_attachments
    end

    def type
      resource_via_client.type
    end
  end
end


text:
        File.symlink("testfile", "alink")
        File.stat("alink").symlink?
        File.lstat("alink").symlink?
      File.delete("alink")


text:
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Thriot.Reporting.Services.Dto;

namespace Thriot.Reporting.Tests
{
    [TestClass]
    public class CurrentDataNetworkTests : NetworkTestBase
    {
        [TestMethod]
        public void UnknownSinkStructuredTest()
        {
            var reportingService = PrepareUnknownSinkReporting();

            var result = reportingService.CurrentDataStructuredReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.IsNull(result);
        }

        [TestMethod]
        public void SingleDeviceReportingEmptyStructuredTest()
        {
            var reportingService = PrepareEmptyReporting();

            var result = reportingService.CurrentDataStructuredReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.AreEqual(0, result.Devices.Count);
        }

        [TestMethod]
        public void SingleDeviceReportingHasRecordsStructuredTest()
        {
            var reportingService = PrepareSingleDeviceReporting();

            var result = reportingService.CurrentDataStructuredReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.AreEqual(1, result.Devices.Count);
            var record = result.Devices.First();
            Assert.AreEqual("1", record.DeviceId);
            Assert.AreEqual("dn", record.Name);
            Assert.IsTrue(record.Timestamp > 100000);
            Assert.AreEqual("{\"Temperature\": 24, \"Humidity\": 60}", record.Payload.ToString());
        }

        [TestMethod]
        public void MultiDeviceReportingHasRecordsStructuredTest()
        {
            var reportingService = PrepareMultiDeviceReporting();

            var result = reportingService.CurrentDataStructuredReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.AreEqual(2, result.Devices.Count);
            var record = result.Devices.First();
            Assert.AreEqual("d1", record.DeviceId);
            Assert.AreEqual("dn", record.Name);
            Assert.IsTrue(record.Timestamp > 100000);
            Assert.AreEqual("{\"Temperature\": 24, \"Humidity\": 60}", record.Payload.ToString());
            record = result.Devices.Last();
            Assert.AreEqual("d2", record.DeviceId);
            Assert.AreEqual("dn2", record.Name);
            Assert.IsTrue(record.Timestamp > 100000);
            Assert.AreEqual("{\"Temperature\": 25, \"Humidity\": 61}", record.Payload.ToString());
        }

        [TestMethod]
        public void UnknownSinkFlatTest()
        {
            var reportingService = PrepareUnknownSinkReporting();

            var result = reportingService.CurrentDataFlatReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.IsNull(result);
        }

        [TestMethod]
        public void SingleDeviceReportingEmptyFlatTest()
        {
            var reportingService = PrepareEmptyReporting();

            var result = reportingService.CurrentDataFlatReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.AreEqual(0, result.Rows.Count);
        }

        [TestMethod]
        public void SingleDeviceReportingHasRecordsFlatTest()
        {
            var reportingService = PrepareSingleDeviceReporting();

            var result = reportingService.CurrentDataFlatReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.AreEqual(2, result.Properties.Count);
            Assert.AreEqual("Temperature", result.Properties[0]);
            Assert.AreEqual("Humidity", result.Properties[1]);
            Assert.AreEqual(1, result.Rows.Count);
            var record = result.Rows.First();
            Assert.AreEqual("1", record.DeviceId);
            Assert.AreEqual("dn", record.Name);
            Assert.IsTrue(record.Timestamp > 100000);
            Assert.AreEqual("24", record.Fields.Single(f => f.Key == "Temperature").Value);
            Assert.AreEqual("60", record.Fields.Single(f => f.Key == "Humidity").Value);
        }

        [TestMethod]
        public void MultiDeviceReportingHasRecordsFlatTest()
        {
            var reportingService = PrepareMultiDeviceReporting();

            var result = reportingService.CurrentDataFlatReport(new SinkAndNetworkDto { NetworkId = "2", SinkName = "currentdata" });
            Assert.AreEqual(2, result.Properties.Count);
            Assert.AreEqual("Temperature", result.Properties[0]);
            Assert.AreEqual("Humidity", result.Properties[1]);
            var record = result.Rows.First();
            Assert.AreEqual("d1", record.DeviceId);
            Assert.AreEqual("dn", record.Name);
            Assert.AreEqual("24", record.Fields.Single(f => f.Key == "Temperature").Value);
            Assert.AreEqual("60", record.Fields.Single(f => f.Key == "Humidity").Value);
            record = result.Rows.Last();
            Assert.AreEqual("d2", record.DeviceId);
            Assert.AreEqual("dn2", record.Name);
            Assert.AreEqual("25", record.Fields.Single(f => f.Key == "Temperature").Value);
            Assert.AreEqual("61", record.Fields.Single(f => f.Key == "Humidity").Value);
        }
    }
}


text:
<?php

namespace Imagine\Image;

use Imagine\Draw\DrawerInterface;
use Imagine\Image\BoxInterface;
use Imagine\Image\Color;
use Imagine\Image\PointInterface;
use Imagine\Exception\RuntimeException;

interface ImageInterface extends ManipulatorInterface
{
    const RESOLUTION_PIXELSPERINCH = 'ppi';
    const RESOLUTION_PIXELSPERCENTIMETER = 'ppc';

    /**
     * Returns the image content as a binary string
     *
     * @param string $format
     * @param array  $options
     *
     * @throws RuntimeException
     *
     * @return string binary
     */
    public function get($format, array $options = array());

    /**
     * Returns the image content as a PNG binary string
     *
     * @throws RuntimeException
     *
     * @return string binary
     */
    public function __toString();

    /**
     * Instantiates and returns a DrawerInterface instance for image drawing
     *
     * @return DrawerInterface
     */
    public function draw();

    /**
     * Returns current image size
     *
     * @return BoxInterface
     */
    public function getSize();

    /**
     * Transforms creates a grayscale mask from current image, returns a new
     * image, while keeping the existing image unmodified
     *
     * @return ImageInterface
     */
    public function mask();

    /**
     * Returns array of image colors as Imagine\Image\Color instances
     *
     * @return array
     */
    public function histogram();

    /**
     * Returns color at specified positions of current image
     *
     * @param PointInterface $point
     *
     * @throws RuntimeException
     *
     * @return Color
     */
    public function getColorAt(PointInterface $point);
}


text:
class C_Help : public C_Control
{
#ifdef USE_SH_POOLS
public:
    // Overload new/delete to use a SmartHeap pool
    void *operator new(size_t size)
    {
        return MemAllocPtr(UI_Pools[UI_CONTROL_POOL], size, FALSE);
    };
    void operator delete(void *mem)
    {
        if (mem) MemFreePtr(mem);
    };
#endif
private:
    // Save from here
    long DefaultFlags_;

    COLORREF FgColor_;
    long Font_;

    // Don't save from here
    O_Output *Picture_;
    O_Output *Text_;

public:
    C_Help();
    C_Help(char **stream);
    C_Help(FILE *fp);
    ~C_Help();

    long Size();
    void Save(char **)
    {
        ;
    }
    void Save(FILE *)
    {
        ;
    }
    void Setup(long ID, short Type);
    void Cleanup(void);

    void SetImage(long x, long y, long ImageID);
    void SetText(long x, long y, long w, long TextID);
    void SetFont(long FontID)
    {
        Font_ = FontID;
    }
    void SetFgColor(COLORREF color)
    {
        FgColor_ = color;
    }
    void SetSubParents(C_Window *parent);
    void SetDefaultFlags()
    {
        SetFlags(DefaultFlags_);
    }
    long GetDefaultFlags()
    {
        return(DefaultFlags_);
    }
    long CheckHotSpots(long , long);
    BOOL Process(long ID, short hittype);
    void Refresh();
    void Draw(SCREEN *surface, UI95_RECT *cliprect);
};

#endif


text: export { NavaidCivil16 as default } from "../../";


text:
package com.custardsource.parfait;

import java.util.concurrent.atomic.AtomicLong;

import javax.measure.unit.Unit;

/**
 * {@link Monitorable} implementation for a free-running Long value.
 */
public class MonitoredLongValue extends MonitoredNumeric<AtomicLong> implements Counter {
	public MonitoredLongValue(String name, String description,
			MonitorableRegistry registry, Long initialValue) {
		this(name, description, registry, initialValue, Unit.ONE);
	}

	public MonitoredLongValue(String name, String description,
			Long initialValue) {
		this(name, description, MonitorableRegistry.DEFAULT_REGISTRY, initialValue, Unit.ONE);
	}

    public MonitoredLongValue(String name, String description,
            MonitorableRegistry registry, Long initialValue, Unit<?> unit) {
        super(name, description, registry, new AtomicLong(initialValue), unit);
    }

    /**
     * Convenience method to increment atomic numeric types.
     */
    public void inc() {
        inc(1);
    }

    @Override
    public void inc(int delta) {
        value.addAndGet(delta);
        notifyMonitors();
    }

    /**
     * Convenience method to decrement atomic numeric types.
     */
    public void dec() {
        dec(1);
    }

    @Override
    public void dec(int delta) {
        inc(-delta);
    }

    @Override
    public void inc(long increment) {
        value.addAndGet(increment);
        notifyMonitors();
    }
}


text:
import numpy as np
import networkx as nx
import seaborn as sns
from matplotlib import pyplot as pp

from ..utils import msme_colors
from ..palettes import msme_rgb

__all__ = ['plot_pop_resids', 'plot_msm_network',
           'plot_timescales', 'plot_implied_timescales']

@msme_colors
def plot_pop_resids(msm, **kwargs):
    """
    Plot residuals between MSM populations and raw counts.

    Parameters
    ----------
    msm : msmbuilder.msm
        MSMBuilder MarkovStateModel
    **kwargs : dict, optional
        Extra arguments to pass to seaborn.jointplot

    Returns
    -------
    ax : matplotlib axis
        matplotlib figure axis

    """
    if hasattr(msm, 'all_populations_'):
        msm_pop = msm.populations_.mean(0)
    elif hasattr(msm, 'populations_'):
        msm_pop = msm.populations_

    raw_pop = msm.countsmat_.sum(1) / msm.countsmat_.sum()
    ax = sns.jointplot(np.log10(raw_pop), np.log10(msm_pop), kind='resid',
                       **kwargs)
    ax.ax_joint.set_xlabel('Raw Populations', size=20)
    ax.ax_joint.set_ylabel('Residuals', size=20)

    return ax

@msme_colors
def plot_msm_network(msm, pos=None, node_size=None, node_color='pomegranate',
                     edge_color='carbon', alpha=.7, ax=None, with_labels=True,
                     **kwargs):
    """
    Plot MSM network diagram.

    Parameters
    ----------
    msm : msmbuilder.msm
        MSMBuilder MarkovStateModel
    pos : dict, optional
        Node positions in dict format (e.g. {node_id : [x, y]})
    node_color : str or [r, g, b], optional
        networkx node colors
    node_size : int or list, optional
        networkx node size
    node_color : str, optional
        networkx edge color
    ax : matplotlib axis, optional (default: None)
        Axis to plot on, otherwise uses current axis.
    with_labels : boolean, optional
        Whether or not to include node labels (default: True)
    alpha : float, optional  (default: 0.7)
        Opacity of nodes
    **kwargs : dict, optional
        Extra arguments to pass to networkx.draw_networkx

    Returns
    -------
    ax : matplotlib axis
        matplotlib figure axis

    """
    if hasattr(msm, 'all_populations_'):
        tmat = msm.all_transmats_.mean(0)
        pop = msm.all_populations_.mean(0)
    elif hasattr(msm, 'populations_'):
        tmat = msm.transmat_
        pop = msm.populations_

    graph = nx.Graph(tmat)

    if not ax:
        ax = pp.gca()

    if pos is None:
        pos = nx.spring_layout(graph)

    if node_size is None:
        node_size = 5000. * pop

    if isinstance(node_size, (list, np.ndarray)):
        node_size = [node_size[i] for i in graph.nodes()]

    if isinstance(node_color, (list, np.ndarray)):
        node_color = [node_color[i] for i in graph.nodes()]

    nx.draw_networkx(graph, pos=pos, node_color=node_color,
                     node_size=node_size, edge_color=edge_color, ax=ax,
                     with_labels=with_labels, alpha=alpha, **kwargs)

    return ax

@msme_colors
def plot_timescales(msm, n_timescales=None, error=None, sigma=2,
                    color_palette=None, xlabel=None, ylabel=None, ax=None):
    """
    Plot MSM timescales spectral diagram.

    Parameters
    ----------
    msm : msmbuilder.msm
        MSMBuilder MarkovStateModel
    n_timescales : int, optional
        Number of timescales to plot
    error : array-like (float), optional
        associated errors for each timescales
    sigma : float, optional
        significance level for default error bars
    color_palette: list or dict, optional
        Color palette to apply
    xlabel : str, optional
        x-axis label
    ylabel : str, optional
        y-axis label
    ax : matplotlib axis, optional (default: None)
        Axis to plot on, otherwise uses current axis.

    Returns
    -------
    ax : matplotlib axis
        matplotlib figure axis

    """
    if hasattr(msm, 'all_timescales_'):
        timescales = msm.all_timescales_.mean(0)
        if not error:
            error = (msm.all_timescales_.std(0) /
                     msm.all_timescales_.shape[0] ** 0.5)
    elif hasattr(msm, 'timescales_'):
        timescales = msm.timescales_
        if not error:
            error = np.nan_to_num(msm.uncertainty_timescales())

    if n_timescales:
        timescales = timescales[:n_timescales]
        error = error[:n_timescales]
    else:
        n_timescales = timescales.shape[0]

    ymin = 10 ** np.floor(np.log10(np.nanmin(timescales)))
    ymax = 10 ** np.ceil(np.log10(np.nanmax(timescales)))

    if not ax:
        _, ax = pp.subplots(1, 1, figsize=(2, 8))
    if not color_palette:
        color_palette = list(msme_rgb.values())

    for i, item in enumerate(zip(timescales, error)):
        t, s = item
        color = color_palette[i % len(color_palette)]
        ax.errorbar([0, 1], [t, t], c=color)
        if s:
            for j in range(1, sigma + 1):
                ax.fill_between([0, 1], y1=[t - j * s, t - j * s],
                                y2=[t + j * s, t + j * s],
                                color=color, alpha=0.2 / j)

    ax.xaxis.set_ticks([])
    if xlabel:
        ax.xaxis.set_label_text(xlabel, size=18)
        ax.xaxis.labelpad = 18
    if ylabel:
        ax.yaxis.set_label_text(ylabel, size=18)
    ax.set_yscale('log')
    ax.set_ylim([ymin, ymax])

    autoAxis = ax.axis()
    rec = pp.Rectangle((autoAxis[0], 100),
                       (autoAxis[1] - autoAxis[0]),
                       ymax, fill=False, lw=2)
    rec = ax.add_patch(rec)

    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(16)

    return ax

@msme_colors
def plot_implied_timescales(msm_list, n_timescales=None, show_error=True,
                            color_palette=None, xlabel=None, ylabel=None, ax=None):
    """
    Plot implied timescales as a function of the MSM lag time

    Parameters
    ----------
    msm_list: list of msmbuilder.msm.MarkovStateModel objects
        A list of msm objects, calculated at different lag times
    n_timescales: int, optional
        Number of timescales to display. If None, all will be displayed.
    show_error: bool, optional
        Wether to display the uncertainty estimation of the timescales as a
        shadowed region
    color_palette: list or dict, optional
        Color palette to apply
    xlabel : str, optional
        x-axis label
    ylabel : str, optional
        y-axis label
    ax : matplotlib axis, optional (default: None)
        Axis to plot on, otherwise uses current axis.

    Returns
    -------
    ax : matplotlib axis
        matplotlib figure axis

    """
    # Determine how many timescales to show in plot
    if n_timescales is None:
        n_timescales = len(msm_list[0].timescales_)
    elif n_timescales > len(msm_list[0].timescales_):
        n_timescales = len(msm_list[0].timescales_)

    # Create axis object
    if not ax:
        _, ax = pp.subplots(1, 1)
    if not color_palette:
        color_palette = list(msme_rgb.values())

    # y axis setup
    long_ts = [msm.timescales_[0] for msm in msm_list]
    short_ts = [msm.timescales_[-1] for msm in msm_list]
    ymin = 10 ** np.floor(np.log10(np.nanmin(short_ts)))
    ymax = 10 ** np.ceil(np.log10(np.nanmax(long_ts)))
    ax.set_yscale('log')
    ax.set_ylim([ymin, ymax])
    if ylabel:
        ax.yaxis.set_label_text(ylabel)

    # x axis setup
    lag_times = [msm.lag_time for msm in msm_list]
    if (max(lag_times) / min(lag_times)) >= 1e3:
        xmin = 10 ** np.floor(np.log10(np.nanmin(lag_times)))
        xmax = 10 ** np.ceil(np.log10(np.nanmax(lag_times)))
        ax.set_xscale('log')
    else:
        xmin, xmax = min(lag_times), max(lag_times)
    ax.set_xlim([xmin, xmax])
    if xlabel:
        ax.xaxis.set_label_text(xlabel)

    for ts in range(n_timescales):
        timescales = [msm.timescales_[ts] for msm in msm_list]
        color = color_palette[ts % len(color_palette)]
        pp.scatter(x=lag_times, y=timescales, color=color)
        if show_error:
            errors = [msm.uncertainty_timescales()[ts] for msm in msm_list]
            pp.fill_between(x=lag_times,
                            y1=[ts - err for ts, err in zip(timescales, errors)],
                            y2=[ts + err for ts, err in zip(timescales, errors)],
                            color=color, alpha=0.5)

    return ax


text:
#include <bluetooth.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <netgraph/ng_message.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "hccontrol.h"

/* Prototypes */
static int                  do_hci_command    (char const *, int, char **);
static struct hci_command * find_hci_command  (char const *, struct hci_command *);
static int                  find_hci_nodes    (struct nodeinfo **);
static void                 print_hci_command (struct hci_command *);
static void usage                             (void);

/* Globals */
int	 verbose = 0;
int	 timeout;
int	 numeric_bdaddr = 0;

/* Main */
int
main(int argc, char *argv[])
{
	char	*node = NULL;
	int	 n;

	/* Process command line arguments */
	while ((n = getopt(argc, argv, "n:Nvh")) != -1) {
		switch (n) {
		case 'n':
			node = optarg;
			break;

		case 'N':
			numeric_bdaddr = 1;
			break;

		case 'v':
			verbose = 1;
			break;

		case 'h':
		default:
			usage();
		}
	}

	argc -= optind;
	argv += optind;

	if (*argv == NULL)
		usage();

	n = do_hci_command(node, argc, argv);

	return (n);
} /* main */

/* Create socket and bind it */
static int
socket_open(char const *node)
{
	struct sockaddr_hci			 addr;
	struct ng_btsocket_hci_raw_filter	 filter;
	int					 s, mib[4], num;
	size_t					 size;
	struct nodeinfo 			*nodes;

	num = find_hci_nodes(&nodes);
	if (num == 0)
		errx(7, "Could not find HCI nodes");

	if (node == NULL) {
		node = strdup(nodes[0].name);
		if (num > 1)
			fprintf(stdout, "Using HCI node: %s\n", node);
	}

	free(nodes);

	s = socket(PF_BLUETOOTH, SOCK_RAW, BLUETOOTH_PROTO_HCI);
	if (s < 0)
		err(1, "Could not create socket");

	memset(&addr, 0, sizeof(addr));
	addr.hci_len = sizeof(addr);
	addr.hci_family = AF_BLUETOOTH;
	strncpy(addr.hci_node, node, sizeof(addr.hci_node));
	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0)
		err(2, "Could not bind socket, node=%s", node);

	if (connect(s, (struct sockaddr *) &addr, sizeof(addr)) < 0)
		err(3, "Could not connect socket, node=%s", node);

	memset(&filter, 0, sizeof(filter));
	bit_set(filter.event_mask, NG_HCI_EVENT_COMMAND_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_COMMAND_STATUS - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_INQUIRY_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_INQUIRY_RESULT - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_CON_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_DISCON_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_REMOTE_NAME_REQ_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_READ_REMOTE_FEATURES_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_READ_REMOTE_VER_INFO_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_RETURN_LINK_KEYS - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_READ_CLOCK_OFFSET_COMPL - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_CON_PKT_TYPE_CHANGED - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_ROLE_CHANGE - 1);

	if (setsockopt(s, SOL_HCI_RAW, SO_HCI_RAW_FILTER,
			(void * const) &filter, sizeof(filter)) < 0)
		err(4, "Could not setsockopt()");

	size = (sizeof(mib)/sizeof(mib[0]));
	if (sysctlnametomib("net.bluetooth.hci.command_timeout",mib,&size) < 0)
		err(5, "Could not sysctlnametomib()");

	if (sysctl(mib, sizeof(mib)/sizeof(mib[0]),
			(void *) &timeout, &size, NULL, 0) < 0)
		err(6, "Could not sysctl()");

	timeout ++;

	return (s);
} /* socket_open */

/* Execute commands */
static int
do_hci_command(char const *node, int argc, char **argv)
{
	char			*cmd = argv[0];
	struct hci_command	*c = NULL;
	int			 s, e, help;

	help = 0;
	if (strcasecmp(cmd, "help") == 0) {
		argc --;
		argv ++;

		if (argc <= 0) {
			fprintf(stdout, "Supported commands:\n");
			print_hci_command(link_control_commands);
			print_hci_command(link_policy_commands);
			print_hci_command(host_controller_baseband_commands);
			print_hci_command(info_commands);
			print_hci_command(status_commands);
			print_hci_command(node_commands);
			fprintf(stdout, "\nFor more information use " \
				"'help command'\n");

			return (OK);
		}

		help = 1;
		cmd = argv[0];
	}

	c = find_hci_command(cmd, link_control_commands);
	if (c != NULL)
		goto execute;

	c = find_hci_command(cmd, link_policy_commands);
	if (c != NULL)
		goto execute;

	c = find_hci_command(cmd, host_controller_baseband_commands);
	if (c != NULL)
		goto execute;

	c = find_hci_command(cmd, info_commands);
	if (c != NULL)
		goto execute;

	c = find_hci_command(cmd, status_commands);
	if (c != NULL)
		goto execute;

	c = find_hci_command(cmd, node_commands);
	if (c == NULL) {
		fprintf(stdout, "Unknown command: \"%s\"\n", cmd);
		return (ERROR);
	}
execute:
	if (!help) {
		s = socket_open(node);
		e = (c->handler)(s, -- argc, ++ argv);
		close(s);
	} else
		e = USAGE;

	switch (e) {
	case OK:
	case FAILED:
		break;

	case ERROR:
		fprintf(stdout, "Could not execute command \"%s\". %s\n",
			cmd, strerror(errno));
		break;

	case USAGE:
		fprintf(stdout, "Usage: %s\n%s\n", c->command, c->description);
		break;

	default: assert(0); break;
	}

	return (e);
} /* do_hci_command */

/* Try to find command in specified category */
static struct hci_command *
find_hci_command(char const *command, struct hci_command *category)
{
	struct hci_command	*c = NULL;

	for (c = category; c->command != NULL; c++) {
		char 	*c_end = strchr(c->command, ' ');

		if (c_end != NULL) {
			int	len = c_end - c->command;

			if (strncasecmp(command, c->command, len) == 0)
				return (c);
		} else if (strcasecmp(command, c->command) == 0)
				return (c);
	}

	return (NULL);
} /* find_hci_command */

/* Find all HCI nodes */
static int
find_hci_nodes(struct nodeinfo** nodes)
{
	struct ng_btsocket_hci_raw_node_list_names	r;
	struct sockaddr_hci				addr;
	int						s;
	const char *					node = "ubt0hci";

	r.num_names = MAX_NODE_NUM;
	r.names = (struct nodeinfo*)calloc(MAX_NODE_NUM, sizeof(struct nodeinfo));
	if (r.names == NULL)
		err(8, "Could not allocate memory");

	s = socket(PF_BLUETOOTH, SOCK_RAW, BLUETOOTH_PROTO_HCI);
	if (s < 0)
		err(9, "Could not create socket");

	memset(&addr, 0, sizeof(addr));
	addr.hci_len = sizeof(addr);
	addr.hci_family = AF_BLUETOOTH;
	strncpy(addr.hci_node, node, sizeof(addr.hci_node));
	if (bind(s, (struct sockaddr *) &addr, sizeof(addr)) < 0)
		err(10, "Could not bind socket");

	if (ioctl(s, SIOC_HCI_RAW_NODE_LIST_NAMES, &r, sizeof(r)) < 0)
		err(11, "Could not get list of HCI nodes");

	close(s);

	*nodes = r.names;

	return (r.num_names);
} /* find_hci_nodes */

/* Print commands in specified category */
static void
print_hci_command(struct hci_command *category)
{
	struct hci_command	*c = NULL;

	for (c = category; c->command != NULL; c++)
		fprintf(stdout, "\t%s\n", c->command);
} /* print_hci_command */

/* Usage */
static void
usage(void)
{
	fprintf(stdout, "Usage: hccontrol [-hN] [-n HCI_node_name] cmd [p1] [..]\n");
	exit(255);
} /* usage */


text:
using System;
using System.Runtime.Serialization;

using Carbon.Data.Annotations;
using Carbon.Platform.Resources;
using Carbon.Platform.Sequences;

namespace Carbon.Platform.Networking
{
    [Dataset("Routers", Schema = "Networking")]
    public class Router : INetworkRouter
    {
        public Router() { }

        public Router(long id, string name, ManagedResource resource)
        {
            Id         = id;
            Name       = name ?? throw new ArgumentNullException(nameof(name));
            ProviderId = resource.ProviderId;
            LocationId = resource.LocationId;
            ResourceId = resource.ResourceId;
        }

        [Member("id"), Key]
        public long Id { get; }

        [Member("name")]
        public string Name { get; }

        public long NetworkId => ScopedId.GetScope(Id);

        #region IResource

        [IgnoreDataMember]
        [Member("providerId")]
        public int ProviderId { get; }

        [IgnoreDataMember]
        [Member("resourceId")]
        [Ascii, StringLength(100)]
        public string ResourceId { get; }

        [IgnoreDataMember]
        [Member("locationId")]
        public int LocationId { get; }

        ResourceType IResource.ResourceType => ResourceTypes.NetworkRouter;

        #endregion

        #region Timestamps

        [IgnoreDataMember]
        [Member("created"), Timestamp]
        public DateTime Created { get; }

        [IgnoreDataMember]
        [Member("deleted")]
        public DateTime? Deleted { get; }

        [IgnoreDataMember]
        [Member("modified"), Timestamp(true)]
        public DateTime Modified { get; }

        #endregion
    }
}


text:
<?php

namespace spec\Indigo\Cart\Stub;

use PhpSpec\ObjectBehavior;

class QuantitySpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Indigo\Cart\Stub\Quantity');
        $this->shouldUseTrait('Indigo\Cart\Quantity');
    }

    function it_has_quantity()
    {
        $quantity = $this->getQuantity();

        $quantity->shouldBeInteger();
        $quantity->shouldBe(1);
    }

    function it_changes_quantity()
    {
        $this->changeQuantity(1);

        $this->getQuantity()->shouldReturn(2);
    }

    function it_throws_an_exception_when_change_quantity_is_not_integer()
    {
        $this->shouldThrow('InvalidArgumentException')->duringChangeQuantity('123');
    }

    function it_sets_quantity()
    {
        $this->setQuantity(3);

        $this->getQuantity()->shouldReturn(3);
    }

    function it_throws_an_exception_when_set_quantity_is_not_integer()
    {
        $this->shouldThrow('InvalidArgumentException')->duringSetQuantity('123');
    }

    function it_throws_an_exception_when_set_quantity_is_not_positive()
    {
        $this->shouldThrow('InvalidArgumentException')->duringSetQuantity(-5);
    }

    public function getMatchers()
    {
        return [
            'useTrait' => function ($subject, $trait) {
                return class_uses($subject, $trait);
            }
        ];
    }
}


text:
Visit my website here: [kvitajakub.github.io](http://kvitajakub.github.io/)

## Installation
Require `ruby`, `bundler` and `jekyll`.

## Usage
To work locally with Jekyll webserver:
```
bundle exec jekyll build
```
```
bundle exec jekyll serve
```

This blog is based on the official Jekyll version of the [Clean Blog](http://startbootstrap.com/template-overviews/clean-blog/) theme by [Start Bootstrap](http://startbootstrap.com/).


text:
import argparse
import logging
import os
import os.path
import re
import sqlite3
import subprocess
import sys
import time
import translator

VERSION='0.1'

logging.basicConfig(level=logging.DEBUG)

def generate(input, languages=None):
	document = translator.Document.load(input)
	translations = [translator.Translation(input, 'en_US')]+translator.find_translations(input, languages=languages.split(',') if languages else None)
	changed = False
	for i in translations:
		if i.update(document):
			changed = True

	if changed:
		sys.stderr.write('Some translations has changed. Please update them and restart the process\n')
		sys.exit(1)

	outputs = []
	for i in translations:
		i = i.translate(document)
		outputs.append(i.generate())

	for i in outputs:
		subprocess.check_call(['xdg-open', i])

def main():
	parser = argparse.ArgumentParser(description='Documents internationalization tool (version {})'.format(VERSION))
	parser.add_argument('--input', action='store',
		help='Name of input file (default: input.tex)', default='input.tex')
	parser.add_argument('--languages', action='store',
		help='List of language codes for which outputs will be generated.'+
		'Default list is built from names of found translation files', default=None)
	args = parser.parse_args()
	generate(input=args.input, languages=args.languages)

if __name__ == '__main__':
	main()


text:
namespace AnswerFactory
{
    public class RecipeConfigParameter
    {
        public string name { get; set; }
        public object value { get; set; }
        public string type { get; set; }

        public RecipeConfigParameter()
        {}

        public RecipeConfigParameter(string name, object value, string type)
        {
            this.name = name;
            this.value = value;
            this.type = type;
        }

        public override string ToString()
        {
            return string.Format(
                "RecipeConfigParameter{name='{0}', value={1},type={2}}",
                this.name,
                this.value,
                this.type);
        }
    }
}


text:
'use strict';

import 'vs/css!./media/activitybarpart';
import nls = require('vs/nls');
import { TPromise } from 'vs/base/common/winjs.base';
import { illegalArgument } from 'vs/base/common/errors';
import { Builder, $, Dimension } from 'vs/base/browser/builder';
import { Action } from 'vs/base/common/actions';
import { ActionsOrientation, ActionBar, Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { GlobalActivityExtensions, IGlobalActivityRegistry } from 'vs/workbench/common/activity';
import { Registry } from 'vs/platform/registry/common/platform';
import { Part } from 'vs/workbench/browser/part';
import { GlobalActivityActionItem, GlobalActivityAction, ViewletActivityAction, ToggleViewletAction } from 'vs/workbench/browser/parts/activitybar/activitybarActions';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { IBadge } from 'vs/workbench/services/activity/common/activity';
import { IPartService, Position as SideBarPosition } from 'vs/workbench/services/part/common/partService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { StandardMouseEvent } from 'vs/base/browser/mouseEvent';
import { dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { ToggleActivityBarVisibilityAction } from 'vs/workbench/browser/actions/toggleActivityBarVisibility';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ACTIVITY_BAR_BACKGROUND, ACTIVITY_BAR_BORDER, ACTIVITY_BAR_FOREGROUND, ACTIVITY_BAR_BADGE_BACKGROUND, ACTIVITY_BAR_BADGE_FOREGROUND, ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND } from 'vs/workbench/common/theme';
import { contrastBorder } from 'vs/platform/theme/common/colorRegistry';
import { CompositeBar } from 'vs/workbench/browser/parts/compositebar/compositeBar';
import { ToggleCompositePinnedAction } from 'vs/workbench/browser/parts/compositebar/compositeBarActions';

export class ActivitybarPart extends Part {

	private static readonly PINNED_VIEWLETS = 'workbench.activity.pinnedViewlets';
	private static COLORS = {
		backgroundColor: ACTIVITY_BAR_FOREGROUND,
		badgeBackground: ACTIVITY_BAR_BADGE_BACKGROUND,
		badgeForeground: ACTIVITY_BAR_BADGE_FOREGROUND,
		dragAndDropBackground: ACTIVITY_BAR_DRAG_AND_DROP_BACKGROUND
	};

	public _serviceBrand: any;

	private dimension: Dimension;

	private globalActionBar: ActionBar;
	private globalActivityIdToActions: { [globalActivityId: string]: GlobalActivityAction; };

	private compositeBar: CompositeBar;

	constructor(
		id: string,
		@IViewletService private viewletService: IViewletService,
		@IContextMenuService private contextMenuService: IContextMenuService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPartService private partService: IPartService,
		@IThemeService themeService: IThemeService
	) {
		super(id, { hasTitle: false }, themeService);

		this.globalActivityIdToActions = Object.create(null);
		this.compositeBar = this.instantiationService.createInstance(CompositeBar, {
			icon: true,
			storageId: ActivitybarPart.PINNED_VIEWLETS,
			orientation: ActionsOrientation.VERTICAL,
			composites: this.viewletService.getViewlets(),
			openComposite: (compositeId: string) => this.viewletService.openViewlet(compositeId, true),
			getActivityAction: (compositeId: string) => this.instantiationService.createInstance(ViewletActivityAction, this.viewletService.getViewlet(compositeId)),
			getCompositePinnedAction: (compositeId: string) => new ToggleCompositePinnedAction(this.viewletService.getViewlet(compositeId), this.compositeBar),
			getOnCompositeClickAction: (compositeId: string) => this.instantiationService.createInstance(ToggleViewletAction, this.viewletService.getViewlet(compositeId)),
			getDefaultCompositeId: () => this.viewletService.getDefaultViewletId(),
			hidePart: () => this.partService.setSideBarHidden(true),
			colors: ActivitybarPart.COLORS,
			overflowActionSize: 50
		});
		this.registerListeners();
	}

	private registerListeners(): void {

		// Activate viewlet action on opening of a viewlet
		this.toUnbind.push(this.viewletService.onDidViewletOpen(viewlet => this.compositeBar.activateComposite(viewlet.getId())));

		// Deactivate viewlet action on close
		this.toUnbind.push(this.viewletService.onDidViewletClose(viewlet => this.compositeBar.deactivateComposite(viewlet.getId())));
		this.toUnbind.push(this.compositeBar.onDidContextMenu(e => this.showContextMenu(e)));
	}

	public showActivity(viewletOrActionId: string, badge: IBadge, clazz?: string): IDisposable {
		if (this.viewletService.getViewlet(viewletOrActionId)) {
			return this.compositeBar.showActivity(viewletOrActionId, badge, clazz);
		}

		return this.showGlobalActivity(viewletOrActionId, badge);
	}

	private showGlobalActivity(globalActivityId: string, badge: IBadge): IDisposable {
		if (!badge) {
			throw illegalArgument('badge');
		}

		const action = this.globalActivityIdToActions[globalActivityId];
		if (!action) {
			throw illegalArgument('globalActivityId');
		}

		action.setBadge(badge);

		return toDisposable(() => action.setBadge(undefined));
	}

	public createContentArea(parent: Builder): Builder {
		const $el = $(parent);
		const $result = $('.content').appendTo($el);

		// Top Actionbar with action items for each viewlet action
		this.compositeBar.create($result.getHTMLElement());

		// Top Actionbar with action items for each viewlet action
		this.createGlobalActivityActionBar($('.global-activity').appendTo($result).getHTMLElement());

		return $result;
	}

	public updateStyles(): void {
		super.updateStyles();

		// Part container
		const container = this.getContainer();
		const background = this.getColor(ACTIVITY_BAR_BACKGROUND);
		container.style('background-color', background);

		const borderColor = this.getColor(ACTIVITY_BAR_BORDER) || this.getColor(contrastBorder);
		const isPositionLeft = this.partService.getSideBarPosition() === SideBarPosition.LEFT;
		container.style('box-sizing', borderColor && isPositionLeft ? 'border-box' : null);
		container.style('border-right-width', borderColor && isPositionLeft ? '1px' : null);
		container.style('border-right-style', borderColor && isPositionLeft ? 'solid' : null);
		container.style('border-right-color', isPositionLeft ? borderColor : null);
		container.style('border-left-width', borderColor && !isPositionLeft ? '1px' : null);
		container.style('border-left-style', borderColor && !isPositionLeft ? 'solid' : null);
		container.style('border-left-color', !isPositionLeft ? borderColor : null);
	}

	private showContextMenu(e: MouseEvent): void {
		const event = new StandardMouseEvent(e);

		const actions: Action[] = this.viewletService.getViewlets().map(viewlet => this.instantiationService.createInstance(ToggleCompositePinnedAction, viewlet, this.compositeBar));
		actions.push(new Separator());
		actions.push(this.instantiationService.createInstance(ToggleActivityBarVisibilityAction, ToggleActivityBarVisibilityAction.ID, nls.localize('hideActivitBar', "Hide Activity Bar")));

		this.contextMenuService.showContextMenu({
			getAnchor: () => { return { x: event.posx, y: event.posy }; },
			getActions: () => TPromise.as(actions),
			onHide: () => dispose(actions)
		});
	}

	private createGlobalActivityActionBar(container: HTMLElement): void {
		const activityRegistry = Registry.as<IGlobalActivityRegistry>(GlobalActivityExtensions);
		const descriptors = activityRegistry.getActivities();
		const actions = descriptors
			.map(d => this.instantiationService.createInstance(d))
			.map(a => new GlobalActivityAction(a));

		this.globalActionBar = new ActionBar(container, {
			actionItemProvider: a => this.instantiationService.createInstance(GlobalActivityActionItem, a, ActivitybarPart.COLORS),
			orientation: ActionsOrientation.VERTICAL,
			ariaLabel: nls.localize('globalActions', "Global Actions"),
			animated: false
		});

		actions.forEach(a => {
			this.globalActivityIdToActions[a.id] = a;
			this.globalActionBar.push(a);
		});
	}

	public getPinned(): string[] {
		return this.viewletService.getViewlets().map(v => v.id).filter(id => this.compositeBar.isPinned(id));
	}

	/**
	 * Layout title, content and status area in the given dimension.
	 */
	public layout(dimension: Dimension): Dimension[] {

		// Pass to super
		const sizes = super.layout(dimension);

		this.dimension = sizes[1];

		let availableHeight = this.dimension.height;
		if (this.globalActionBar) {
			// adjust height for global actions showing
			availableHeight -= (this.globalActionBar.items.length * this.globalActionBar.domNode.clientHeight);
		}
		this.compositeBar.layout(new Dimension(dimension.width, availableHeight));

		return sizes;
	}

	public dispose(): void {
		if (this.compositeBar) {
			this.compositeBar.dispose();
			this.compositeBar = null;
		}

		if (this.globalActionBar) {
			this.globalActionBar.dispose();
			this.globalActionBar = null;
		}

		super.dispose();
	}

	public shutdown(): void {
		// Persist Hidden State
		this.compositeBar.store();

		// Pass to super
		super.shutdown();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
		http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.3.xsd
		http://www.liquibase.org/xml/ns/dbchangelog-ext
		http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <property name="now" value="sysdate" dbms="h2"/>
    <include file="classpath:db/changelog/user-changelog.xml" />
</databaseChangeLog>


text:
package org.apache.accumulo.test.replication;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.accumulo.tserver.logger.LogEvents.OPEN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

import java.io.DataOutputStream;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map.Entry;
import java.util.UUID;

import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.accumulo.core.protobuf.ProtobufUtil;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.miniclusterImpl.MiniAccumuloConfigImpl;
import org.apache.accumulo.server.ServerConstants;
import org.apache.accumulo.server.data.ServerMutation;
import org.apache.accumulo.server.replication.ReplicaSystemFactory;
import org.apache.accumulo.server.replication.StatusUtil;
import org.apache.accumulo.server.replication.proto.Replication.Status;
import org.apache.accumulo.test.functional.ConfigurableMacBase;
import org.apache.accumulo.tserver.log.DfsLogger;
import org.apache.accumulo.tserver.logger.LogEvents;
import org.apache.accumulo.tserver.logger.LogFileKey;
import org.apache.accumulo.tserver.logger.LogFileValue;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.junit.Ignore;
import org.junit.Test;

import com.google.common.collect.Iterables;

@Ignore("Replication ITs are not stable and not currently maintained")
public class UnusedWalDoesntCloseReplicationStatusIT extends ConfigurableMacBase {

  @Override
  public void configure(MiniAccumuloConfigImpl cfg, Configuration coreSite) {
    cfg.setNumTservers(1);
  }

  @Test
  public void test() throws Exception {
    File accumuloDir = this.getCluster().getConfig().getAccumuloDir();
    final AccumuloClient client = Accumulo.newClient().from(getClientProperties()).build();
    final String tableName = getUniqueNames(1)[0];

    client.securityOperations().grantTablePermission("root", MetadataTable.NAME,
        TablePermission.WRITE);
    client.tableOperations().create(tableName);

    final TableId tableId = TableId.of(client.tableOperations().tableIdMap().get(tableName));
    final int numericTableId = Integer.parseInt(tableId.canonical());
    final int fakeTableId = numericTableId + 1;

    assertNotNull("Did not find table ID", tableId);

    client.tableOperations().setProperty(tableName, Property.TABLE_REPLICATION.getKey(), "true");
    client.tableOperations().setProperty(tableName,
        Property.TABLE_REPLICATION_TARGET.getKey() + "cluster1", "1");
    // just sleep
    client.instanceOperations().setProperty(Property.REPLICATION_PEERS.getKey() + "cluster1",
        ReplicaSystemFactory.getPeerConfigurationValue(MockReplicaSystem.class, "50000"));

    FileSystem fs = FileSystem.getLocal(new Configuration());
    File tserverWalDir =
        new File(accumuloDir, ServerConstants.WAL_DIR + Path.SEPARATOR + "faketserver+port");
    File tserverWal = new File(tserverWalDir, UUID.randomUUID().toString());
    fs.mkdirs(new Path(tserverWalDir.getAbsolutePath()));

    // Make a fake WAL with no data in it for our real table
    FSDataOutputStream out = fs.create(new Path(tserverWal.getAbsolutePath()));

    out.write(DfsLogger.LOG_FILE_HEADER_V4.getBytes(UTF_8));

    DataOutputStream dos = new DataOutputStream(out);
    dos.writeUTF("NullCryptoModule");

    // Fake a single update WAL that has a mutation for another table
    LogFileKey key = new LogFileKey();
    LogFileValue value = new LogFileValue();

    key.event = OPEN;
    key.tserverSession = tserverWal.getAbsolutePath();
    key.filename = tserverWal.getAbsolutePath();
    key.write(out);
    value.write(out);

    key.event = LogEvents.DEFINE_TABLET;
    key.tablet = new KeyExtent(TableId.of(Integer.toString(fakeTableId)), null, null);
    key.seq = 1L;
    key.tabletId = 1;

    key.write(dos);
    value.write(dos);

    key.tablet = null;
    key.event = LogEvents.MUTATION;
    key.filename = tserverWal.getAbsolutePath();
    value.mutations = Arrays.asList(new ServerMutation(new Text("row")));

    key.write(dos);
    value.write(dos);

    key.event = LogEvents.COMPACTION_START;
    key.filename =
        accumuloDir.getAbsolutePath() + "/tables/" + fakeTableId + "/t-000001/A000001.rf";
    value.mutations = Collections.emptyList();

    key.write(dos);
    value.write(dos);

    key.event = LogEvents.COMPACTION_FINISH;
    value.mutations = Collections.emptyList();

    key.write(dos);
    value.write(dos);

    dos.close();

    try (BatchWriter bw = client.createBatchWriter(tableName)) {
      Mutation m = new Mutation("m");
      m.put("m", "m", "M");
      bw.addMutation(m);
    }

    log.info("State of metadata table after inserting a record");

    try (Scanner s = client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {

      s.setRange(MetadataSchema.TabletsSection.getRange(tableId));
      for (Entry<Key,Value> entry : s) {
        System.out.println(entry.getKey().toStringNoTruncate() + " " + entry.getValue());
      }
    }

    try (Scanner s = client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {
      s.setRange(MetadataSchema.ReplicationSection.getRange());
      for (Entry<Key,Value> entry : s) {
        System.out.println(entry.getKey().toStringNoTruncate() + " "
            + ProtobufUtil.toString(Status.parseFrom(entry.getValue().get())));
      }

      log.info("Offline'ing table");

      client.tableOperations().offline(tableName, true);

      // Add our fake WAL to the log column for this table
      String walUri = tserverWal.toURI().toString();
      KeyExtent extent = new KeyExtent(tableId, null, null);
      try (BatchWriter bw = client.createBatchWriter(MetadataTable.NAME)) {
        Mutation m = new Mutation(extent.getMetadataEntry());
        m.put(MetadataSchema.TabletsSection.LogColumnFamily.NAME,
            new Text("localhost:12345/" + walUri), new Value(walUri + "|1"));
        bw.addMutation(m);

        // Add a replication entry for our fake WAL
        m = new Mutation(MetadataSchema.ReplicationSection.getRowPrefix() + new Path(walUri));
        m.put(MetadataSchema.ReplicationSection.COLF, new Text(tableId.canonical()),
            new Value(StatusUtil.fileCreated(System.currentTimeMillis()).toByteArray()));
        bw.addMutation(m);
      }

      log.info("State of metadata after injecting WAL manually");
    }

    try (Scanner s = client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {
      s.setRange(MetadataSchema.TabletsSection.getRange(tableId));
      for (Entry<Key,Value> entry : s) {
        log.info("{} {}", entry.getKey().toStringNoTruncate(), entry.getValue());
      }
    }

    try (Scanner s = client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {
      s.setRange(MetadataSchema.ReplicationSection.getRange());
      for (Entry<Key,Value> entry : s) {
        log.info("{} {}", entry.getKey().toStringNoTruncate(),
            ProtobufUtil.toString(Status.parseFrom(entry.getValue().get())));
      }

      log.info("Bringing table online");
      client.tableOperations().online(tableName, true);

      assertEquals(1, Iterables.size(client.createScanner(tableName, Authorizations.EMPTY)));

      log.info("Table has performed recovery, state of metadata:");
    }

    try (Scanner s = client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {
      s.setRange(MetadataSchema.TabletsSection.getRange(tableId));
      for (Entry<Key,Value> entry : s) {
        log.info("{} {}", entry.getKey().toStringNoTruncate(), entry.getValue());
      }
    }

    try (Scanner s = client.createScanner(MetadataTable.NAME, Authorizations.EMPTY)) {
      s.setRange(MetadataSchema.ReplicationSection.getRange());
      for (Entry<Key,Value> entry : s) {
        Status status = Status.parseFrom(entry.getValue().get());
        log.info("{} {}", entry.getKey().toStringNoTruncate(), ProtobufUtil.toString(status));
        assertFalse("Status record was closed and it should not be", status.getClosed());
      }
    }
  }
}


text:
import { Directive, ElementRef } from '@angular/core';
declare let jQuery: any;
declare let Tether: any;

@Directive ({
  selector: '[bootstrap-application-wizard]'
})

export class BootstrapApplicationWizard {
  $el: any;

  constructor(el: ElementRef) {
    this.$el = jQuery(el.nativeElement);
    /* tslint:disable */
    (<any>window).validateServerLabel = function(el) {
      let name = el.val();
      let retValue = {};

      if (name === '') {
        retValue['status'] = false;
        retValue['msg'] = 'Please enter a label';
      } else {
        retValue['status'] = true;
      }

      return retValue;
    };

    (<any>window).validateFQDN = function(el) {
      let $this = jQuery(el);
      let retValue = {};

      if ($this.is(':disabled')) {
        // FQDN Disabled
        retValue['status'] = true;
      } else {
        if ($this.data('lookup') === 0) {
          retValue['status'] = false;
          retValue['msg'] = 'Preform lookup first';
        } else {
          if ($this.data('is-valid') === 0) {
            retValue['status']= false;
            retValue['msg'] = 'Lookup Failed';
          } else {
            retValue['status'] = true;
          }
        }
      }

      return retValue;
    };
    /* tslint:enable */
  }

  lookup(): void {
    // Normally a ajax call to the server to preform a lookup
    jQuery('#fqdn').data('lookup', 1);
    jQuery('#fqdn').data('is-valid', 1);
    jQuery('#ip').val('127.0.0.1');
  }

  render(): void {
    let wizard = this.$el.wizard({
      keyboard : false,
      contentHeight : 400,
      contentWidth : 700,
      backdrop: 'static'
    });

    jQuery('#fqdn').on('input', function() {
      if (jQuery(this).val().length !== 0) {
        jQuery('#ip').val('').attr('disabled', 'disabled');
        jQuery('#fqdn, #ip').parents('.form-group').removeClass('has-error has-success');
      } else {
        jQuery('#ip').val('').removeAttr('disabled');
      }
    });

    jQuery('#btn-fqdn').find('button').on('click', this.lookup);
    /* tslint:disable */
    let pattern = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
    let x = 46;
    /* tslint:enable */
    jQuery('#ip').on('input', () => {
      if (jQuery(this).val().length !== 0) {
        jQuery('#fqdn').val('').attr('disabled', 'disabled');
      } else {
        jQuery('#fqdn').val('').removeAttr('disabled');
      }
    }).keypress(function(e): boolean {
      if (e.which !== 8 && e.which !== 0 && e.which !== x && (e.which < 48 || e.which > 57)) {
        console.log(e.which);
        return false;
      }
    }).keyup(function(): void {
      let $this = jQuery(this);
      if (!pattern.test($this.val())) {
        // jQuery('#validate_ip').text('Not Valid IP');
        console.log('Not Valid IP');
        $this.parents('.form-group').removeClass('has-error has-success').addClass('has-error');
        while ($this.val().indexOf('..') !== -1) {
          $this.val($this.val().replace('..', '.'));
        }
        x = 46;
      } else {
        x = 0;
        let lastChar = $this.val().substr($this.val().length - 1);
        if (lastChar === '.') {
          $this.val($this.val().slice(0, -1));
        }
        let ip = $this.val().split('.');
        if (ip.length === 4) {
          // jQuery('#validate_ip').text('Valid IP');
          console.log('Valid IP');
          $this.parents('.form-group').removeClass('has-error').addClass('has-success');
        }
      }
    });

    wizard.on('closed', () => {
      wizard.reset();
    });

    wizard.on('reset', () => {
      wizard.modal.find(':input').val('').removeAttr('disabled');
      wizard.modal.find('.form-group').removeClass('has-error').removeClass('has-succes');
      wizard.modal.find('#fqdn').data('is-valid', 0).data('lookup', 0);
    });

    wizard.on('submit', function(wizardItem): void {
      let submit = {
        'hostname': jQuery('#new-server-fqdn').val()
      };

      this.log('seralize()');
      this.log(this.serialize());
      this.log('serializeArray()');
      /* tslint:disable */
      this.log(this['serializeArray']());
      /* tslint:enable */

      setTimeout(() => {
        wizardItem.trigger('success');
        wizardItem.hideButtons();
        wizardItem._submitting = false;
        wizardItem.showSubmitCard('success');
        wizardItem.updateProgressBar(0);
      }, 2000);
    });

    wizard.el.find('.wizard-success .im-done').click(() => {
      wizard.hide();
      setTimeout(() => {
        wizard.reset();
      }, 250);

    });

    wizard.el.find('.wizard-success .create-another-server').click(() => {
      wizard.reset();
    });
    /* tslint:disable */
    wizard.el.find('.wizard-progress-container').empty()
      .append('

');
    /* tslint:enable */
    wizard.progress = wizard.modal.find('progress');

    jQuery('.wizard-group-list').click(() => {
      window.alert('Disabled for demo.');
    });

    jQuery('#open-wizard').click((e) => {
      e.preventDefault();
      wizard.show();
      wizard.errorPopover = function(el, msg, allowHtml): void {
        this.log('launching popover on', el);
        allowHtml = typeof allowHtml !== 'undefined' ? allowHtml : false;
        let popover = el.popover({
          content: msg,
          trigger: 'manual',
          html: allowHtml,
          container: el.parents('.form-group')
        }).addClass('error-popover').popover('show').next('.popover');

        el.parents('.form-group').find('.popover').addClass('error-popover');
        jQuery('.popover-title').css('display', 'none');
        jQuery('.popover').addClass('popover-body-error');
        jQuery('.popover-content').addClass('popover-content-error');
        jQuery('.popover-arrow').addClass('popover-arrow-error');
        Tether.position();
        /* tslint:disable */
        this['popovers'].push(el);
        /* tslint:enable */
        return popover;
      };
      jQuery('.dropdown-menu > li > a').addClass('dropdown-item');
    });

    wizard.el.find('.wizard-nav-list').addClass('flex-column');
    wizard.el.find('.wizard-close').addClass('flex-last');
  }

  ngAfterViewInit(): void {
    setTimeout(() => {this.render();}, 100);
  }
}


text:
namespace GDXClient
{
    partial class FruitEditControl
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            //
            // FruitEditControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "FruitEditControl";
            this.Size = new System.Drawing.Size(1034, 619);
            this.ResumeLayout(false);

        }

        #endregion
    }
}


text:
package com.google.android.gms.internal;

import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.safeparcel.a;
import com.google.android.gms.common.internal.safeparcel.a.a;
import com.google.android.gms.common.internal.safeparcel.b;
import java.util.HashSet;
import java.util.Set;

public class ie
  implements Parcelable.Creator<id>
{
  static void a(id paramid, Parcel paramParcel, int paramInt)
  {
    int i = b.o(paramParcel);
    Set localSet = paramid.fa();
    if (localSet.contains(Integer.valueOf(1)))
      b.c(paramParcel, 1, paramid.getVersionCode());
    if (localSet.contains(Integer.valueOf(2)))
      b.a(paramParcel, 2, paramid.getId(), true);
    if (localSet.contains(Integer.valueOf(4)))
      b.a(paramParcel, 4, paramid.fr(), paramInt, true);
    if (localSet.contains(Integer.valueOf(5)))
      b.a(paramParcel, 5, paramid.getStartDate(), true);
    if (localSet.contains(Integer.valueOf(6)))
      b.a(paramParcel, 6, paramid.fs(), paramInt, true);
    if (localSet.contains(Integer.valueOf(7)))
      b.a(paramParcel, 7, paramid.getType(), true);
    b.D(paramParcel, i);
  }

  public id at(Parcel paramParcel)
  {
    int i = a.n(paramParcel);
    HashSet localHashSet = new HashSet();
    int j = 0;
    String str1 = null;
    ib localib1 = null;
    String str2 = null;
    ib localib2 = null;
    String str3 = null;
    while (paramParcel.dataPosition() < i)
    {
      int k = a.m(paramParcel);
      switch (a.M(k))
      {
      default:
        break;
      case 1:
        j = a.g(paramParcel, k);
        localHashSet.add(Integer.valueOf(1));
        break;
      case 2:
        str1 = a.m(paramParcel, k);
        localHashSet.add(Integer.valueOf(2));
        break;
      case 4:
        localib1 = (ib)a.a(paramParcel, k, ib.CREATOR);
        localHashSet.add(Integer.valueOf(4));
        break;
      case 5:
        str2 = a.m(paramParcel, k);
        localHashSet.add(Integer.valueOf(5));
        break;
      case 6:
        localib2 = (ib)a.a(paramParcel, k, ib.CREATOR);
        localHashSet.add(Integer.valueOf(6));
        break;
      case 7:
        str3 = a.m(paramParcel, k);
        localHashSet.add(Integer.valueOf(7));
        break;
      case 3:
        a.b(paramParcel, k);
      }
    }
    if (paramParcel.dataPosition() != i)
      throw new a.a("Overread allowed size end=" + i, paramParcel);
    return new id(localHashSet, j, str1, localib1, str2, localib2, str3);
  }

  public id[] bl(int paramInt)
  {
    return new id[paramInt];
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.internal.ie
 * JD-Core Version:    0.6.2
 */


text:
package com.eigengo.lift.profile

object UserProfileProtocol {

  /**
   * The user account details
   * @param email the user's email
   * @param password the hashed password
   * @param salt the salt used in hashing
   */
  @SerialVersionUID(1017l) case class Account(email: String, password: Array[Byte], salt: String)
}


text:
layout: post
title: 46 Neuromarketing
date:  2017-02-21 00:00:00
---

<iframe width="100%" height="200" frameborder="0" allowfullscreen="" scrolling="no" src="http://www.ivoox.com/player_ej_12417529_2_1.html?data=kpehk5yZdpqhhpywj5WVaZS1k5eSlaaXd46ZmKiak5KJe6Shkpqdj4qbh46llpKSmaiRaZOnkZehjYqpdoaskYqmlZCyqdbm0NLO1NDJuMriyJKSmaiRsMrW09Tg0sbWpcbh0dfS0MnJqNDmxtiah5yncZE.&"></iframe>

Capes del cervell

1. Cervell Nou: Raciona
2. Cervell Mitjà: Emocions
3. Cervell Primitiu o Reptilià: Decisions.

El cervell Reptilià té en compte els dos cervells anteriors i pren desicions.

### 6 Estímuls amb els quals podem parlar al cervell

1. Egocentrisme: Cal apelar a l'egocentrisme.
2. Contrast: Si son existeixen contrastos el cervell primitiu es confon. Cal aclarir què és millor i pitjor. Cal fugir de les frases neutrals.
3. Simplicitat: No té capacitat per ententre el llenguatge escrit. Cal donar informació simple, fàcil d'entendre.
4. Amb principi i final: Cal oferir un principi fort i un final fort. Posar màxima energia en el principi i en el final.
5. Reconeixement visual: La supervivència l'utilitza constantment.
6. Emoció: Quan som capaços d'associar una emoció a alguna cosa la recordarem.

### 4 Passos per tenir èxit

#### 1. Diagnosticar el dolor: Cal preguntar al client. Cal fer veure que el client veja el seu dolor. Això comunica al client que saps com buscar els problemes.

Pregunta 1: Quin és el dolor més important?

a. Financera;

b. Estratègica;

c. Personal.

Pregunta 2: Quina és la intensidad del dolor?

Pregunta 3: Quin nivell d'urgència té aquest dolor?

A major nivell d'urgència més motivació per comparar.

Pregunta 4: El client s'ha donat compte?

#### 2. Conseguir diferenciar-nos amb les nostres afirmacions

Cal oferir contraste: «Som els únics que fem tal cosa».

Cal diferenciar-se d'una manera precisa i contundent.

#### 3. Demostrar les ganàncies

Cal donar informació de dades concretes, fàcils d'entendre.

Les ganàncies estratègiques no són fàcils de mesurar.

Potser mitjançant l'history telling, és una visió, una història inventada que servisca per a transmetre una idea, una emoció.

#### 4. Entregar el missatge el cervell primitiu

2 Formes de parlar-li al cervell

### 1. Peces perconstruir el missatge

1. *Captadors d'atenció*. El cervell primitiu es concentra en el principi i en el final. Cal captar l'atenció del client al principi, cal entrar amb una explosió, cal causar una impressió forta.
- Minidrames: Que passaria si no tinguera el producte o servei.
- Jocs de paraules: Jugar amb les paraules per crear missatges.
- Preguntes retòriques: Preguntes que no necessiten respostes explícites, però sí necessiten respostes mentals. Associar imatges fent preguntes, per tal que el client es responga amb beneficis.
- Objectes: Poden ajudar a relacionar.
- Explicar històries.
2. *Visió panoràmica*. Mostrar imàges de l'abans i el després.
3. *Afirmacions*. Punts claus, valor real de la solució.
4. *Llenguatge clar*. A nivell d'un xiquet de 3r de primària.
5. *Proves de ganància*. Demostrar que hi ha una ganància. Cal respaldar-ho tot amb proves.
6. *Objecions*. Poden ser malentesos o aclaracions. Cal entrar, de manera elegant a detallar, repetir per tal que quede clar.
7. *Tancament de la venta*. Si s'ha anat construint el missatge sols cal tancar, sense agressivitat. Esperar el compromís.

## 2.Claus per potenciar el missatge

1. *Benefici* per al client. Utilitzar constantment la paraula *tu*, que la frase estiga centrada en el client.
2. *Credibilitat*
- Creativitat
- Integritat
- Similitudes con los clientes
- Las teues paraules, la forma en que comuniques, no utilitzar paraules complexes
3. *Ús de les pauses*
4. *Paraules persuasives*
- tu
- diners
- estalviar
- salut
- seguretat
- amor
- nou
- resultat
- fàcil
- provat
- garantitzat
- podria por favor
5. *Emoció*
6. *Estils d'aprenentatge* del client
7. *Menys és més*. No inundar amb missatges, centrar-nos en les afirmacions més importants.

-- Patrick Renvoisé, Christophe Morin. 2007. Neuromarketing.


text:
<?xml version="1.0"?>

<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" version="2.0">
	<portlet>
		<portlet-name>jsonws-services</portlet-name>
		<display-name>JSONWS services</display-name>
		<portlet-class>com.liferay.util.bridges.mvc.MVCPortlet</portlet-class>
		<init-param>
			<name>view-template</name>
			<value>/view.jsp</value>
		</init-param>
		<expiration-cache>0</expiration-cache>
		<supports>
			<mime-type>text/html</mime-type>
		</supports>
		<portlet-info>
			<title>JSONWS services</title>
			<short-title>JSONWS services</short-title>
			<keywords>JSONWS services</keywords>
		</portlet-info>
		<security-role-ref>
			<role-name>administrator</role-name>
		</security-role-ref>
		<security-role-ref>
			<role-name>guest</role-name>
		</security-role-ref>
		<security-role-ref>
			<role-name>power-user</role-name>
		</security-role-ref>
		<security-role-ref>
			<role-name>user</role-name>
		</security-role-ref>
	</portlet>
</portlet-app>