text:
module RailsDbObjects
  class DbObjectsCreator
    attr_reader :objects

    def initialize
      @objects = {}
    end

    def register_files(files)
      files.each do |file|
        object_name = File.basename(file, File.extname(file))
        object_type = File.dirname(file.to_s).to_s.split('/').last.upcase

        @objects[object_type] ||= {}

        content = File.read(file)
        content_lines = content.split("\n")

        # Reject the commented lines from the file
        sql_content = content_lines.reject { |x| x.strip =~ /^--/ || x.strip =~ /^#/ }.join("\n")

        file_obj = {
          name: object_name,
          type: object_type,
          debug: false,
          directives: [],
          path: file,
          sql_content: sql_content,
          status: :none,
          requires: [],
          silent: false,
          keep: false,
          nodrop: false,
          deleted: false,
          nocreate: false,
          dbschema: Rails.configuration.rails_db_objects[:objects_dbschema],
          dropsql: [],
          createsql: [],
          vanilla: false,
          condition: [],
          dropconditionruby: [],
          createconditionruby: [],
          beforedropruby: [],
          beforedropsql: [],
          afterdropruby: [],
          afterdropsql: [],
          beforecreateruby: [],
          beforecreatesql: [],
          aftercreateruby: [],
          aftercreatesql: []
        }

        # Detect directives in commentary
        directives = extract_from_comments(content_lines)

        # puts "directives: #{directives.inspect}"
        directives.each { |directive| prepare_directive(file_obj, directive) }

        @objects[object_type][object_name] = file_obj
      end
    end

    def drop_objects
      reset_objects_status!
      @objects.keys.each do |object_type|
        @objects[object_type].each do |_name, object|
          drop_object(object)
        end
      end
    end

    def create_objects
      reset_objects_status!
      @objects.keys.each do |object_type|
        @objects[object_type].each do |_name, object|
          create_object(object)
        end
      end
    end

    private

    def full(name)
      prefix = @dbschema.blank? ? '' : "#{@dbschema}."
      "#{prefix}#{wrap_name(name)}"
    end

    def wrap_name(name)
      adapter_name = ActiveRecord::Base.connection.adapter_name

      case adapter_name
      when 'PostgreSQL'
        "\"#{name}\""
      when 'MySQL'
        "`#{name}`"
      when 'SQLServer'
        "[#{name}]"
      end
    end

    def extract_from_comments(content_lines)
      dir_lines = content_lines.select { |x| x.strip =~ /^--/ || x.strip =~ /^#/ }.map(&:strip)
      dir_lines.map { |x| /^--/.match?(x) ? x[2..-1] : x[1..-1] }.select { |x| x =~ /^!/ }
    end

    # rubocop:disable Metrics/AbcSize
    def prepare_directive(file_obj, directive)
      file_obj[:debug] = /^!debug/.match?(directive) unless file_obj[:debug]
      file_obj[:directives] << directive
      file_obj[:requires] += directive.split(' ')[1..-1] if /^!require /.match?(directive)
      file_obj[:vanilla] = /^!vanilla/.match?(directive) unless file_obj[:vanilla]
      file_obj[:nocreate] = file_obj[:deleted] = /^!deleted/.match?(directive) unless file_obj[:deleted]
      file_obj[:silent] = /^!silent/.match?(directive) unless file_obj[:silent]
      file_obj[:nodrop] = file_obj[:keep] = /^!keep/.match?(directive) unless file_obj[:keep]
      file_obj[:dbschema] = directive.split(' ')[1..-1] if /^!schema/.match?(directive)
      file_obj[:dropconditionruby] << directive.split(' ')[1..-1].join(' ') if /^!dropconditionruby /.match?(directive)
      file_obj[:createconditionruby] << directive.split(' ')[1..-1].join(' ') if /^!createconditionruby /.match?(directive)
      file_obj[:condition] << directive.split(' ')[1..-1].join(' ') if /^!condition /.match?(directive)
      file_obj[:beforedropsql] << directive.split(' ')[1..-1].join(' ') if /^!beforedropsql /.match?(directive)
      file_obj[:dropsql] << directive.split(' ')[1..-1].join(' ') if /^!dropsql /.match?(directive)
      file_obj[:afterdropsql] << directive.split(' ')[1..-1].join(' ') if /^!afterdropsql /.match?(directive)
      file_obj[:beforecreatesql] << directive.split(' ')[1..-1].join(' ') if /^!beforecreatesql /.match?(directive)
      file_obj[:createsql] << directive.split(' ')[1..-1].join(' ') if /^!createsql /.match?(directive)
      file_obj[:aftercreatesql] << directive.split(' ')[1..-1].join(' ') if /^!aftercreatesql /.match?(directive)
    end
    # rubocop:enable Metrics/AbcSize

    def reset_objects_status!
      @objects.keys.each do |object_type|
        @objects[object_type].each do |_name, object|
          object[:status] = :none
        end
      end
    end

    def conditional_ruby(condition, object)
      interpolated_command = object.instance_eval('"' + condition.gsub(/\"/, '\"') + '"')
      condition = object.instance_eval(interpolated_command)
      if object[:debug]
        puts '=' * 80
        puts "interpolated_command: #{interpolated_command}"
        puts '=' * 80
        puts "condition: #{condition.inspect}"
        puts '=' * 80
      end
      condition ? true : false
    end

    def interpolate_sql(sql, object)
      object.instance_eval('"' + sql.gsub(/\"/, '\"') + '"')
    end

    # rubocop:disable Metrics/AbcSize
    def drop_object(object)
      return if object[:nodrop]

      return if object[:status] == :loaded

      object_type = object[:type]
      name = object[:name]
      @dbschema = (object[:dbschema] || []).clone

      raise "Error: Circular file reference! (#{object_type} #{name})" if object[:status] == :inprogress

      full_name = full(name)

      if object[:dropconditionruby].compact.any?
        condition = conditional_ruby(object[:dropconditionruby].join("\n"), object)
        if condition
          puts "RUBY CONDITION MET FOR #{object_type} #{full_name} #{condition}"
        else
          puts "RUBY CONDITION NOT MET FOR #{object_type} #{full_name} #{condition}"
          return
        end
      elsif object[:condition].compact.any?
        condition = !ActiveRecord::Base.connection.select_rows(object[:condition].join("\n")).empty?
        if condition
          puts "SQL CONDITION MET FOR #{object_type} #{full_name}"
        else
          puts "SQL CONDITION NOT MET FOR #{object_type} #{full_name}"
          return
        end
      end

      if object[:debug]
        puts '=' * 80
        puts "DROP OBJECT #{name} / #{object[:path]}"
        puts '=' * 80
        puts object.to_json
        puts '=' * 80
      end

      object[:requires].each do |requirement|
        requires = requirement.split('/', 2)
        required_object = requires.last
        required_type = requires.first.upcase if requires.length == 2
        required_type ||= object_type
        drop_object @objects[required_type.upcase][required_object]
      end

      sql = if object[:dropsql].compact.empty? && !object[:vanilla]
              "DROP #{object_type} #{full_name};"
            else
              interpolate_sql(object[:dropsql].compact.join(";\n"), object)
            end

      begin
        conditional_ruby(object[:beforedropruby].join("\n"), object) unless object[:beforedropruby].empty?
        ActiveRecord::Base.connection.exec_query(object[:beforedropsql].join("\n")) unless object[:beforedropsql].empty?
        ActiveRecord::Base.connection.exec_query(sql)
        ActiveRecord::Base.connection.exec_query(object[:afterdropsql].join("\n")) unless object[:afterdropsql].empty?
        puts "DROP #{object_type} #{full_name}... OK"
        conditional_ruby(object[:afterdropruby].join("\n"), object) unless object[:afterdropruby].empty?
      rescue StandardError => e
        unless object[:debug]
          puts '#' * 80
          puts e.message.to_s
          puts "-"*80
          #puts "#{e.backtrace}"
          #puts '-' * 80
          puts "WARNING: >>#{sql}<<... ERROR"
          puts '#' * 80
        end
      end

      object[:status] = :loaded
    end

    def create_object(object)
      return if object[:nocreate]

      return if object[:status] == :loaded

      object_type = object[:type]
      name = object[:name]

      raise "Error: Circular file reference! (#{object_type} #{name})" if object[:status] == :inprogress

      object[:status] = :inprogress
      @dbschema = (object[:dbschema] || []).clone

      full_name = full(name)

      if object[:createconditionruby].compact.any?
        condition = conditional_ruby(object[:createconditionruby].join("\n"), object)
        if condition
          puts "RUBY CONDITION MET FOR #{object_type} #{full_name} / #{condition}"
        else
          puts "RUBY CONDITION NOT MET FOR #{object_type} #{full_name}"
          return
        end
      elsif object[:condition].compact.any?
        condition = ActiveRecord::Base.connection.select_rows(object[:condition].join("\n")).empty?
        if condition
          puts "CONDITION MET FOR #{object_type} #{full_name}"
        else
          puts "CONDITION NOT MET FOR #{object_type} #{full_name}"
          return
        end
      end

      if object[:debug]
        puts '=' * 80
        puts "CREATE OBJECT #{name} / #{object[:path]}"
        puts '=' * 80
        puts object.to_json
        puts '=' * 80
      end
      # skip empty sql content
      if object[:sql_content].strip.blank?
        puts "#{object_type} #{name} EMPTY... SKIPPING"
        return
      end

      create_dependencies(object, object_type)

      sql = if object[:vanilla]
              interpolate_sql(object[:sql_content], object)
            elsif object[:createsql].compact.empty?
              "CREATE #{object_type} #{full_name}\n#{object[:sql_content]}"
            else
              interpolate_sql(object[:createsql].compact.join(";\n"), object)
            end

      begin
        conditional_ruby(object[:beforecreateruby].join("\n"), object) unless object[:beforecreateruby].empty?
        ActiveRecord::Base.connection.exec_query(object[:beforecreatesql].join("\n")) unless object[:beforecreatesql].empty?
        ActiveRecord::Base.connection.exec_query(sql.to_s)
        ActiveRecord::Base.connection.exec_query(object[:aftercreatesql].join("\n")) unless object[:aftercreatesql].empty?
        conditional_ruby(object[:aftercreateruby].join("\n"), object) unless object[:aftercreateruby].empty?
        puts "CREATE #{object_type} #{full_name}... OK"
      rescue StandardError => e
        unless object[:silent]
          puts '#' * 80
          puts e.message.to_s
          puts '-' * 80
          puts sql.to_s
          puts '-' * 80
          puts "WARNING: CREATE #{object_type} #{full_name}... ERROR"
          puts '#' * 80
        end
      end

      object[:status] = :loaded
    end
    # rubocop:enable Metrics/AbcSize

    def create_dependencies(object, object_type)
      object[:requires].each do |requirement|
        requires = requirement.split('/', 2)
        required_object = requires.last
        required_type = requires.first.upcase if requires.length == 2
        required_type ||= object_type
        create_object(@objects[required_type.upcase][required_object])
      end
    end
  end
end


text:
<?php
class Curso extends Eloquent { //Todos los modelos deben extender la clase Eloquent

    public function cvu(){
        return $this->belongsTo('CVU', 'id_cvu');
    }

    protected $table = 'Cursos';
    protected $fillable = array('id_cvu', 'nom_curso', 'desc_curso');
}

redpajama_set_name: RedPajamaGithub


text:
package com.sksamuel.avro4s

import org.scalatest.{WordSpec, Matchers}

class TemplateGeneratorTest extends WordSpec with Matchers {

  "TemplateGenerator" should {
    "generate a file per enum" in {
      val enums = TemplateGenerator(Seq(EnumType("com.a", "Boo", Seq("A", "B")), EnumType("com.a", "Foo", Seq("A", "B"))))
      enums shouldBe Seq(Template("com/a/Boo", "java", "package com.a;\n\n//auto generated code by avro4s\npublic enum Boo{\n    A, B\n}"), Template("com/a/Foo", "java", "package com.a;\n\n//auto generated code by avro4s\npublic enum Foo{\n    A, B\n}"))
    }
    "generate one file for all records of same namespace" in {
      val enums = TemplateGenerator(Seq(RecordType("com.a", "Boo", Seq(FieldDef("name", PrimitiveType.String), FieldDef("bibble", PrimitiveType.Long))), RecordType("com.a", "Foo", Seq(FieldDef("dibble", PrimitiveType.Double), FieldDef("bibble", PrimitiveType.Boolean)))))
      enums shouldBe Seq(Template("com/a/domain", "scala", "package com.a\n\n//auto generated code by avro4s\ncase class Boo(\n  name: String,\n  bibble: Long\n)\n\n//auto generated code by avro4s\ncase class Foo(\n  dibble: Double,\n  bibble: Boolean\n)"))
    }
  }
}


text:
package org.onetwo.common.apiclient.utils;

import org.onetwo.common.exception.ErrorType;

/**
 * @author wayshall
 * <br/>
 */
public abstract class ApiClientConstants {

	public static enum ApiClientErrors implements ErrorType {
		REQUEST_MAPPING_NOT_PRESENT("@RequestMapping not present"),
		REQUEST_MAPPING_NOT_FOUND("@RequestMapping not found on method: %s"),
		REQUEST_BODY_ONLY_ONCE("There can be only one @RequstBody on method: %s"),
		EXECUTE_REST_ERROR("execute rest error for interface: %s");

		private String errorMessage;

		private ApiClientErrors(String errorMessage) {
			this.errorMessage = errorMessage;
		}

		@Override
		public String getErrorCode() {
			return name();
		}

		@Override
		public String getErrorMessage() {
			return errorMessage;
		}

	}

}


text:
/*
   statusbar-overlay sets the background color for the overlay. Black text is the default when the statusbar plugin is not added. When the
   statusbar plugin is added, it also adds default setting to make the content white via:

       <preference name="StatusBarStyle" value="lightcontent"/>

   Setting the background color to black will allow the default light content (white text/icons) to show on it. The statusbar plugin is included
   in the config.xml file and will be added by the CLI when you build locally.

   See https://github.com/apache/cordova-plugin-statusbar
*/

.statusbar-overlay {
    background: #000000;
}

.align-center {
	text-align: center;
}

.red {
	color:red;
}

.row {
  margin-bottom: 30px;
}

.material-icons {
	font-size: 60px;
	color: #007aff;
}

.panel-left a {
	color:#FFF;
}

.panel-left a.warn {
	color:#FF0000;
}


text:
{% import "lib/memberHelpers.html" as memberHelpers -%}
{% import "lib/descendants.html" as descendants -%}
{% import "lib/paramList.html" as params -%}
{% extends 'export-base.template.html' -%}

{% block overview %}
  {% include "includes/class-overview.html" %}
{% endblock %}
{% block details %}
  {% block additional %}{% endblock %}
  {% include "includes/description.html" %}
  {$ memberHelpers.renderProperties(doc.staticProperties, 'static-properties', 'static-property', 'Static Properties') $}
  {$ memberHelpers.renderMethodDetails(doc.staticMethods, 'static-methods', 'static-method', 'Static Methods') $}
  {% if doc.constructorDoc %}

Constructor

  {$ memberHelpers.renderMethodDetail(doc.constructorDoc, 'constructor') $}{% endif %}

  {$ memberHelpers.renderProperties(doc.properties, 'instance-properties', 'instance-property', 'Properties') $}

  {$ memberHelpers.renderMethodDetails(doc.methods, 'instance-methods', 'instance-method', 'Methods') $}

  {% block annotations %}{% include "includes/annotations.html" %}{% endblock %}
{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.pierceboggan.employeedirectory">
	<uses-sdk android:minSdkVersion="15" />
	<uses-permission android:name="android.permission.CAMERA" />
	<uses-permission android:name="android.permission.INTERNET" />
	<application android:label="EmployeeDirectory"></application>
</manifest>


text:
/* eslint-disable max-lines */
import _ from 'lodash';
import { Election, irv } from 'caritat';

export default ({ playerVotes, vote, votes = [], candidates, player, players, game, round }) => {
    if (_.isEmpty(playerVotes)) {
        return [
            {
                type: 'show-ranked-list',
                payload: {
                    game: game.id,
                    round: round.id,
                    vote: _.keys(
                        _.pickBy(candidates, c => c.id === vote.id)
                    )[0],
                    ranked: [vote],
                    unranked: _.values(_.pickBy(candidates, (c, p) => p !== player.id))
                        .filter(c => c.id !== vote.id),
                },
            },
        ];
    }

    if (playerVotes.length === 2) {
        const otherCandidates = _.pickBy(candidates, (c, p) => p !== player.id);
        const base = [...playerVotes, vote];
        const ranked = [...base, ..._.differenceBy(_.values(otherCandidates), base, 'id')];
        const messages = [];

        messages.push({
            type: 'show-votes-message',
            payload: {
                game: game.id,
                round: round.id,
                vote: _.keys(
                    _.pickBy(candidates, c => c.id === vote.id)
                )[0],
                ranked,
            },
        });

        if (_.keys(votes).length === 5) {
            const election = new Election({
                candidates: _.map(players, p => p.id.toString()),
            });

            votes[player.id].push(_.findKey(candidates, c => c.id === vote.id));
            _.forIn(votes, v => election.addBallot(v));
            const winnerId = irv(election);
            const winner = candidates[winnerId];

            messages.push({
                type: 'show-winner-message',
                payload: {
                    goal: round.card,
                    winner,
                    player: _.find(players, { id: winnerId }),
                },
            });
        }
        return messages;
    }

    const otherCandidates = _.pickBy(candidates, (c, p) => p !== player.id);
    const ranked = [...playerVotes, vote];
    return [
        {
            type: 'show-ranked-list',
            payload: {
                game: game.id,
                round: round.id,
                vote: _.keys(
                    _.pickBy(candidates, c => c.id === vote.id)
                )[0],
                ranked,
                unranked: _.differenceBy(_.values(otherCandidates), ranked, 'id'),
            },
        },
    ];
};


text: from BinPy.Operations.operations import *


text:
import { injectReducer } from '../../store/reducers'
import injectSaga from '../../store/injectSaga'

export default (store) => ({
  path : 'routes',
  /*  Async getComponent is only invoked when route matches   */
  getComponent (nextState, cb) {
    /*  Webpack - use 'require.ensure' to create a split point
     and embed an async module loader (jsonp) when bundling   */
    require.ensure([], (require) => {
      /*  Webpack - use require callback to define
       dependencies for bundling   */
      const Routes = require('./containers/RoutesContainer').default
      const reducer = require('./modules/routes').default
      const sagas = require('./sagas').default

      /*  Add the reducer to the store on key 'routes'  */
      injectReducer(store, { key: 'routes', reducer })

      /* Run sagas */
      sagas.map((saga, index) => injectSaga(store, { key: `routes_${index}`, saga }))

      /*  Return getComponent   */
      cb(null, Routes)

      /* Webpack named bundle   */
    }, 'routes')
  },
})


text:
package logstash

import (
	"time"

	"github.com/elastic/beats/libbeat/outputs"
	"github.com/elastic/beats/libbeat/outputs/transport"
)

type logstashConfig struct {
	Index            string                `config:"index"`
	Port             int                   `config:"port"`
	LoadBalance      bool                  `config:"loadbalance"`
	BulkMaxSize      int                   `config:"bulk_max_size"`
	Timeout          time.Duration         `config:"timeout"`
	CompressionLevel int                   `config:"compression_level" validate:"min=0, max=9"`
	MaxRetries       int                   `config:"max_retries"       validate:"min=-1"`
	TLS              *outputs.TLSConfig    `config:"tls"`
	Proxy            transport.ProxyConfig `config:",inline"`
}

var (
	defaultConfig = logstashConfig{
		Port:             10200,
		LoadBalance:      false,
		BulkMaxSize:      2048,
		CompressionLevel: 3,
		Timeout:          30 * time.Second,
		MaxRetries:       3,
	}
)


text:
var Rabbus = require("rabbus");
var logger = require("../logging")("bus-factory");

module.exports = function createCustomerOrProducerPromise(rabbitPromise, entityName, _class, options, _entityType) {
    return rabbitPromise.then(function (rabbit) {
        var customerOrProducer = new Rabbus[_class](rabbit, options);
        customerOrProducer.use(function (err, message, properties, actions, next) {
            logger.error(err.message, err.stackTrace);
            throw err;
        });
        logger.debug('created ' + _class +  ' for ' + _entityType + ' ' + entityName);
        return customerOrProducer;
    });
};


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns="http://shanque.zhangshuoyin.cn" versionCode="0.8,1.0">
	<application setting="true">
		<name><![CDATA[系统卡券]]></name>
		<identifie><![CDATA[we7_coupon]]></identifie>
		<version><![CDATA[4.2]]></version>
		<type><![CDATA[business]]></type>
		<ability><![CDATA[山雀卡券]]></ability>
		<description><![CDATA[山雀卡券]]></description>
		<author><![CDATA[山雀之家]]></author>
		<url><![CDATA[http://shanque.zhangshuoyin.cn]]></url>
	</application>
	<platform>
		<subscribes>
		</subscribes>
		<handles>
		</handles>
		<rule embed="false" />
		<card embed="false" />
	</platform>
	<bindings>
		<cover>
			<entry title="会员卡入口设置" do="card" state="" direct="false" />
			<entry title="收银台入口设置" do="clerk" state="" direct="false" />
		</cover>
		<menu>
			<entry title="会员卡设置" do="membercard" state="" direct="false" />
			<entry title="会员卡管理" do="cardmanage" state="" direct="false" />
			<entry title="会员属性" do="memberproperty" state="" direct="false" />
			<entry title="优惠券管理" do="couponmanage" state="" direct="false" />
			<entry title="优惠券核销" do="couponconsume" state="" direct="false" />
			<entry title="优惠券派发" do="couponmarket" state="" direct="false" />
			<entry title="兑换优惠券" do="couponexchange" state="" direct="false" />
			<entry title="兑换真实物品" do="goodsexchange" state="" direct="false" />
			<entry title="门店管理" do="storelist" state="" direct="false" />
			<entry title="店员管理" do="clerklist" state="" direct="false" />
			<entry title="门店收银台" do="paycenter" state="" direct="false" />
			<entry title="工作台菜单设置" do="clerkdeskmenu" state="" direct="false" />
			<entry title="签到管理" do="signmanage" state="" direct="false" />
			<entry title="通知管理" do="noticemanage" state="" direct="false" />
			<entry title="会员积分统计" do="statcredit1" state="" direct="false" />
			<entry title="会员余额统计" do="statcredit2" state="" direct="false" />
			<entry title="会员现金消费统计" do="statcash" state="" direct="false" />
			<entry title="会员卡统计" do="statcard" state="" direct="false" />
			<entry title="收银台收款统计" do="statpaycenter" state="" direct="false" />
			<entry title="微信卡券回复" do="wxcardreply" state="" direct="false" />
		</menu>
		<profile>
			<entry title="会员卡" do="card" state="" direct="false" />
			<entry title="兑换商城" do="activity" state="" direct="false" />
		</profile>
	</bindings>
	<permissions>
	</permissions>
	<install><![CDATA[install.php]]></install>
	<uninstall><![CDATA[]]></uninstall>
	<upgrade><![CDATA[upgrade.php]]></upgrade>
</manifest>


text:
require 'linguist/blob_helper'

module Linguist
  # A FileBlob is a wrapper around a File object to make it quack
  # like a Grit::Blob. It provides the basic interface: `name`,
  # `data`, and `size`.
  class FileBlob
    include BlobHelper

    # Public: Initialize a new FileBlob from a path
    #
    # path      - A path String that exists on the file system.
    # base_path - Optional base to relativize the path
    #
    # Returns a FileBlob.
    def initialize(path, base_path = nil)
      @path = path
      @name = base_path ? path.sub("#{base_path}/", '') : path
    end

    # Public: Filename
    #
    # Examples
    #
    #   FileBlob.new("/path/to/linguist/lib/linguist.rb").name
    #   # =>  "/path/to/linguist/lib/linguist.rb"
    #
    #   FileBlob.new("/path/to/linguist/lib/linguist.rb",
    #                "/path/to/linguist").name
    #   # =>  "lib/linguist.rb"
    #
    # Returns a String
    attr_reader :name

    # Public: Read file permissions
    #
    # Returns a String like '100644'
    def mode
      File.stat(@path).mode.to_s(8)
    end

    # Public: Read file contents.
    #
    # Returns a String.
    def data
      File.binread(@path)
    end

    # Public: Get byte size
    #
    # Returns an Integer.
    def size
      File.size(@path)
    end
  end
end


text:
.class public Landroid/bluetooth/BluetoothBipr;
.super Ljava/lang/Object;
.source "BluetoothBipr.java"

# interfaces
.implements Landroid/bluetooth/BluetoothProfileManager$BluetoothProfileBehavior;

# static fields
.field private static final DBG:Z = true

.field private static final TAG:Ljava/lang/String; = "BIP fw"

.field private static final VDBG:Z = true

# instance fields
.field private mConnection:Landroid/content/ServiceConnection;

.field private final mContext:Landroid/content/Context;

.field private mService:Landroid/bluetooth/IBluetoothBipr;

# direct methods
.method public constructor <init>(Landroid/content/Context;)V
    .locals 3
    .parameter "context"

    .prologue
    .line 77
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 65
    new-instance v0, Landroid/bluetooth/BluetoothBipr$1;

    invoke-direct {v0, p0}, Landroid/bluetooth/BluetoothBipr$1;-><init>(Landroid/bluetooth/BluetoothBipr;)V

    iput-object v0, p0, Landroid/bluetooth/BluetoothBipr;->mConnection:Landroid/content/ServiceConnection;

    .line 78
    iput-object p1, p0, Landroid/bluetooth/BluetoothBipr;->mContext:Landroid/content/Context;

    .line 79
    new-instance v0, Landroid/content/Intent;

    const-class v1, Landroid/bluetooth/IBluetoothBipr;

    invoke-virtual {v1}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    iget-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mConnection:Landroid/content/ServiceConnection;

    const/4 v2, 0x1

    invoke-virtual {p1, v0, v1, v2}, Landroid/content/Context;->bindService(Landroid/content/Intent;Landroid/content/ServiceConnection;I)Z

    move-result v0

    if-nez v0, :cond_0

    .line 81
    const-string v0, "BIP fw"

    const-string v1, "Could not bind to Bluetooth BIP Service"

    invoke-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 83
    :cond_0
    return-void
.end method

.method static synthetic access$002(Landroid/bluetooth/BluetoothBipr;Landroid/bluetooth/IBluetoothBipr;)Landroid/bluetooth/IBluetoothBipr;
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 55
    iput-object p1, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    return-object p1
.end method

# virtual methods
.method public declared-synchronized close()V
    .locals 4

    .prologue
    .line 87
    monitor-enter p0

    :try_start_0
    iget-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    if-eqz v1, :cond_0

    .line 88
    const/4 v1, 0x0

    iput-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    .line 91
    :cond_0
    iget-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mConnection:Landroid/content/ServiceConnection;

    if-eqz v1, :cond_1

    .line 92
    iget-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mContext:Landroid/content/Context;

    iget-object v2, p0, Landroid/bluetooth/BluetoothBipr;->mConnection:Landroid/content/ServiceConnection;

    invoke-virtual {v1, v2}, Landroid/content/Context;->unbindService(Landroid/content/ServiceConnection;)V

    .line 93
    const/4 v1, 0x0

    iput-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mConnection:Landroid/content/ServiceConnection;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0
    .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0

    .line 98
    :cond_1
    :goto_0
    monitor-exit p0

    return-void

    .line 95
    :catch_0
    move-exception v0

    .line 96
    .local v0, e:Ljava/lang/Exception;
    :try_start_1
    const-string v1, "BIP fw"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "Exception occurred in close(): "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    goto :goto_0

    .line 87
    .end local v0           #e:Ljava/lang/Exception;
    :catchall_0
    move-exception v1

    monitor-exit p0

    throw v1
.end method

.method public connect(Landroid/bluetooth/BluetoothDevice;)Z
    .locals 1
    .parameter "device"

    .prologue
    .line 101
    const/4 v0, 0x0

    return v0
.end method

.method public disconnect(Landroid/bluetooth/BluetoothDevice;)Z
    .locals 4
    .parameter "device"

    .prologue
    .line 105
    iget-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    if-eqz v1, :cond_0

    .line 107
    :try_start_0
    iget-object v1, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    invoke-interface {v1, p1}, Landroid/bluetooth/IBluetoothBipr;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    move-result v1

    .line 116
    :goto_0
    return v1

    .line 108
    :catch_0
    move-exception v0

    .line 109
    .local v0, e:Landroid/os/RemoteException;
    const-string v1, "BIP fw"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "Exception occurred in disconnect(): "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 116
    .end local v0           #e:Landroid/os/RemoteException;
    :goto_1
    const/4 v1, 0x0

    goto :goto_0

    .line 113
    :cond_0
    const-string v1, "BIP fw"

    const-string/jumbo v2, "mService is null"

    invoke-static {v1, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 114
    const-string v1, "BIP fw"

    new-instance v2, Ljava/lang/Throwable;

    invoke-direct {v2}, Ljava/lang/Throwable;-><init>()V

    invoke-static {v2}, Landroid/util/Log;->getStackTraceString(Ljava/lang/Throwable;)Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_1
.end method

.method public getConnectedDevices()Ljava/util/Set;
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/Set",
            "<",
            "Landroid/bluetooth/BluetoothDevice;",
            ">;"
        }
    .end annotation

    .prologue
    .line 138
    iget-object v2, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    if-eqz v2, :cond_0

    .line 139
    new-instance v0, Ljava/util/HashSet;

    invoke-direct {v0}, Ljava/util/HashSet;-><init>()V

    .line 141
    .local v0, devices:Ljava/util/HashSet;,"Ljava/util/HashSet<Landroid/bluetooth/BluetoothDevice;>;"
    :try_start_0
    iget-object v2, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    invoke-interface {v2}, Landroid/bluetooth/IBluetoothBipr;->getConnectedDevice()Landroid/bluetooth/BluetoothDevice;

    move-result-object v2

    invoke-virtual {v0, v2}, Ljava/util/HashSet;->add(Ljava/lang/Object;)Z
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 151
    .end local v0           #devices:Ljava/util/HashSet;,"Ljava/util/HashSet<Landroid/bluetooth/BluetoothDevice;>;"
    :goto_0
    return-object v0

    .line 143
    .restart local v0       #devices:Ljava/util/HashSet;,"Ljava/util/HashSet<Landroid/bluetooth/BluetoothDevice;>;"
    :catch_0
    move-exception v1

    .line 144
    .local v1, e:Landroid/os/RemoteException;
    const-string v2, "BIP fw"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Exception occurred in getConnectedDevices(): "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 151
    .end local v0           #devices:Ljava/util/HashSet;,"Ljava/util/HashSet<Landroid/bluetooth/BluetoothDevice;>;"
    .end local v1           #e:Landroid/os/RemoteException;
    :goto_1
    const/4 v0, 0x0

    goto :goto_0

    .line 148
    :cond_0
    const-string v2, "BIP fw"

    const-string/jumbo v3, "mService is null"

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 149
    const-string v2, "BIP fw"

    new-instance v3, Ljava/lang/Throwable;

    invoke-direct {v3}, Ljava/lang/Throwable;-><init>()V

    invoke-static {v3}, Landroid/util/Log;->getStackTraceString(Ljava/lang/Throwable;)Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_1
.end method

.method public getState(Landroid/bluetooth/BluetoothDevice;)I
    .locals 5
    .parameter "device"

    .prologue
    .line 120
    iget-object v2, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    if-eqz v2, :cond_1

    .line 123
    :try_start_0
    iget-object v2, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    invoke-interface {v2}, Landroid/bluetooth/IBluetoothBipr;->getConnectedDevice()Landroid/bluetooth/BluetoothDevice;

    move-result-object v0

    .line 124
    .local v0, current:Landroid/bluetooth/BluetoothDevice;
    if-eqz v0, :cond_0

    invoke-virtual {v0, p1}, Landroid/bluetooth/BluetoothDevice;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    iget-object v2, p0, Landroid/bluetooth/BluetoothBipr;->mService:Landroid/bluetooth/IBluetoothBipr;

    invoke-interface {v2}, Landroid/bluetooth/IBluetoothBipr;->getState()I
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    move-result v2

    .line 134
    .end local v0           #current:Landroid/bluetooth/BluetoothDevice;
    :goto_0
    return v2

    .line 124
    .restart local v0       #current:Landroid/bluetooth/BluetoothDevice;
    :cond_0
    const/4 v2, 0x2

    goto :goto_0

    .line 126
    .end local v0           #current:Landroid/bluetooth/BluetoothDevice;
    :catch_0
    move-exception v1

    .line 127
    .local v1, e:Landroid/os/RemoteException;
    const-string v2, "BIP fw"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "Exception occurred in getState(): "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 134
    .end local v1           #e:Landroid/os/RemoteException;
    :goto_1
    const/4 v2, 0x5

    goto :goto_0

    .line 131
    :cond_1
    const-string v2, "BIP fw"

    const-string/jumbo v3, "mService is null"

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 132
    const-string v2, "BIP fw"

    new-instance v3, Ljava/lang/Throwable;

    invoke-direct {v3}, Ljava/lang/Throwable;-><init>()V

    invoke-static {v3}, Landroid/util/Log;->getStackTraceString(Ljava/lang/Throwable;)Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_1
.end method


text:
"""

# nfl/pgf.py
# interactive search of player_game_finder

"""
import logging

import pandas as pd
from .gf import GameFinder

class PlayerGameFinder(GameFinder):
    """
    Interactive command line app

    """

    prompt = "player_game_finder> "
    intro = "Welcome to Player Game Finder! Type ? to list commands"

    def do_search(self, inp):
        """
        Search for stats

        Args:
            inp(str):

        Returns:
            None

        """
        logging.debug(inp)
        file_name = self.path / f"{self.seas}_{self.opp}_{self.pos}.csv"
        if file_name.is_file():
            df = self.read_csv(file_name)
            self.print_results(df)
        else:
            vals = self.gf_search()
            df = pd.DataFrame(vals)
            df = self.clean_results(df, self.pos)
            if self.pos == "QB":
                cols = self.basecols + self.qbcols
            else:
                cols = self.basecols + self.flexcols
            self.to_csv(df[cols], file_name)
            self.print_results(df[cols])

if __name__ == "__main__":
    pass


text:
#ifndef SRC_VNSW_AGENT_OVS_TOR_AGENT_OVSDB_CLIENT_HA_STALE_L2_ROUTE_H_
#define SRC_VNSW_AGENT_OVS_TOR_AGENT_OVSDB_CLIENT_HA_STALE_L2_ROUTE_H_

#include <base/lifetime.h>
#include <ovsdb_entry.h>
#include <ovsdb_object.h>
#include <ovsdb_client_idl.h>

class BridgeRouteEntry;

namespace OVSDB {
class HaStaleDevVnEntry;
class HaStaleL2RouteEntry;
class ConnectionStateEntry;

class HaStaleL2RouteTable : public OvsdbDBObject {
public:
    HaStaleL2RouteTable(HaStaleDevVnEntry *dev_vn,
                        AgentRouteTable *table);
    virtual ~HaStaleL2RouteTable();

    KSyncEntry *Alloc(const KSyncEntry *key, uint32_t index);
    KSyncEntry *DBToKSyncEntry(const DBEntry*);

    DBFilterResp OvsdbDBEntryFilter(const DBEntry *entry,
                                    const OvsdbDBEntry *ovsdb_entry);

    Agent *agent() const;
    void ManagedDelete();
    virtual void EmptyTable();
    Ip4Address dev_ip() const;
    uint32_t vxlan_id() const;
    const std::string &vn_name() const;
    const std::string &vrf_name() const;

    void UpdateParams(HaStaleDevVnEntry *dev_vn);

private:
    friend class HaStaleL2RouteEntry;
    void OvsdbNotify(OvsdbClientIdl::Op, struct ovsdb_idl_row *) {}
    OvsdbDBEntry *AllocOvsEntry(struct ovsdb_idl_row *row) { return NULL; }

    LifetimeRef<HaStaleL2RouteTable> table_delete_ref_;
    // take reference to a dummy dev_vn entry to hold peer till
    // route table is deleted. route object cannot hold reference
    // to dev_vn entry creating it, as it will cause cyclic dependency
    KSyncEntry::KSyncEntryPtr dev_vn_ref_;
    ConnectionStateEntry *state_;
    Ip4Address dev_ip_;
    uint32_t vxlan_id_;
    // take reference to the vrf while exporting route, to assure sanity
    // of vrf pointer even if Add route request fails, due to any reason
    VrfEntryRef vrf_;
    std::string vn_name_;
    DISALLOW_COPY_AND_ASSIGN(HaStaleL2RouteTable);
};

class HaStaleL2RouteEntry : public OvsdbDBEntry {
public:
    HaStaleL2RouteEntry(HaStaleL2RouteTable *table,
                          const std::string &mac);
    ~HaStaleL2RouteEntry();

    void AddMsg(struct ovsdb_idl_txn *);
    void ChangeMsg(struct ovsdb_idl_txn *);
    void DeleteMsg(struct ovsdb_idl_txn *);

    bool Sync(DBEntry*);
    bool IsLess(const KSyncEntry&) const;
    std::string ToString() const {return "Ha Stale L2 Route Entry";}
    KSyncEntry* UnresolvedReference();

    const std::string &mac() const;
    uint32_t vxlan_id() const;
    bool IsStale() const;

protected:
    virtual bool IsNoTxnEntry() { return true; }

private:
    friend class HaStaleL2RouteTable;
    friend class VrfRouteReflectorTable;

    void StaleClearCb();

    std::string mac_;
    uint32_t path_preference_;
    uint32_t vxlan_id_;
    uint64_t time_stamp_;
    DISALLOW_COPY_AND_ASSIGN(HaStaleL2RouteEntry);
};
};

#endif //SRC_VNSW_AGENT_OVS_TOR_AGENT_OVSDB_CLIENT_HA_STALE_L2_ROUTE_H_


text:
<mat-card>
  <mat-card-header class="colored">

          {{workout.price}} €

      <mat-card-title class="title">{{workout.title}} {{workout.id}}</mat-card-title>
      <mat-card-subtitle>{{workout.sport.name}} </mat-card-subtitle>
  </mat-card-header>

<mat-icon class="mat-72">fitness_center</mat-icon>

  <mat-card-content>

        {{workout.startdate | date: 'EEEE d MMMM'}}

{{workout.address.city}}

début

        {{workout.startdate | date: 'shortTime'}}

fin

        {{workout.enddate | date: 'shortTime'}}

{{workout.description}}

{{workout.outfit}}

{{workout.notice}}

{{tag.name}}

  </mat-card-content>
</mat-card>


text:
ECHO OFF
REM Windows Batch Script to print PDF file by Adobe Acrobat Reader(TM)

REM Adjust path to Acrobat Reader Executable
SET ACROBAT.EXE=C:\Programme\Adobe\Reader 8.0\Reader\AcroRd32.exe

REM Execute Acrobat Reader and open Print Dialog:
REM Attention: Blocks until Acrobat Reader is closed by user
REM "%ACROBAT.EXE%" /p %1

REM Print Label on default Printer without user interaction:
START "" "%ACROBAT.EXE%" /h /p %1

REM Print Label on specified Printer without user interaction:
REM START "" "%ACROBAT.EXE%" /t %1 printername drivername portname
REM printername - The name of your printer.
REM drivername  - Your printer driver name.
REM portname    - The printer port.
REM Hint: The values may appear at the testpage printed by the Windows Print Manager.


text:
#import "Base.h"
#import "MBGSocialLeaderboard.h"
@interface common_Leaderboard_base : Base

@end


text:
package com.jaregu.database.queries.dialect;

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

import com.jaregu.database.queries.building.Query;
import com.jaregu.database.queries.building.QueryImpl;

public class Oracle12PlusDialect extends DefaultDialectImpl {

	@Override
	public Query toPagedQuery(Query query, Pageable pageable) {
		if (pageable.getLimit() != null) {
			List<Object> parameters = new ArrayList<>(query.getParameters().size() + 2);
			parameters.addAll(query.getParameters());
			StringBuilder newSql = new StringBuilder(query.getSql()).append("\n");
			if (pageable.getOffset() != null) {
				newSql.append("OFFSET ? ");
				parameters.add(pageable.getOffset());
			}
			newSql.append("ROWS FETCH NEXT ? ROWS ONLY");
			parameters.add(pageable.getLimit());

			return new QueryImpl(newSql.toString(), parameters, query.getAttributes(), this);
		}
		return query;
	}

	@Override
	public String getSuffix() {
		return "oracle";
	}
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="com.vardemin.wiwing.WiNewsFragment">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/news_recycler_view"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            android:layout_above="@+id/news_post_section">

        </android.support.v7.widget.RecyclerView>

        <RelativeLayout
            android:id="@+id/news_post_section"
            android:layout_width="fill_parent"
            android:orientation="horizontal"
            android:layout_height="wrap_content"
            android:background="@color/whiteTransparent"
            android:layout_alignParentBottom="true"
            android:padding="8dp">
                <LinearLayout
                    android:id="@+id/news_linear"
                    android:padding="8dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:layout_alignParentLeft="true"
                    android:layout_toLeftOf="@+id/news_button">
                    <EditText
                        android:id="@+id/news_header"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:hint="Header..."
                        android:inputType="textShortMessage"
                        android:singleLine="true" />
                    <EditText
                        android:id="@+id/news_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:inputType="textMultiLine"
                        android:hint="I`m going for a walk..." />
                </LinearLayout>

                <Button
                    android:id="@+id/news_button"
                    android:layout_width="100dp"
                    android:layout_height="100dp"
                    android:background="@drawable/post_btn"
                    android:layout_alignParentRight="true"
                    android:layout_alignBottom="@id/news_linear"/>

        </RelativeLayout>

    </RelativeLayout>
</FrameLayout>


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CMSCreateMenusTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
            if (!Schema::hasTable('_db_menus'))
            {
		Schema::create('_db_menus', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('icon_class')->nullable();
			$table->string('label');
			$table->integer('weight')->default(0);
			$table->string('href')->nullable();
			$table->integer('parent_id')->nullable();
                        $table->timestamp('created_at')->default('0000-00-00 00:00:00');
                        $table->timestamp('updated_at')->default('0000-00-00 00:00:00');
		});
            }
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
            Schema::dropIfExists('_db_menus');
	}

}


text:
import { Observable } from 'rxjs';
export const toPromise = Observable.prototype.toPromise;
//# sourceMappingURL=toPromise.js.map


text:
using System;
using Xunit;

namespace Rhino.Mocks.Tests.RecordPlaybackSyntax
{

	public class RecordPlaybackTests
	{
		[Fact]
		public void CanRecordPlayback()
		{
			MockRepository mockRepository;
			mockRepository = new MockRepository();
			IFoo mockedFoo = mockRepository.StrictMock<IFoo>();
			using (mockRepository.Record())
			{
				Expect.Call(mockedFoo.Bar()).Return(42);
			}
			using (mockRepository.Playback())
			{
				Fooz fooz = new Fooz(mockedFoo);
				fooz.Barz();
			}
		}

		[Fact]
		public void PlaybackThrowsOtherExceptionDoesntReport()
		{
			MockRepository mockRepository;
			mockRepository = new MockRepository();
			IFoo mockedFoo = mockRepository.StrictMock<IFoo>();
			using (mockRepository.Record())
			{
				Expect.Call(mockedFoo.Bar()).Return(42);
			}
			Assert.Throws<ArgumentException>(delegate
			{
				using (mockRepository.Playback())
				{
					throw new ArgumentException();
				}
			});
		}

		[Fact]
		public void RecordThrowsOtherExceptionDoesntReport()
		{
			MockRepository mockRepository;
			mockRepository = new MockRepository();
			IFoo mockedFoo = mockRepository.StrictMock<IFoo>();
			Assert.Throws<ArgumentException>(() =>
			{
				using (mockRepository.Record())
				{
					mockedFoo.Bar(); //create expectation but doesn't setup return value
					throw new ArgumentException();
				}
			});
		}
	}

	internal interface IFoo
	{
		int Bar();
	}

	internal class Fooz
	{
		private readonly IFoo m_foo;

		public Fooz(IFoo foo)
		{
			m_foo = foo;
		}

		public void Barz()
		{
			m_foo.Bar();
		}
	}
}


text:
<?php

namespace Cyvelnet\EasyCart;

/*
 * Class CartInstance
 *
 * @package Cyvelnet\EasyCart
 */
use Cyvelnet\EasyCart\Collections\CartConditionCollection;
use Cyvelnet\EasyCart\Collections\CartItemCollection;
use Cyvelnet\EasyCart\Contracts\ConditionableContract;
use Cyvelnet\EasyCart\Contracts\ManipulatableInterface;
use DateTime;

/**
 * Class CartInstance.
 */
class Cart extends ConditionableContract implements ManipulatableInterface
{
    /**
     * @var
     */
    private $name;
    /**
     * @var
     */
    private $expiration;
    /**
     * @var \Cyvelnet\EasyCart\Collections\CartItemCollection
     */
    protected $items;

    /**
     * @var \Cyvelnet\EasyCart\Collections\CartConditionCollection
     */
    protected $conditions;

    /**
     * CartInstance constructor.
     *
     * @param $name
     * @param null $expiration
     */
    public function __construct($name, $expiration = null)
    {
        $this->name = $name;
        $this->expiration = $expiration;
        $this->items = new CartItemCollection();
        $this->conditions = new CartConditionCollection();
    }

    /**
     * get cart items stored in an cart instance.
     *
     * @return \Cyvelnet\EasyCart\CartItemCollection
     */
    public function getCartItemCollection()
    {
        return $this->items;
    }

    /**
     * verify if a cart is expired.
     *
     * @return bool
     */
    public function isExpired()
    {
        if (!$this->expiration) {
            return false;
        }

        return $this->expiration < new DateTime();
    }

    /**
     * get the expiration timestamp.
     *
     * @return int|null
     */
    public function expirationTimestamp()
    {
        if ($this->expiration instanceof \DateTime) {
            return $this->expiration->getTimestamp();
        }
    }

    /**
     * get a cart item by rowId.
     *
     * @param $rowId
     *
     * @return mixed
     */
    public function get($rowId)
    {
        return $this->getCartItemCollection()->get($rowId);
    }

    /**
     * add product to cart.
     *
     * @param $id
     * @param null  $name
     * @param null  $price
     * @param null  $qty
     * @param array $attributes
     * @param float $weight
     *
     * @return \Cyvelnet\EasyCart\CartItem|\Cyvelnet\EasyCart\Collections\CartItemCollection
     */
    public function add($id, $name = null, $price = null, $qty = null, $attributes = [], $weight = 0.0)
    {
        // helps to add item one by one
        if (is_array($id)) {
            $addedCartItemCollection = new CartItemCollection();
            foreach ($id as $row) {
                $addedCartItemCollection->push($this->add(
                    $row['id'],
                    $row['name'],
                    $row['price'],
                    $row['qty'],
                    array_key_exists('attributes', $row) ? $row['attributes'] : [],
                    array_key_exists('weight', $row) ? $row['weight'] : 0.0
                ));
            }

            return $addedCartItemCollection;
        } else {
            $item = new CartItem($id, $name, $price, $qty, $attributes, $weight);

            // append quantity instead of insert a new rows
            if ($this->exists($item->getRowId())) {

                // reuse the existing item and update its qty accordingly
                $existedItem = $this->getCartItemCollection()->get($item->getRowId());
                $existedItem->addQty($item->getQty());

                $item = $existedItem;
            }

            return $this->addToCollection($item);
        }
    }

    /**
     * remove a cart item row.
     *
     * @param $rowId
     *
     * @return bool
     */
    public function remove($rowId)
    {
        if (!$this->exists($rowId)) {
            return false;
        }

        $item = $this->get($rowId);

        if (false === $this->triggerEvent('cart.deleting', $item)) {
            return false;
        }

        $this->getCartItemCollection()->forget($rowId);

        $this->triggerEvent('cart.deleted', $rowId, $item);

        return true;
    }

    /**
     * update cart item by rowId.
     *
     * @param $rowId
     * @param array|int $qty
     *
     * @return \Cyvelnet\EasyCart\CartItem
     */
    public function update($rowId, $qty)
    {
        $item = $this->get($rowId);

        $updateData = is_array($qty) ? $qty : ['qty' => $qty];

        $item->mergeFromArray($updateData);

        // remove the item when has 0 qty

        if ($item->qty <= 0) {
            $this->remove($rowId);

            return false;
        }

        return $this->addToCollection($item);
    }

    /**
     * destroy a cart.
     */
    public function destroy()
    {
        app('session')->forget($this->name);
    }

    /**
     * retrieves cart content.
     *
     * @return \Cyvelnet\EasyCart\Collections\CartItemCollection
     */
    public function content()
    {
        return $this->getCartItemCollection();
    }

    /**
     * retrieves cart content.
     *
     * @return \Cyvelnet\EasyCart\Collections\CartItemCollection
     */
    public function items()
    {
        return $this->getCartItemCollection();
    }

    /**
     * filter out cart item.
     *
     * @param string|int|callable $id
     *
     * @return mixed
     */
    public function find($id)
    {
        if (is_callable($id)) {
            return $this->getCartItemCollection()->filter($id);
        }

        return $this->getCartItemCollection()->first(function ($item) use ($id) {
            return $item->id == $id;
        });
    }

    /**
     * filter out cart items by matching cart item id against an array of ids.
     *
     * @param array $ids
     *
     * @return \Cyvelnet\EasyCart\Collections\CartItemCollection
     */
    public function findByIds($ids = [])
    {
        return $this->find(function ($item) use ($ids) {
            return in_array($item->getId(), $ids);
        });
    }

    /**
     * get the total quantity of all cart items.
     *
     * @return int
     */
    public function qty()
    {
        return $this->getCartItemCollection()->sum(function (CartItem $item) {
            return $item->getQty();
        });
    }

    /**
     * get the total weight per cart.
     *
     * @return float|int
     */
    public function weight()
    {
        return $this->getCartItemCollection()->sum(function ($item) {
            return $item->getTotalWeight();
        });
    }

    /**
     * get cart total without charges.
     *
     * @return float|int
     */
    public function subtotal()
    {
        return $this->getCartItemCollection()->sum(function (CartItem $item) {
            return $item->subtotal();
        });
    }

    /**
     * get cart total with charges.
     *
     * @return float|int
     */
    public function total()
    {
        return $this->calculateTotal();
    }

    /**
     * render cart into view.
     *
     * @param null $view
     *
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
     */
    public function render($view = null, $instance = null)
    {
        if (!$view) {
            $view = 'easycart::cart';
        }

        return view($view, ['cart' => $this->instance($instance)]);
    }

    /**
     * add cart condition.
     *
     * @param array|CartCondition $condition
     *
     * @return bool
     */
    public function condition($condition)
    {
        if (is_array($condition)) {
            foreach ($condition as $item) {
                $this->condition($item);
            }
        }

        if (false === app('events')->dispatch('cart.condition.adding', $this)) {
            return false;
        }

        if ($condition instanceof CartCondition && $this->conditions->doesntHaveCondition($condition)) {
            $this->conditions->push($condition);

            $this->applyConditionToItems($condition);
        }

        $this->persistCart();

        return true;
    }

    /**
     * get applied conditions.
     *
     * @return mixed
     */
    public function getConditions()
    {
        return $this->conditions;
    }

    /**
     * remove a condition by its type.
     *
     * @param $type
     */
    public function removeConditionByType($type)
    {
        $toRemoves = $this->getConditions()->filter(function ($item) use ($type) {
            return $item->getType() === $type;
        });

        $toRemoves->each(function ($item, $key) use ($type) {
            $this->conditions->forget($key);

            $this->getCartItemCollection()->each(function ($item) use ($type) {
                $item->removeConditionByType($type);
            });
        });
    }

    /**
     * remove a condition by its name.
     *
     * @param $name
     */
    public function removeConditionByName($name)
    {
        $toRemoves = $this->getConditions()->filter(function ($item) use ($name) {
            return $item->getName() === $name;
        });

        $toRemoves->each(function ($item, $key) use ($name) {
            $this->conditions->forget($key);

            $this->getCartItemCollection()->each(function ($item) use ($name) {
                $item->removeConditionByName($name);
            });
        });
    }

    /**
     * remove all conditions.
     */
    public function removeAllConditions()
    {
        $this->getConditions()->each(function ($item, $key) {
            $this->conditions->pop();
        });

        $this->getCartItemCollection()->each(function (CartItem $item) {
            $item->removeAllConditions();
        });
    }

    /**
     * add a cart item to collection.
     *
     * @param $item
     *
     * @return \Cyvelnet\EasyCart\CartItem
     */
    protected function addToCollection($item)
    {
        if (false === $this->triggerEvent('cart.adding', $item)) {
            return false;
        }

        $cart = $this->getCartItemCollection();

        $cart->put($item->rowId, $item);

        $this->applyItemConditionToAllItems();

        $this->persistCart();

        $this->triggerEvent('cart.added', $item->rowId);

        return $item;
    }

    /**
     * @param $rowId
     *
     * @return bool
     */
    protected function exists($rowId)
    {
        return $this->getCartItemCollection()->has($rowId);
    }

    /**
     * get the conditions that should be calculated.
     *
     * @return mixed
     */
    protected function getCalculateableCondition()
    {
        return $this->getConditions()->filter(function (CartCondition $condition) {
            if ($condition->getType() !== 'tax') {
                if (($condition->getApplyMinimum() && !$condition->getApplyMinimumForEach()
                && $condition->getApplyMinimum() <= $this->subtotal())) {
                    return true;
                }

                if ($condition->getTarget() !== 'products' && !$condition->getApplyMinimum()) {
                    return true;
                }
            }
        });
    }

    protected function calculateTotal()
    {
        $sum = $this->items()->sum(function (CartItem $item) {
            return $item->total();
        });

        $this->getCalculateableCondition()->each(function (CartCondition $condition) use (&$sum) {
            $sum += $this->calculateValue($condition->getValue(), $sum, $condition->maxValue());
        });

        // calculate tax after all conditions
        return $this->calculateTaxes($sum);
    }

    private function applyItemConditionToAllItems()
    {
        $this->conditions->filter(function ($item) {
            return count($item->getProducts()) > 0;
        })->each(function ($condition) {
            $this->applyConditionToItems($condition);
        });
    }

    /**
     * apply the exact condition to cart item.
     *
     * @param $condition
     */
    private function applyConditionToItems($condition)
    {
        $this->items->each(function ($item) use ($condition) {
            $item->condition(clone $condition);
        });
    }

    private function getSumOfItems(array $ids = [])
    {
        return $this->items()->filter(function ($item) use ($ids) {
            return in_array($item->id, $ids);
        })->sum(function ($item) {
            return $item->total();
        });
    }

    /**
     * @param $event
     * @param array ...$param
     *
     * @return array|null
     */
    private function triggerEvent($event, ...$param)
    {
        return app('events')->dispatch($event, array_merge($param, [$this]));
    }

    /**
     * @param $cart
     */
    private function persistCart()
    {
        app('session')->put($this->name, $this);
    }
}


text:
import { RefObject, useEffect, useLayoutEffect, useRef } from "react";

export const useScrollListener = (
  listener: (event: Event) => void,
  elementRef: RefObject<HTMLElement>
) => {
  const listenerRef = useRef(listener);
  useLayoutEffect(() => {
    listenerRef.current = listener;
  });
  useEffect(() => {
    const element = elementRef.current;
    if (!element) return undefined;
    let ticking = false;
    const listener = (ev: Event) => {
      if (ticking) return;
      requestAnimationFrame(() => {
        listenerRef.current(ev);
        ticking = false;
      });
      ticking = true;
    };
    element.addEventListener("scroll", listener, { passive: true });
    return () => {
      element.removeEventListener("scroll", listener);
    };
  }, [elementRef]);
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>RenderStateContext</title>
<meta name="date" content="2022-10-27">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.facebook.litho

Class RenderStateContext

java.lang.Object

com.facebook.litho.RenderStateContext

All Implemented Interfaces:

CalculationStateContext

public class RenderStateContext
extends java.lang.Object
implements CalculationStateContext

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

MeasuredResultCache
getCache()

LithoNode
getCurrentRoot()

TreeFuture
getLayoutStateFuture()

int
getLayoutVersion()

PerfEvent
getPerfEventLogger()

TreeState
getTreeState()

boolean
isFutureReleased()

void
markLayoutUninterruptible()

void
release()

void
setLayoutStateFuture(TreeFuture layoutStateFuture)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getLayoutVersion

public int getLayoutVersion()

Specified by:

getLayoutVersion in interface CalculationStateContext

isFutureReleased

public boolean isFutureReleased()

Specified by:

isFutureReleased in interface CalculationStateContext

getLayoutStateFuture

public TreeFuture getLayoutStateFuture()

Specified by:

getLayoutStateFuture in interface CalculationStateContext

markLayoutUninterruptible

public void markLayoutUninterruptible()

getTreeState

public TreeState getTreeState()

Specified by:

getTreeState in interface CalculationStateContext

getCurrentRoot

public LithoNode getCurrentRoot()

getCache

public MeasuredResultCache getCache()

Specified by:

getCache in interface CalculationStateContext

release

public void release()

setLayoutStateFuture

public void setLayoutStateFuture(TreeFuture layoutStateFuture)

getPerfEventLogger

public PerfEvent getPerfEventLogger()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text: JSID Web Solutions Inc.


text:
        ./bin/bridgedb datasource "Entrez Gene"
#       # -> "http://vocabularies.bridgedb.org/ops#conventionalName"
#       #     This is the IRI for the BridgeDb conventional name.
#     Example 2) Detect the format of the input "ncbigene":
        ./bin/bridgedb datasource "ncbigene"
#       # -> "http://identifiers.org/idot/preferredPrefix"
#       #    This is the IRI for the identifiers.org (Miriam) preferred prefix.

#     More examples:
        ./bin/bridgedb datasource "ensembl"
        ./bin/bridgedb datasource "http://identifiers.org/ensembl/"

# To CONVERT a data source to another format, specify a term or IRI for "as".
#     Example) Convert the BridgeDb conventional name "Entrez Gene" to an identifiers.org preferred prefix:
        ./bin/bridgedb datasource "Entrez Gene" preferredPrefix
#       # -> "ncbigene"

#     More examples:
	./bin/bridgedb datasource "Entrez Gene" "http://identifiers.org/idot/preferredPrefix"
	./bin/bridgedb datasource "Entrez Gene" "http://www.w3.org/1999/02/22-rdf-syntax-ns#about"
	./bin/bridgedb datasource "Entrez Gene" id


text:
package org.openmhealth.shimmer.common.configuration;

import org.springframework.web.util.UriTemplate;

import java.util.Optional;

/**
 * @author Emerson Farrugia
 */
public class DefaultEndpointSettings implements EndpointSettings {

    private String id;
    private UriTemplate uriTemplate;
    private DateTimeQuerySettings effectiveDateTimeQuerySettings;
    private DateTimeQuerySettings creationDateTimeQuerySettings;
    private DateTimeQuerySettings modificationDateTimeQuerySettings;

    @Override
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public UriTemplate getUriTemplate() {
        return uriTemplate;
    }

    public void setUriTemplate(UriTemplate uriTemplate) {
        this.uriTemplate = uriTemplate;
    }

    @Override
    public Optional<DateTimeQuerySettings> getEffectiveDateTimeQuerySettings() {
        return Optional.ofNullable(effectiveDateTimeQuerySettings);
    }

    public void setEffectiveDateTimeQuerySettings(DateTimeQuerySettings settings) {
        this.effectiveDateTimeQuerySettings = settings;
    }

    @Override
    public Optional<DateTimeQuerySettings> getCreationDateTimeQuerySettings() {
        return Optional.ofNullable(creationDateTimeQuerySettings);
    }

    public void setCreationDateTimeQuerySettings(DateTimeQuerySettings settings) {
        this.creationDateTimeQuerySettings = settings;
    }

    @Override
    public Optional<DateTimeQuerySettings> getModificationDateTimeQuerySettings() {
        return Optional.ofNullable(modificationDateTimeQuerySettings);
    }

    public void setModificationDateTimeQuerySettings(DateTimeQuerySettings settings) {
        this.modificationDateTimeQuerySettings = settings;
    }
}


text:
# Unit 10
## Chapter 2: User Index

In this chapter, you will provide the index method for users.  The index of users should be available ONLY to the admins and not to the users or the general public.  The index will offer pagination and search capabilities.

### New Branch
Enter the command "git checkout -b 10-02-user_index".

### Gemfile
* Add the following lines to the end of the Gemfile:
```
# Pagination gems
gem 'bootstrap-will_paginate' # Twitter Bootstrap for pagination
gem 'will_paginate' # For pagination

gem 'ransack' # For searching users
```
* Enter the command "sh git_check.sh".
* Enter the following commands:
```
git add .
git commit -m "Added gems for paginating and searching the user index"
```

### Controller Test
* Add the following text to the index section of the file test/controllers/users_controller_test.rb:
```
  test 'should redirect index page when not logged in' do
    get :index
    assert_redirected_to root_path
  end

  test 'should redirect index page when logged in as a user' do
    sign_in @u1, scope: :user
    get :index
    assert_redirected_to root_path
  end

  test 'should not redirect index page when logged in as a super admin' do
    sign_in @a1, scope: :admin
    get :index
    assert :success
  end

  test 'should not redirect index page when logged in as a regular admin' do
    sign_in @a4, scope: :admin
    get :index
    assert :success
  end
```
* Enter the command "sh testc.sh".  The 4 new controller tests fail because of a missing route.

### Integration Test
* Enter the command "rails generate integration_test users_index".
* Replace the contents of the file test/integration/users_index_test.rb with the following:
```
require 'test_helper'

class UsersIndexTest < ActionDispatch::IntegrationTest
  def check_index_disabled
    visit users_path
    assert page.has_css?('title', text: full_title(''),
                                  visible: false)
    assert page.has_css?('h1', text: 'Home', visible: false)
  end

  def check_index_disabled_for_user(u)
    login_as(u, scope: :user)
    check_index_disabled
  end

  # rubocop:disable Metrics/AbcSize
  # rubocop:disable Metrics/MethodLength
  def check_index_enabled
    visit users_path
    assert page.has_css?('title', text: full_title('User Index'),
                                  visible: false)
    assert page.has_css?('h1', text: 'User Index')
    assert page.has_text?('Connery')
    assert page.has_text?('Lazenby')
    assert page.has_text?('Moore')
    assert page.has_text?('Dalton')
    assert page.has_text?('Brosnan')
    assert page.has_text?('Craig')
    assert page.has_text?('Blofeld')

    # Verify that index page provides access to profile pages
    assert page.has_link?('sconnery', href: user_path(@u1))
    assert page.has_link?('sean_connery@example.com', href: user_path(@u1))
    assert page.has_link?('glazenby', href: user_path(@u2))
    assert page.has_link?('george_lazenby@example.com', href: user_path(@u2))
    assert page.has_link?('rmoore', href: user_path(@u3))
    assert page.has_link?('roger_moore@example.com', href: user_path(@u3))
    assert page.has_link?('tdalton', href: user_path(@u4))
    assert page.has_link?('timothy_dalton@example.com', href: user_path(@u4))
    assert page.has_link?('pbrosnan', href: user_path(@u5))
    assert page.has_link?('pierce_brosnan@example.com', href: user_path(@u5))
    assert page.has_link?('dcraig', href: user_path(@u6))
    assert page.has_link?('daniel_craig@example.com', href: user_path(@u6))
    assert page.has_link?('eblofeld', href: user_path(@u7))
    assert page.has_link?('ernst_blofeld@example.com', href: user_path(@u7))

    # Verify that root page provides access to index page
    click_on 'Home'
    assert page.has_link?('User Index', href: users_path)
  end
  # rubocop:enable Metrics/AbcSize
  # rubocop:enable Metrics/MethodLength

  test 'users index page is not accessible to visitors' do
    check_index_disabled
  end

  test 'users index page is not accessible to users' do
    check_index_disabled_for_user(@u1)
    check_index_disabled_for_user(@u2)
    check_index_disabled_for_user(@u3)
    check_index_disabled_for_user(@u4)
    check_index_disabled_for_user(@u5)
    check_index_disabled_for_user(@u6)
    check_index_disabled_for_user(@u7)
  end

  test 'users index page is accessible to super admins' do
    login_as(@a1, scope: :admin)
    check_index_enabled
  end

  test 'users index page is accessible to regular admins' do
    login_as(@a4, scope: :admin)
    check_index_enabled
  end
end
```
* Enter the command "alias test1='rails test test/integration/users_index_test.rb'".
* Enter the command "test1".  All 4 tests fail because the method users_path is undefined.  Yes, it's the same issue causing the controller tests to fail.

### Routing
* In the config/routes.rb file, remove the line "get 'users/new'". This is covered by the Devise registration feature.
* In the config/routes.rb file, replace the line beginning with "resources :users" with the following:
```
  resources :users, only: [:show, :index]
```
* Enter the command "sh testc.sh".  All 4 controller tests fail because the index action is missing from the user controller.
* Enter the command "test1".  Again, all 4 integration tests fail because the index action is missing from the user controller.

### User Controller
* In the before_action section of the file app/controllers/users_controller.rb, add the following line:
```
  before_action :may_index_user, only: [:index]
```
* In the action section of the file app/controllers/users_controller.rb, add the following lines:
```
  # rubocop:disable Metrics/AbcSize
  def index
    @search = User.search(params[:q].presence)
    @users = @search.result.paginate(page: params[:page])
    # NOTE: The following line specifies the sort order.
    # This is reflected in the default sort criteria shown.
    # The user is free to remove these default criteria.
    @search.sorts = 'last_name asc' if @search.sorts.empty?
    @search.build_condition if @search.conditions.empty?
    @search.build_sort if @search.sorts.empty?
    @users = @search.result
    @users = @users.order('last_name').page(params[:page])
  end
  # rubocop:enable Metrics/AbcSize
```
* In the private section of the file app/controllers/users_controller.rb, add the following lines:
```
  def may_index_user
    return redirect_to(root_path) unless admin_signed_in?
  end
  helper_method :may_index_user
```
* Enter the command "sh testc.sh".  Two of the tests fail because of a missing template.
* Enter the command "test1".  Two of the tests fail because of a missing template.

### User Index View
* Enter the command "touch app/views/users/index.html.erb" to create the user index page.
* Enter the command "sh testc.sh".  All of the controller tests should pass.
* Enter the command "test1".  Two of the integration tests fail due to missing content on the index page.
* Create the file app/views/users/index.html.erb with the following content:
```
<% provide(:title, 'User Index') %>

<br><br>

<%= search_form_for @search, url: search_users_path, method: :post do |f| %>
  <%= f.condition_fields do |c| %>
    <%= render "condition_fields", f: c %>
  <% end %>
  <p><%= link_to_add_fields "Add Conditions", f, :condition %></p>
  <div class="field">
    Sort:
    <%= f.sort_fields do |s| %>
      <%= s.sort_select %>
    <% end %>
  </div>
  <div class="actions"><%= f.submit "Search" %></div>
<% end %>

<h1>User Index</h1>
<%= will_paginate %>
<table class="users">
  <tr>
    <td><b>Last Name</b></td>
    <td><b>First Name</b></td>
    <td><b>Username</b></td>
    <td><b>Email</b></td>
  </tr>
  <%= render @users %>
</table>
<%= will_paginate %>
```
* Enter the command "test1".  Two tests fail because the search_users_path method is missing.

### User Index Search Elements
* Update the routing. Edit the file config/routes.rb and add the following lines to the end of the user section:
```
  resources :users do
    collection { post :search, to: 'users#index' }
  end
```
* Enter the command "test1".  Two tests fail because the users/_condition_fields is missing.
* Create the file app/views/users/_condition_fields.html.erb with the following content to provide the ability to display and remove fields in the search form:
```
<div class="field">
  <%= f.attribute_fields do |a| %>
    <%= a.attribute_select associations: [:category] %>
  <% end %>
  <%= f.predicate_select %>
  <%= f.value_fields do |v| %>
    <%= v.text_field :value %>
  <% end %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</div>
```
* Enter the command "test1".  Two tests fail because the method link_to_add_fields is missing.
* Add the following lines to the end of app/helpers/application_helper.rb (just before the final "end" command):
```
  def link_to_add_fields(name, f, type)
    new_object = f.object.send "build_#{type}"
    id = "new_#{type}"
    fields = f.send("#{type}_fields", new_object, child_index: id) do |builder|
      render(type.to_s + '_fields', f: builder)
    end
    link_to(name, '#', class: 'add_fields',
                       data: { id: id, fields: fields.delete("\n") })
  end
```
* Enter the command "test1".  Two tests fail because the users/_user view is missing.
* Create the file app/views/users/_user.html.erb with the following content to show information on each user in the index:
```
<% require 'email_munger' %>
<tr>
  <td><%= user.last_name %></td>
  <td><%= user.first_name %></td>
  <td><%= link_to user.username, user %></td>
  <td><%= link_to raw(EmailMunger.encode(user.email)), user %></td>
</tr>
```
* Enter the command "test1".  Two tests fail because the user index page is not accessible from the home page for admins.

### Header
* Add the following line to the beginning of the admin section in app/views/layouts/_header.html.erb:
```
          <li><%= link_to "User Index",   users_path %></li>
```
* Enter the command "test1".  All tests pass.
* Enter the command "sh git_check.sh". All of the tests should pass, but Rails Best Practices flags app/controllers/users_controller.rb with the message "move model logic into model" and config/routes.rb with the message "restrict auto -generated routes". Because I was unable to figure out how to make the suggested changes and believe that these are false alarms, the next step is to update config/rails_best_practices.yml.

### Rails Best Practices
* In the file config/rails_best_practices.yml, replace the line beginning with "MoveModelLogicIntoModelCheck" with the following line:
```
MoveModelLogicIntoModelCheck: { ignored_files: ['app/controllers/users_controller.rb'] }
```
* In the file config/rails_best_practices.yml, replace the line beginning with "RestrictAutoGeneratedRoutesCheck" with the following line:
```
RestrictAutoGeneratedRoutesCheck: { ignored_files: ['config/routes.rb'] }
```
* Enter the command "bundle exec rails_best_practices .".  There should be no remaining issues.
* Enter the command "sh git_check.sh".  All tests should pass, and there should be no flagged issues.
* Enter the following commands:
```
git add .
git commit -m "Added user methods"
```

### Bootstrap Styling
* If you have not already done so, restart the local server, and then refresh the browser.  (If you do not, you'll may get an error message when you attempt to view the user index.)
* Log in to your local app as an admin.
* Click on the "User Index" link.  The user index will appear, but the table would look far better with lines between each entry.
* Add the following content to the end of app/assets/stylesheets/custom.scss to format the table in the users index page:
```
/* Users and admins indices */
.users, .admins {
  td {
    border: 1px solid black;
    padding: 5px;
    text-align: center;
  }
  th {
    border: 1px solid black;
    padding: 5px;
    text-align: center;
  }
}
```
* The admins index page (which you will create later) will use the same table formatting.
* Refresh the user index page.  Now the table looks better.
* Enter the command "sh git_check.sh".  All tests should pass, and there should be no offenses.
* Enter the following commands:
```
git add .
git commit -m "Updated the user index styling"
```

### Adding and Removing Fields
* The search form appears at the top of the user index page, but the buttons for adding and removing fields do not work yet.
* Add the following content to the end of the app/assets/javascripts/users.coffee file to allow the buttons for adding and removing fields in the search form:
```
jQuery ->
  $('form').on 'click', '.remove_fields', (event) ->
    $(this).closest('.field').remove()
    event.preventDefault()

  $('form').on 'click', '.add_fields', (event) ->
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
    event.preventDefault()
```
* Now the buttons for adding and removing fields in the user index search form should work.  Try them out on the browser in your local app to verify this.
* Enter the command "sh git_check.sh".  All tests should pass, and there should be no offenses.
* Enter the following commands:
```
git add .
git commit -m "Allow the buttons to add and remove fields in the user index search form to work"
```

### Limiting Searchable Fields
* So far, the search form offers all parameters for filtering search results.  This is confusing and not desirable.  In addition, let's also change the number of entries listed per page from 30 (default value) to 50.
* Add the following lines to app/models/user.rb immediately after the line beginning with "class User":
```
  # Specify the number of entries per page given use of the will_paginate gem
  self.per_page = 50

  # Limit the parameters available for searching the user database
  RANSACKABLE_ATTRIBUTES = %w(email username last_name first_name).freeze
  def self.ransackable_attributes(_auth_object = nil)
    RANSACKABLE_ATTRIBUTES + _ransackers.keys
  end
```
* Refresh your web browser.  Now the only searchable fields should be the email address, username, last name, and first name.
* Enter the command "sh git_check.sh".  All tests should pass, and there should be no offenses.
* Enter the following commands:
```
git add .
git commit -m "Limit the ransackable attributes for users and display up to 50 users per page"
```

### Wrapping Up
* Enter the command "git push origin 10-02-user_index_controller".
* Go to the GitHub repository and click on the "Compare and pull request" button for this branch.
* The dynamic render path in the user index page will be flagged by Hakiri. Mark this issue as a false positive.
* Accept this pull request to merge it with the master branch, but do NOT delete this branch.
* Enter the following commands:
```
git checkout master
git pull
sh heroku.sh
```


text:
crackfortran has support for operator and assignment overloading
----------------------------------------------------------------
``crackfortran`` parser now understands operator and assignment
definitions in a module. They are added in the ``body`` list of the
module which contains a new key ``implementedby`` listing the names
of the subroutines or functions implementing the operator or
assignment.


text:
// Copyright (c) 2018 Nikolay Zahariev <zahasoft.com>. Licensed under the MIT License.

namespace Zahasoft.Guard.Base
{
    using System.Threading.Tasks;

    /// <summary>
    /// Write-only action's interface.
    /// </summary>
    public interface IAction
    {
    }

    /// <summary>
    /// Write-only action's interface.
    /// </summary>
    /// <typeparam name="TRequest">Type of request model</typeparam>
    /// <typeparam name="TResponse">Type of response model</typeparam>
    public interface IAction<TRequest, TResponse> : IAction
    {
        /// <summary>
        /// Apply action.
        /// </summary>
        /// <param name="request">Request model</param>
        /// <returns>Task from response model</returns>
        Task<TResponse> ApplyAsync(TRequest request);
    }
}


text:
Build your Slack apps by reacting to messages, emojis, files, and many more types of interesting
events in the [Events API](https://api.slack.com/events-api). This package will help you start
with sensible and secure defaults.

The adapter gives you a simple and highly configurable Node-style [EventEmitter](https://nodejs.org/dist/latest/docs/api/events.html#events_class_eventemitter) to attach functions
to handle events.

---

### Support

Need help? Join the [Bot Developer Hangout](https://community.botkit.ai) team and talk to us in
[#slack-api](https://dev4slack.slack.com/messages/slack-api/).

You can also [create an Issue](https://github.com/slackapi/node-slack-sdk/issues/new)
right here on GitHub.


text:
package com.betfair.cougar.caching;

/**
 *
 */
public interface CacheFrameworkIntegration {
    /**
     * Returns true if the cache was found.
     */
    boolean refreshNamedCache(String name);
    void refreshAllCaches();
    String getName();
}


text:
<?php

// File generated from our OpenAPI spec

namespace Stripe;

/**
 * @property string $id Unique identifier for the object.
 * @property string $object String representing the object's type. Objects of the same type share the same value.
 * @property null|string $invoice The invoice in which this usage period has been billed for.
 * @property bool $livemode Has the value true if the object exists in live mode or the value false if the object exists in test mode.
 * @property \Stripe\StripeObject $period
 * @property string $subscription_item The ID of the subscription item this summary is describing.
 * @property int $total_usage The total usage within this usage period.
 */
class UsageRecordSummary extends ApiResource
{
    const OBJECT_NAME = 'usage_record_summary';
}


text:
using Evol.Domain.Dto;
using System;
using System.ComponentModel.DataAnnotations;

namespace Sample.Domain.Dto
{
    public class ItemDeleteDto : IInputDto
    {
        [Required]
        public Guid Id { get; set; }

    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Oncidium obryzatum Rchb.f. & Warsz.

### Remarks
null


text:
package org.valuereporter.agent.http;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.valuereporter.agent.ObservedMethod;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by baardl on 07.05.14.
 */
public class HttpSender implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(HttpSender.class);

    private final String prefix;
    private final List<ObservedMethod> observedMethods;
    private final String reporterHost;
    private final String reporterPort;
    private ObjectMapper mapper = new ObjectMapper();
    private static final int STATUS_BAD_REQUEST = 400; //Response.Status.BAD_REQUEST.getStatusCode();
    private static final int STATUS_OK = 200; //Response.Status.OK.getStatusCode();
    private static final int STATUS_FORBIDDEN = 403;
    private Map<String, WebTarget> observedMethodTargets;
    private final String observedMethodsJson;

    public HttpSender(final String reporterHost, final String reporterPort, final String prefix, final List<ObservedMethod> observedMethods) {
        observedMethodsJson = buildJson(observedMethods);
        this.reporterHost = reporterHost;
        this.reporterPort = reporterPort;
        this.prefix = prefix;
        this.observedMethods = observedMethods;
    }

    private String buildJson(List<ObservedMethod> observedMethods)  {
        String json = null;
        try {
            json = mapper.writeValueAsString(observedMethods);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    //public void forwardObservations(String prefix, List<ObservedMethod> observedMethods) {
    public void run() {
        Client client = ClientBuilder.newClient();
        String observationUrl = "http://"+reporterHost + ":" + reporterPort +"/reporter/observe";
        log.info("Connection to ValueReporter on {}" , observationUrl);
        final WebTarget observationTarget = client.target(observationUrl);
        observedMethodTargets = new HashMap<>();
        //WebTarget webResource = findWebResourceByPrefix(prefix);
        WebTarget webResource = observationTarget.path("observedmethods").path(prefix);
        //String observedMethodsJson = mapper.writeValueAsString(observedMethods);
        log.trace("Forwarding observedMethods as Json \n{}", observedMethodsJson);

        Response response = webResource.request(MediaType.APPLICATION_JSON).post(Entity.entity(observedMethodsJson, MediaType.APPLICATION_JSON));
        int statusCode = response.getStatus();
        switch (statusCode) {
            case STATUS_OK:
                log.trace("Updated via http ok. Response is {}", response.readEntity(String.class));
                break;
            case STATUS_FORBIDDEN:
                log.warn("Can not access ValueReporter. The application will function as normally, though Observation statistics will not be stored. URL {}, HttpStatus {}, Response {}, ", observationUrl,response.getStatus(), response.readEntity(String.class));
                break;
            default:
                log.error("Error while accessing ValueReporter. The application will function as normally, though Observation statistics will not be stored. URL {}, HttpStatus {},Response from ValueReporter {}",observationUrl, response.getStatus(), response.readEntity(String.class));
        }

    }

    /*
    private WebTarget findWebResourceByPrefix(String prefix) {
        WebTarget webTarget = observedMethodTargets.get(prefix);
        if (webTarget == null ) {
            webTarget = observationTarget.path("observedmethods").path(prefix);
            observedMethodTargets.put(prefix, webTarget);
        }
        return webTarget;
    }
    */

}


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Lorem Ipsum page</title>
    <link href="StyleLorem.css" rel="stylesheet" />
</head>
<body>
    <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus tempus bibendum neque, sit amet posuere libero ultricies tristique. Duis ornare turpis vitae lacus feugiat, non varius turpis placerat. Donec condimentum efficitur leo, eu aliquam ex hendrerit ut. Pellentesque imperdiet, risus ut facilisis fermentum, augue elit vehicula orci, in sagittis lectus metus non neque. Donec mattis viverra eros sed interdum. Quisque porttitor pellentesque turpis, in mattis massa rhoncus vel. Nulla facilisi. Nulla a tincidunt velit. Mauris a erat ac ex condimentum pellentesque sed non massa. Vestibulum in lectus sagittis, iaculis dui eu, tristique tellus. Nam tempor mauris in tincidunt faucibus. Pellentesque malesuada orci eros, nec bibendum ante euismod vehicula. Ut id est tincidunt, tempus sapien ut, mollis nisl. Vivamus feugiat consectetur iaculis. Maecenas tristique commodo tellus, quis ultricies velit faucibus id.
    </p>
</body>
</html>


text:
<?php
/**
 * Config-file for navigation bar.
 *
 */
return [

    // Use for styling the menu
    'class' => 'navbar',

    // Here comes the menu strcture
    'items' => [

        // This is a menu item
        'home'  => [
            'text'  => 'Om mig',
            'url'   => $this->di->get('url')->create('about'),
            'title' => 'Sidan om mig'
        ],

        // This is a menu item
        'report' => [
            'text'  =>'Redovisning',
            'url'   => $this->di->get('url')->create('redovisning'),
            'title' => 'Redovisning',
        ],

        // This is a menu item
        'regioner' => [
            'text'  =>'Regioner',
            'url'   => $this->di->get('url')->create('regioner'),
            'title' => 'Regioner',
            // Here we add the submenu, with some menu items, as part of a existing menu item
            'submenu' => [
                'items' => [

                    // This is a menu item of the submenu
                    'typography'  => [
                        'text'  => 'Typography',
                        'url'   => $this->di->get('url')->create('regioner/typography'),
                        'title' => 'Typography'
                    ],
                    // This is a menu item of the submenu
                    'font-awesome'  => [
                        'text'  => 'Font Awesome',
                        'url'   => $this->di->get('url')->create('regioner/fontawesome'),
                        'title' => 'Font Awesome'
                    ],

                ],
            ],
        ],

        // This is a menu item
        'source' => [
            'text'  =>'Källkod',
            'url'   => $this->di->get('url')->create('source'),
            'title' => 'Sourcecode browser'
        ],

    ],

    /**
     * Callback tracing the current selected menu item base on scriptname
     *
     */
    'callback' => function ($url) {
        if ($url == $this->di->get('request')->getCurrentUrl(false)) {
            return true;
        }
    },

    /**
     * Callback to check if current page is a decendant of the menuitem, this check applies for those
     * menuitems that has the setting 'mark-if-parent' set to true.
     *
     */
    'is_parent' => function ($parent) {
        $route = $this->di->get('request')->getRoute();
        return !substr_compare($parent, $route, 0, strlen($parent));
    },

   /**
     * Callback to create the url, if needed, else comment out.
     *
     */
   /*
    'create_url' => function ($url) {
        return $this->di->get('url')->create($url);
    },
    */
];


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_description">"Изменение значений framework-res.apk. Нажмите здесь для конфигурирования настроек."</string>
    <string name="label_icontext">Показать описание рядом с иконкой на панели действий</string>
    <string name="sum_icontext">Показать описание на иконке в панели действий</string>
    <string name="label_ledoff">Выключать светодиод, когда зарядка закончена</string>
    <string name="sum_ledoff">Выключить свеодиод, когда зарядка полностью закончена.</string>
    <string name="label_unplugon">"Не включать экран, когда док-станция отключена."</string>
    <string name="sum_unplugon">"Не включать экран автоматически, когда Вы начинаете/заканчиваете зарядку."</string>
    <string name="label_unplugdock">Выключить автоповорот в док-станции</string>
    <string name="sum_unplugdock">Выключить принудительно автоповорот в настольном/автомобильном режиме док-станции.</string>
    <string name="label_noisy">Отключить предупреждение о большой громкости</string>
    <string name="sum_noisy">Выключить передупреждение, когда вы повышаете громкость в наушниках.\nБудьте осторожны и не повышайте громкость слишком сильно.</string>
    <string name="label_volsound">Выключить звук при смене громкости</string>
    <string name="sum_volsound">Выключить звук, когда Вы меняете громкость.</string>
    <string name="label_skipnet">"Пропустить восстановление сетевого режима"</string>
    <string name="sum_skipnet">"Не восстанавливать сетевой режим, когда вы сменили сеть."</string>
    <string name="label_prefapn">Не предпочитать моб. интернет</string>
    <string name="sum_prefapn">Не предпочитать моб. интернет</string>
    <string name="label_voice">Исправить проблему ячеек памяти</string>
    <string name="sum_voice">Исправить проблему ячеек памяти даты (только SIM)</string>
    <string name="label_dim">Изменить минимальную яркость до 5</string>
    <string name="sum_dim">Вы можете изменить яркость до 10 в настройках экрана.</string>
    <string name="label_ime">"Выключить уведомление \"Выберите способ ввода\""</string>
    <string name="sum_ime">"Выключить уведомление \"Выберите способ ввода\", когда Вы набираете текст."</string>
    <string name="label_lockmenu">Показывать кнопку \"Меню\" на экране блокировки</string>
    <string name="sum_lockmenu">Не прятать кнопку \"Меню\" на экране блокировки</string>
    <string name="label_lockrot">Разрешить поворот экрана блокировки</string>
    <string name="sum_lockrot">Вы можете поворачивать экран блокировки.</string>
    <string name="label_notifbg">Сделать фон иконки уведомления прозрачным</string>
    <string name="sum_notifbg">Изменить цвет фона иконки уведомления прозрачным.</string>
    <string name="label_hideime">Выключить звук камеры</string>
    <string name="sum_hideime">Показать настройку звука спуска в камере.</string>
    <string name="label_autob">Понизить авторегулируемую яркость</string>
    <string name="sum_autob">Снизить автонастраимаевую яркость наполовину.</string>
    <string name="label_rebootaf">Замечание</string>
    <string name="nosum">Вы должны перезагрузиться, чтобы изменения вступили в силу.</string>
</resources>


text:
package gnu.java.net.protocol.ftp;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * An output stream that notifies a DTP on end of stream.
 *
 * @author Chris Burdess (dog@gnu.org)
 */
abstract class DTPOutputStream extends FilterOutputStream
{

  DTP dtp;
  boolean transferComplete;

  /**
   * Constructor.
   * @param dtp the controlling data transfer process
   * @param out the socket output stream
   */
  DTPOutputStream (DTP dtp, OutputStream out)
    {
      super (out);
      this.dtp = dtp;
      transferComplete = false;
    }

  /**
   * Tells this stream whether transfer has completed or not.
   * @param flag true if the process has completed, false otherwise
   */
  void setTransferComplete (boolean flag)
    {
      transferComplete = flag;
    }

  /**
   * Notifies the controlling DTP that this stream has been terminated.
   */
  public void close () throws IOException
    {
      dtp.transferComplete ();
    }

}