text:
package com.avanza.astrix.serviceunit;

public interface ServiceExporter {

	void addServiceProvider(Object bean);

	void exportService(ExportedServiceBeanDefinition<?> definition);

	void startPublishServices();

}


text:
$LOAD_PATH << File.dirname(__FILE__) unless $LOAD_PATH.include?(File.dirname(__FILE__))

require 'matchers/suit_matcher_base'
require 'matchers/scope_creator_matchers'
require 'matchers/scope_is_public_matchers'
require 'matchers/scope_ordinal_matchers'
require 'matchers/scope_sorting_matchers'
require 'matchers/scope_time_matchers'
require 'matchers/scope_active_matchers'
require 'matchers/nested_attribute_matcher'
require 'matchers/sanitize_matcher'

module Suit # :nodoc:
  module Models # :nodoc:
    # = Matchers for common active record scopes:
    #
    #   scope :by_title, order("title ASC")
    #   scope :by_name, order("name ASC")
    #   scope :by_newest, order("created_at DESC")
    #   scope :by_oldest, order("created_at ASC")
    #   scope :by_latest, order("updated_at DESC")
    #   scope :newer_than, lambda { |*args| where("created_at > ?", args.first || DateTime.now) }
    #   scope :older_than, lambda { |*args| where("created_at < ?", args.first || 1.day.ago.to_s(:db)) }
    #   scope :is_public, where(["is_public = ?", true])
    #   scope :created_by, lambda { |creator| where("creator_id = ? AND creator_type = ?", creator.id, creator.class.to_s) } }
    #   scope :sorted, order("sort ASC")
    #   scope :sorted_id, order("id ASC")
    #
    # These matchers will test common scopes used in active record models:
    #
    #   describe User do
    #     it { should scope_by_title }
    #     it { should scope_by_name }
    #     it { should scope_by_latest }
    #     it { should scope_by_newest }
    #     it { should scope_by_oldest }

    #     it { should scope_newer_than }
    #     it { should scope_older_than }

    #     it { should scope_is_public }

    #     it { should scope_created_by }

    #     it { should sanitize :title }
    #     it { should scope_sorted }
    #     it { should scope_sorted_id }
    #   end

    module Matchers
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_sign_in"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.adhass.creators.squadgames.controllers.SignInActivity"
    android:orientation="vertical"
    android:background="#B8FFFF">

    <TextView
        android:text="SquadGames"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textAlignment="gravity"
        android:fontFamily="casual"
        android:textStyle="bold"
        android:textSize="30sp"
        android:textColor="@android:color/black"
        android:id="@+id/textView"
        android:layout_weight="5"
        />

    <TextView
        android:text="Find your board game adventure."
        android:fontFamily="casual"
        android:textStyle="italic"
        android:textSize="40sp"
        android:layout_marginStart="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginRight="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:textAlignment="gravity"
        android:id="@+id/textView2"
        android:layout_weight="3"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_weight="4">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:background="#C2E6F0"
            android:text="Register"
            android:id="@+id/first_register_button"
            android:textColor="@android:color/black" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            style="@style/Widget.AppCompat.Button.Borderless"
            android:background="#C2E6F0"
            android:text="Login"
            android:id="@+id/first_login_button"
            android:textColor="@android:color/black" />
    </LinearLayout>

</LinearLayout>


text:
<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>

<!-- The Basque langpack -->

<izpack:langpack version="5.0"
                 xmlns:izpack="http://izpack.org/schema/langpack"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://izpack.org/schema/langpack http://izpack.org/schema/5.0/izpack-langpack-5.0.xsd">

    <!-- Heading messages START -->
    <str id="CheckedHelloPanel.headline" txt="Ongi Etorri"/>
    <str id="CompilePanel.headline" txt="Java Iturriak Konpilatu"/>
    <str id="ConditionalUserInputPanel.headline" txt="Erabiltzailearen datuak"/>
    <str id="FinishPanel.headline" txt="Instalazioa amaitua"/>
    <str id="HelloPanel.headline" txt="Ongi Etorri"/>
    <str id="HTMLInfoPanel.headline" txt="Informazioa"/>
    <str id="HTMLLicencePanel.headline" txt="Lizentzia Akordioa"/>
    <str id="PDFLicencePanel.headline" txt="Lizentzia Akordioa"/>
    <str id="ImgPacksPanel.headline" txt="Paketeak aukeratu"/>
    <str id="InfoPanel.headline" txt="Informazioa"/>
    <str id="InstallPanel.headline" txt="Instalazioa"/>
    <str id="JDKPathPanel.headline" txt="JDKren bidea"/>
    <str id="LicencePanel.headline" txt="Lizentzia Akordioa"/>
    <str id="PacksPanel.headline" txt="Paketeak aukeratu"/>
    <str id="ProcessPanel.headline" txt="Kanpo-prozesuak burutu"/>
    <str id="ShortcutPanel.headline" txt="Laburbideak ezarri"/>
    <str id="SimpleFinishPanel.headline" txt="Instalazioa bukatua"/>
    <str id="SummaryPanel.headline" txt="Konfigurazio Datuen Laburpena"/>
    <str id="TargetPanel.headline" txt="Jopunturako bidea"/>
    <str id="TreePacksPanel.headline" txt="Paketeak aukeratu"/>
    <str id="UserInputPanel.headline" txt="Erabiltzailearen datuak"/>
    <str id="UserPathPanel.headline" txt="Aukeratu Bidea"/>
    <str id="InstallationTypePanel.headline" txt="Instalazio Mota"/>

    <!-- ConsolePrompt strings -->
    <str id="ConsolePrompt.okCancel" txt="Enter O for OK, C to Cancel: "/>
    <str id="ConsolePrompt.yesNo" txt="Enter Y for Yes, N for No: "/>
    <str id="ConsolePrompt.yesNoCancel" txt="Enter Y for Yes, N for No, or C to Cancel: "/>
    <str id="ConsolePrompt.ok" txt="O"/>
    <str id="ConsolePrompt.cancel" txt="C"/>
    <str id="ConsolePrompt.yes" txt="Y"/>
    <str id="ConsolePrompt.no" txt="N"/>

    <!-- ConsoleInstaller strings -->
    <str id="ConsoleInstaller.continueQuitRedisplay" txt="Press 1 to continue, 2 to quit, 3 to redisplay"/>
    <str id="ConsoleInstaller.acceptRejectRedisplay" txt="Press 1 to accept, 2 to reject, 3 to redisplay"/>
    <str id="ConsoleInstaller.redisplayQuit" txt="Press 1 to redisplay, 2 to quit"/>
    <str id="ConsoleInstaller.permissionError" txt="Administrative privileges required. Please re-run the installer with administrative privileges."/>
    <str id="ConsoleInstaller.inputSelection" txt="Input selection: "/>
    <str id="ConsoleInstaller.pagingMore" txt="More"/>
    <str id="ConsoleInstaller.aborted.PressedCTRL-C" txt="CTRL-C pressed"/>
    <str id="ConsoleInstaller.aborted.LicenseRejected" txt="License rejected"/>
    <str id="ConsoleInstaller.aborted.PressedQuit" txt="Quit pressed"/>
    <str id="ConsoleInstaller.shutdown.pendingFileOperations" txt="There are file operations pending after reboot"/>
    <str id="ConsoleInstaller.shutdown.rebootingNow" txt="Rebooting now automatically"/>
    <str id="ConsoleInstaller.shutdown.done" txt="Console installation done"/>
    <str id="ConsoleInstaller.shutdown.aborted" txt="Console installation ABORTED by the user!"/>
    <str id="ConsoleInstaller.shutdown.failed" txt="Console installation FAILED!"/>

    <!-- General installer strings -->
    <str id="installer.title" txt="Alliaria - Instaladorea: "/>
    <str id="installer.next" txt="Aurrera"/>
    <str id="installer.prev" txt="Atzera"/>
    <str id="installer.quit" txt="Amaitu"/>
    <str id="installer.madewith" txt="(Alliariak eginda - http://www.alliaria.com/)"/>
    <str id="installer.quit.title" txt="Ziur al zaude amaitu nahi duzula?"/>
    <str id="installer.quit.message" txt="Instalazioa amaituko da!"/>
    <str id="installer.warning" txt="Adi!"/>
    <str id="installer.yes" txt="Bai"/>
    <str id="installer.no" txt="Ez"/>
    <str id="installer.accept" txt="Onartu"/>
    <str id="installer.cancel" txt="Ezeztatu"/>
    <str id="installer.error" txt="Errorea"/>
    <str id="installer.help" txt="Laguntza"/>
    <str id="installer.help.close" txt="Itxi"/>
    <str id="installer.step" txt="Pausua"/>
    <str id="installer.of" txt=" - "/>
    <str id="installer.Message" txt="Mezua"/>
    <str id="installer.errorMessage" txt="An error occured"/>
    <str id="installer.close" txt="Close"/>
    <str id="installer.showDetails" txt="Show Details"/>
    <str id="installer.hideDetails" txt="Hide Details"/>
    <str id="installer.copy" txt="Copy"/>
    <str id="installer.sendReport" txt="Send Report"/>
    <str id="installer.continueQuestion" txt="Continue anyway?"/>
    <str id="installer.cancelled" txt="Installation cancelled"/>
    <str id="installer.started" txt="Installation started"/>
    <str id="installer.platform" txt="Platform: {0}"/>
    <str id="installer.version" txt="Framework: {0}"/>
    <str id="installer.finished" txt="Installation finished"/>

    <!-- Uninstaller specific strings -->
    <str id="uninstaller.warning" txt="Instalatutako aplikazioak ezabatuko dira!"/>
    <!--<str id="uninstaller.warning" txt=""/>-->
    <str id="uninstaller.destroytarget" txt=" Ezabaketa Behartu "/>
    <str id="uninstaller.uninstall" txt="Desinstalatzailea"/>

    <!-- The strings for the 'official' IzPack plugins -->
    <!-- HelloPanel strings -->
    <str id="HelloPanel.welcome1" txt="Instalatuko da "/>
    <str id="HelloPanel.welcome2" txt="!"/>
    <str id="HelloPanel.authors" txt="Programa honen egileak: "/>
    <str id="HelloPanel.url" txt="Web horria: "/>

    <!-- LicensePanel strings -->
    <str id="LicencePanel.info" txt="Mesedez, irakurri hurrengo lizentzia akordioa:"/>
    <str id="LicencePanel.agree" txt="Lizentzia akordioa onartzen dut."/>
    <str id="LicencePanel.notagree" txt="Lizentzia akordioa ez dut onartzen."/>
    <str id="LicencePanel.yes" txt="Bai"/>
    <str id="LicencePanel.no" txt="Ez"/>

    <!-- PrinterSelect Panel -->
    <str id="PrinterSelectPanel.select_printer" txt="Aukeratu aurreneko instalazio eta frogetarako imprimagailua."/>

    <!-- InfoPanel strings -->
    <str id="InfoPanel.info" txt="Mesedez, hurrengoa irakurri: "/>

    <!-- PathInputPanel strings -->
    <str id="PathInputPanel.required" txt="Aukeratutako direktorioa existitu beharko luke."/>
    <str id="PathInputPanel.required.forModificationInstallation"
         txt="Aukeratutako direktorioa existitu beharko luke."/>
    <str id="PathInputPanel.notValid" txt="Aukeratutako direktorioak ez dauka behar den produktua."/>

    <!-- TargetPanel strings -->
    <str id="TargetPanel.info" txt="Aukeratu instalatzeko bidea: "/>
    <str id="TargetPanel.browse" txt="Gainbegiratu..."/>
    <str id="TargetPanel.warn"
         txt="Direktorioa aurrez existitzen da! Ziur al zaude hemen instalatu nahi duzula? Fitxategiak gainidatzi ditzakezu!"/>
    <str id="TargetPanel.empty_target" txt="Ez duzu jopuntua aukeratu! Ondo al dago?"/>
    <str id="TargetPanel.createdir" txt="Jopuntu direktorioa sortuko da: "/>
    <str id="TargetPanel.nodir" txt="Fitxategi hau ez da direktorioa! Aukeratu direktorio bat!"/>
    <str id="TargetPanel.notwritable" txt="Ezinezkoa da direktorio honetan idatzi! Aukeratu beste direktorio bat!"/>

    <!-- JDKPathPanel strings -->

    <!--La instalaci�n instalada necesita un JDK cuya versi�n est� comprendida entre la ${JDKPathPanel.minVersion} y la ${JDKPathPanel.maxVersion}. Un entorno de ejecuci�n de Java (JRE) no es suficiente."/>-->

    <str id="JDKPathPanel.extendedIntro"
         txt="Instalaturiko aplikazioak JDK-ren bertsioa ${JDKPathPanel.minVersion} eta ${JDKPathPanel.maxVersion} tartean egon behar du, Java runtime environment (JRE)-a soilik ez da nahiko izango."/>
    <str id="JDKPathPanel.intro"
         txt="Instalaturiko aplikazioak JDK behar du. Java runtime environment (JRE) bakarrik edukitzea ez da nahiko izango."/>
    <str id="JDKPathPanel.info" txt="Aukeratu JDKren bidea:"/>
    <str id="JDKPathPanel.badVersion1" txt="Aukeratutako JDK bertsioa okerra da (erabilgarria: "/>
    <str id="JDKPathPanel.badVersion2" txt=" beharrezkoa: "/>
    <str id="JDKPathPanel.badVersion3" txt=") JDK hau erabiliko dugu hala ere?"/>
    <str id="JDKPathPanel.nonValidPathInReg"
         txt="Windows-en erregistroak, JDK honentzako jopunturako bide baliogabea du. Erabiliko dugu JDK hau, hala ere?"/>

    <!-- PacksPanel strings -->
    <str id="PacksPanel.info" txt="Aukeratu instalatzeko paketeak:"/>
    <str id="PacksPanel.tip" txt="Nota: Pakete grisak beharrezkoak dira."/>
    <str id="PacksPanel.space" txt="Diskan beharrezkoa den lekua: "/>
    <str id="PacksPanel.freespace" txt="Diskan dagoen leku erabilgarria: "/>
    <str id="PacksPanel.description" txt="Deskripzioa"/>
    <str id="PacksPanel.dependencyList" txt="The selected package has the following dependencies and/or excludes"/>
    <!--<str id="PacksPanel.dependencyList" txt="Aukeratutako paketeak hurrengoko mendekotasun (dependentzia) eta/edo bazterketak ditu"/>-->
    <str id="PacksPanel.dependencies" txt="Dependentziak: "/>
    <str id="PacksPanel.excludes" txt="Bazterketak: "/>
    <str id="PacksPanel.notEnoughSpace" txt="Instalaziorako behar den lekua, diskan dagoena baino handiagoa da."/>
    <str id="PacksPanel.notAscertainable" txt="Determinatugabea"/>

    <!-- InstallPanel strings -->
    <str id="InstallPanel.info" txt="Sakatu 'Instalatu!' Instalazioa hasteko"/>
    <str id="InstallPanel.install" txt="Instalatu!"/>
    <str id="InstallPanel.tip" txt="Paketearen instalazio bilakaera:"/>
    <str id="InstallPanel.begin" txt=" [Hasi gabe]"/>
    <str id="InstallPanel.finished" txt="[Amaitua]"/>
    <str id="InstallPanel.progress" txt="Instalazio osoaren bilakaera:"/>
    <str id="InstallPanel.overwrite.title" txt="Fitxeroa aurrez existitzen da"/>
    <str id="InstallPanel.overwrite.question" txt="Hurrengo fitxeroa aurrez existitzen da. Berridatzi daiteke?"/>

    <!-- InstallationGroupPanel strings -->
    <str id="InstallationGroupPanel.colNameSelected" txt="Aukeratua"/>
    <str id="InstallationGroupPanel.colNameInstallType" txt="Instalazio Mota"/>
    <str id="InstallationGroupPanel.colNameSize" txt="Tamaina"/>

    <!-- InstallationTypePanel strings -->
    <str id="InstallationTypePanel.info" txt="Mesedez, aukeratu instalazio mota:"/>
    <str id="InstallationTypePanel.normal" txt="Instalazio berria"/>
    <str id="InstallationTypePanel.modify" txt="Instalazioa aldatu"/>

    <!-- FinishPanel strings -->
    <str id="FinishPanel.success" txt="Instalazio arrakastatsua."/>
    <str id="FinishPanel.done" txt="Eginda"/>
    <str id="FinishPanel.fail" txt="Instalazio ezegokia!"/>
    <str id="FinishPanel.uninst.info" txt="Hurrengoko bidean sortu da desinstaladorea: "/>
    <str id="FinishPanel.auto" txt="Gidoi automatikoa sortu instalazioa errepikatzeko"/>
    <str id="FinishPanel.auto.tip" txt="Erabili gidoi hau beste ordenadoreetan instalazioa errepikatzeko."/>
    <str id="FinishPanel.auto.dialog.filterdesc" txt="XML Fitxeroak"/>

    <!-- ImgPacksPanel strings -->
    <str id="ImgPacksPanel.dependencyList" txt="Dependentziak eta/edo bazterketak"/>
    <str id="ImgPacksPanel.packs" txt="Hurrengoak dira pakete erabilgarriak:"/>
    <str id="ImgPacksPanel.snap" txt="Pantailaren uneko argazkia:"/>
    <str id="ImgPacksPanel.checkbox" txt=" Pakete hau instalatu"/>

    <!-- ShortcutPanel strings -->
    <str id="ShortcutPanel.regular.list" txt="Programa Taldea Aukeratu Laburbideentzat:"/>
    <str id="ShortcutPanel.regular.default" txt="Lehenetsia"/>
    <str id="ShortcutPanel.regular.desktop" txt="Idazmahaian Laburbide gehiago sortu"/>
    <str id="ShortcutPanel.regular.create" txt="Menuetan Laburbideak sortu "/>
    <str id="ShortcutPanel.regular.userIntro" txt="Laburbidea sortu"/>
    <str id="ShortcutPanel.regular.currentUser" txt="Bertoko erabiltzailearentzat"/>
    <str id="ShortcutPanel.regular.allUsers" txt="Erabiltzaile guztientzat"/>
    <str id="ShortcutPanel.alternate.apology"
         txt="Barkatu baina Sistema Eragile honetan, ezin dira laburbiderik sortu ."/>
    <str id="ShortcutPanel.alternate.targetsLabel"
         txt="Hurrengokoa, software honen fabrikatzaileak sortutako helburu zerrenda bat da, sarbidea edukitzeko."/>

    <str id="ShortcutPanel.alternate.textFileExplanation"
         txt="Aplikazioaren helburuen informazio zehatzagoa gorde dezakezu texto fitxategi batean, datozen hurrengo errefenetziatan."/>

    <str id="ShortcutPanel.alternate.saveButton" txt="Textu Fitxeroa gorde"/>
    <str id="ShortcutPanel.textFile.header"
         txt="Laburbide informazioa\n====================\n\nAukeratutako laburbideei buruzko informazio garrantzitsuena hemen daukazue.\n Nahiko izan beharko litzateke laburbideak eskuz sortzeko.\n"/>
    <str id="ShortcutPanel.textFile.name" txt="Laburbidea          : "/>
    <str id="ShortcutPanel.textFile.location" txt="Aukeratutako kokapena : "/>
    <str id="ShortcutPanel.textFile.description" txt="Deskripzioa       : "/>
    <str id="ShortcutPanel.textFile.target" txt="Laburbidearen jopuntua   : "/>
    <str id="ShortcutPanel.textFile.command" txt="Komando lerroa      : "/>
    <str id="ShortcutPanel.textFile.iconName" txt="Ikonoaren Fitxeroa         : "/>
    <str id="ShortcutPanel.textFile.iconIndex" txt="Ikonoaren Indizea        : "/>
    <str id="ShortcutPanel.textFile.work" txt="Lanerako Direktorioa: "/>
    <str id="ShortcutPanel.location.desktop" txt="Idazmahaia"/>
    <str id="ShortcutPanel.location.applications" txt="Aplikazio Menua"/>
    <str id="ShortcutPanel.location.startMenu" txt="Hasiera Menua"/>
    <str id="ShortcutPanel.location.startup" txt="Hasiera Taldea"/>
    <str id="ShortcutPanel.regular.StartMenu:Start-Menu" txt="Hasiera-Menua"/>
    <str id="ShortcutPanel.regular.StartMenu:K-Menu" txt="XDG-Menua"/>

    <!-- UserInputPanel strings -->
    <str id="UserInputPanel.error.caption" txt="Errorea"/>
    <str id="UserInputPanel.dir.nodirectory.message" txt="Direktorio egokia aukeratu behar duzu."/>
    <str id="UserInputPanel.dir.nodirectory.caption" txt="Ez duzu direktoriorik aukeratu"/>
    <str id="UserInputPanel.dir.notdirectory.message"
         txt="Aukeratutako direktorioak ez du baliorik edota ez da existitzen."/>
    <str id="UserInputPanel.dir.notdirectory.caption" txt="Direktorio ezegokia"/>
    <str id="UserInputPanel.file.nofile.message" txt="Fitxero egokia aukeratu behar duzu."/>
    <str id="UserInputPanel.file.nofile.caption" txt="Ez duzu fitxerorik aukeratu"/>
    <str id="UserInputPanel.file.notfile.message" txt="Aukeratutako fitxeroak ez du balio edo ez da existitzen."/>
    <str id="UserInputPanel.file.notfile.caption" txt="Fitxero ezegokia"/>
    <!-- more descriptive error message would be cool, like specifying what file we looked for -->
    <str id="UserInputPanel.search.autodetect" txt="Autodetekzioa"/>
    <str id="UserInputPanel.search.autodetect.failed.message" txt="Auto-detekzioak huts egin du."/>
    <str id="UserInputPanel.search.autodetect.failed.caption" txt="Auto-detekzioak huts egin du"/>
    <str id="UserInputPanel.search.autodetect.tooltip" txt="Fitxero edo direktorioa bilatu aurreko bideetan."/>
    <str id="UserInputPanel.search.location" txt="Sartu {0}ren kokapena."/>
    <str id="UserInputPanel.search.location.checkedfile" txt="{0} existitzen den aztertuko da."/>
    <str id="UserInputPanel.search.browse" txt="Gainbegiratu..."/>
    <str id="UserInputPanel.search.wrongselection.message"
         txt="Aukeratutako fitxero edo direktorioa ez da existitzen edo ez da egokia."/>
    <str id="UserInputPanel.search.wrongselection.caption" txt="Aukeraketa ezegokia"/>

    <!-- UserPathPanel strings -->
    <str id="UserPathPanel.required" txt="Aukeratutako direktorioa existitu beharko luke."/>
    <str id="UserPathPanel.info" txt="Bidea aukeratu: "/>
    <str id="UserPathPanel.browse" txt="Gainbegiratu"/>
    <str id="UserPathPanel.exists_warn"
         txt="Direktorioa aurrez existitzen da! Ziur zaude hemen instalatu nahi duzula aurrez existitzen diren fitxeroak gainidatziz?"/>
    <str id="UserPathPanel.empty_target" txt="Ez duzu jopuntu kokapenarik sartu! Ondo al dago hau?"/>
    <str id="UserPathPanel.createdir" txt="Jopuntu direktorioa sortuko da: "/>
    <str id="UserPathPanel.nodir" txt="Fitxero hau ez da direktorio bat! Mesedez, aukeratu direktorio bat!"/>
    <str id="UserPathPanel.notwritable"
         txt="Ez dut fitxategi hauetan idazteko baimenik! Beste direktorio bat aukeratu, mesedez!"/>

    <!-- CompilePanel strings -->
    <str id="CompilePanel.heading" txt="Konpilazioa"/>
    <str id="CompilePanel.tip" txt="Lanen konpilazio progresua:"/>
    <str id="CompilePanel.browse" txt="Gainbegiratu..."/>
    <str id="CompilePanel.browse.approve" txt="Erabili hurrengo konpiladorea"/>
    <str id="CompilePanel.start" txt="Hasi"/>
    <str id="CompilePanel.progress.initial" txt="[Sakatu Hasi botoia]"/>
    <str id="CompilePanel.progress.finished" txt="[Amaitua]"/>
    <str id="CompilePanel.progress.overall" txt="Prozesuaren aurrerabide globala:"/>
    <str id="CompilePanel.error" txt="Konpilazioak huts egin du"/>
    <str id="CompilePanel.error.reconfigure" txt="Berkonfiguratu"/>
    <str id="CompilePanel.error.ignore" txt="Kontutan ez hartu"/>
    <str id="CompilePanel.error.abort" txt="Utzi"/>
    <str id="CompilePanel.error.seebelow" txt="Beheko partean begiratu huts egindako komandua eta bere irteera. "/>
    <str id="CompilePanel.error.nofiles" txt="Eskaneatzerakoan errorea konpilatutako fitxeroetan."/>
    <str id="CompilePanel.error.compilernotfound" txt="Konpiladorea ezin da exekutatu."/>
    <str id="CompilePanel.error.invalidarguments" txt="Konpiladoreari pasatutako argumentuak baliogabeak dira. "/>
    <str id="CompilePanel.error.noclassfile" txt="Konpiladoreak ez ditu class fitxeroak sortu iturri fitxeroetatik. "/>
    <str id="CompilePanel.choose_compiler" txt="Erabiltzeko konpiladorea:"/>
    <str id="CompilePanel.additional_arguments" txt="Konpiladorearen argumentu gehigarriak:"/>

    <!-- ProcessPanel strings -->
    <str id="ProcessPanel.heading" txt="Prozesatu"/>

    <!-- SummaryPanel strings -->
    <str id="SummaryPanel.info"
         txt="Instalazioa hurrengoko konfigurazioarekin hasiko da. Sakatu Aurrera jarraitzeko."/>
    <str id="SummaryPanel.next" txt="Aurrera"/>
    <str id="TargetPanel.summaryCaption" txt="Instalazio bidea"/>
    <str id="JDKPathPanel.summaryCaption" txt="JDK bidea"/>
    <str id="PacksPanel.summaryCaption" txt="Aukeratutako instalazio paketeak"/>
    <str id="ImgPacksPanel.summaryCaption" txt="Aukeratutako Instalazio Paketeak"/>
    <str id="TreePacksPanel.summaryCaption" txt="Aukeratutako Instalazio Paketeak"/>
    <str id="UserPathPanel.summaryCaption" txt="Aukeratutako bidea"/>
    <str id="DefaultTargetPanel.summaryCaption" txt="Instalazio bidea"/>

    <!-- Strings for the Registry -->
    <str id="functionFailed.RegOpenKeyEx" txt="Cannot open registry key {0}\\{1}."/>

    <!-- CheckedHelloPanel strings -->
    <str id="CheckedHelloPanel.productAlreadyExist0"
         txt="Produktu hau bide berberean berinstalatuta dago ordenadore hontan"/>
    <str id="CheckedHelloPanel.productAlreadyExist1" txt=" . Zihur al zaude, beste entitate bat sortzearekin?"/>
    <str id="CheckedHelloPanel.infoOverUninstallKey" txt="Desinstalazio giltza berrizendatua izango da: "/>

    <!-- Next Media Strings -->
    <str id="nextmedia.title" txt="Next install media"/>
    <str id="nextmedia.msg" txt="Choose the next install media."/>
    <str id="nextmedia.browsebtn" txt="Browse"/>
    <str id="nextmedia.okbtn" txt="Apply"/>
    <str id="nextmedia.cancelbtn" txt="Cancel"/>
    <str id="nextmedia.choosertitle" txt="Choose install media"/>
    <str id="nextmedia.filedesc" txt="install packs (.pak*)"/>

    <!-- This string defines the time stamp format in the installation report.
The format details are documented in java.text.SimpleDateFormat -->
    <str id="log.timeStamp" txt="MM-dd-yyyy [HH:mm:ss]  zzzz"/>

    <!-- Strings for various purposes in the logging/reporting system  -->
    <str id="log.reportHeading" txt="                           IzPack INSTALLATION REPORT"/>
    <str id="log.installFailed" txt="WARNING!!! Instalazioa ez du arrakastarik izan!"/>
    <str id="log.partialInstall" txt="WARNING!!! Instalazioa ez dirudi arrakastarik izan duen!"/>
    <str id="log.messageCount" txt="Informe honek baditu {0} mezu generalak, {1} abisuak eta {2} erroreak"/>
    <str id="log.application" txt="Installation report for : {0} Version {1}"/>
    <str id="log.timePrefix" txt="Install time            : {0}"/>
    <str id="log.pathPrefix" txt="Install directory       : {0}"/>
    <str id="log.messageHeading" txt="                         --- Installation Messages ---"/>
    <str id="log.warningHeading" txt="                               --- Warnings ---"/>
    <str id="log.errorHeading" txt="                                --- Errors ---"/>
    <str id="log.exceptionPrefix" txt="                 >> Exception: {0}"/>
    <str id="log.messagePrefix" txt="Message  [{0}] - "/>
    <str id="log.warningPrefix" txt="Warning [{0}] - "/>
    <str id="log.errorPrefix" txt="Error [{0}] - "/>
    <str id="log.reportWriteErrorTitle" txt="Errorea informea idazten"/>
    <str id="log.reportWriteError" txt="Ezinezkoa instalazio informea idaztea to ''{0}''"/>
    <str id="log.informUserTitle" txt="Instalazio arazoak"/>
    <str id="log.saveLogTitle" txt="Log fitxategia gorde"/>
    <str id="log.LogFileName" txt="installLog.txt"/>
    <str id="log.informUserFail"
         txt="<html>Instalazioa ez da arrakastatsua izan!<br>Gustatuko al litzaizuke log fitxategia idaztea?</html>"/>
    <str id="log.informUserPartial"
         txt="<html>Instalazioa arrakastatsua izan da oso!!<br>Gustatuko al litzaizuke log fitxategia idaztea?</html>"/>

    <!-- Strings for individual messages in the logging/reporting system.
         Numbers for each category (message/warning/error) start at 0  -->
    <str id="log.message_" txt=""/>
    <str id="log.warning_" txt=""/>
    <str id="log.error_0" txt="unable to write ''{0}''"/>
    <str id="debug.changevariable" txt="modify value"/>

</izpack:langpack>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

  <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring">
    <!-- START SNIPPET: pgp-xml-basic -->
    <dataFormats>
      <!-- will load the file from classpath by default, but you can prefix with file: to load from file system -->
      <pgp id="encrypt" keyFileName="org/apache/camel/component/crypto/pubring.gpg"
           keyUserid="sdude@nowhere.net"/>
      <pgp id="decrypt" keyFileName="org/apache/camel/component/crypto/secring.gpg"
           password="sdude"/>
    </dataFormats>

    <route>
      <from uri="direct:inline"/>
      <marshal ref="encrypt"/>
      <to uri="mock:encrypted"/>
      <unmarshal ref="decrypt"/>
      <to uri="mock:unencrypted"/>
    </route>
    <!-- END SNIPPET: pgp-xml-basic -->

    <!-- START SNIPPET: pgp-xml-data-format-bean-with-keyring-bytearray -->
    <route>
      <from uri="direct:pgp-key-ring-byte-array"/>
      <marshal ref="encryptBean"/>
      <to uri="mock:encrypted"/>
      <unmarshal ref="decryptBean"/>
      <to uri="mock:unencrypted"/>
    </route>
  </camelContext>

   <bean id="encryptBean" class="org.apache.camel.converter.crypto.PGPDataFormat">
      <property name="keyUserid" value="sdude@nowhere.net"/>
      <property name="encryptionKeyRing" ref="pubKeyRing"/>
      <property name="algorithm" value="7"/> <!-- AES128  algorithm -->
      <property name="compressionAlgorithm" value="3"/> <!-- BZ2 compression -->
   </bean>

   <bean id="decryptBean" class="org.apache.camel.converter.crypto.PGPDataFormat">
      <property name="encryptionKeyRing" ref="secKeyRing"/>
      <property name="passphraseAccessor" ref="passphraseAccessorBean"/>
   </bean>

   <!-- bean represents the public key ring as byte array -->
   <bean id="pubKeyRing"
		class="org.apache.camel.converter.crypto.PGPDataFormatTest"
		factory-method="getPublicKeyRing" />

	<!-- bean represents the secret key ring as byte array -->
   <bean id="secKeyRing"
		class="org.apache.camel.converter.crypto.PGPDataFormatTest"
		factory-method="getSecKeyRing" />

    <!-- bean passphrase accessor  -->
     <bean id="passphraseAccessorBean"
        class="org.apache.camel.converter.crypto.PGPDataFormatTest"
        factory-method="getPassphraseAccessor" />
    <!-- END SNIPPET:  pgp-xml-data-format-bean-with-keyring-bytearray -->
</beans>


text:
layout: single
title: "Git: Git Log With Authors"
date: 2018-09-27 10:14
modified: 2018-09-27 10:14
categories: til
tags:
  - git
  - til
---

In my [never-ending quest](https://til.hashrocket.com/posts/32d01c979e-git-log-since)
to better summarize my work at the end of the day using computers,
I discovered today the Git `--author` flag. It works like this:

```bash
$ glg --since=midnight --author=dev+jwworth+mikechau@hashrocket.com
* 4ba91a8 (HEAD, origin/checkout, checkout) Add guard for manual entry
* 3a4e4c9 Seed a coupon and code and auto-apply in preview
* cb1adee Add discount
...
```

The alias `glg` is discussed
[here](https://til.hashrocket.com/posts/32d01c979e-git-log-since).

I use this when multiple developers or teams are committing throughout the day
to the same repository, to disambiguate our work from others.
Ready to paste into your billing software of choice.

Via [jwworth/til](https://github.com/jwworth/til).


text:
package io.truthencode.ddo.model.feats

import io.truthencode.ddo.model.race.Race
import io.truthencode.ddo.support.requisite.{FeatRequisiteImpl, RaceRequisite, RequiresAnyOfRace}

/**
 * Created by adarr on 2/20/2017.
 */
trait SpellSaveBonus
  extends FeatRequisiteImpl with RaceRequisite with Passive with RequiresAnyOfRace {
  override def anyOfRace: Seq[(Race, Int)] =
    List((Race.DrowElf, 1), (Race.Dwarf, 1))

  override def grantsToRace: Seq[(Race, Int)] =
    List((Race.DrowElf, 1), (Race.Dwarf, 1))
}


text:
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// "tTJS" script language API class implementation
//---------------------------------------------------------------------------

#ifndef tjsH
#define tjsH

#include <vector>
#include "tjsConfig.h"
#include "tjsVariant.h"
#include "tjsInterface.h"
#include "tjsString.h"
#include "tjsMessage.h"

namespace TJS
{

//---------------------------------------------------------------------------
// TJS version
//---------------------------------------------------------------------------
extern tjs_int TJSVersionMajor;
extern tjs_int TJSVersionMinor;
extern tjs_int TJSVersionRelease;

extern tjs_char TJSCompiledDate[];
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Console output callback interface
//---------------------------------------------------------------------------
class iTJSConsoleOutput
{
public:
	virtual void ExceptionPrint(const tjs_char *msg) = 0;
	virtual void Print(const tjs_char *msg) = 0;
};
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Object Hash Size Limit ( must be larger than or equal to 0 )
//---------------------------------------------------------------------------
extern tjs_int TJSObjectHashBitsLimit;

//---------------------------------------------------------------------------
// global options
//---------------------------------------------------------------------------
extern bool TJSEvalOperatorIsOnGlobal;
	// Post-! operator (evaluate expression) is to be executed on "this" context
	// since TJS2 2.4.1.
	// Turn this switch true makes post-! operator running on global context,
	// like TJS2 before 2.4.1.
extern bool TJSWarnOnNonGlobalEvalOperator;
	// Output warning against non-local post-! operator.
	// (For checking where the post-! operators are used)

//---------------------------------------------------------------------------
// tTJS class - "tTJS" TJS API Class
//---------------------------------------------------------------------------
class tTJSScriptBlock;
class tTJSPPMap;
class tTJSCustomObject;
class tTJSScriptCache;
class tTJS
{
	friend class tTJSScriptBlock;
private:
	tjs_uint RefCount; // reference count

public:
	tTJS();

protected:
	virtual ~tTJS();

public:
	void AddRef();
	void Release();

	void Shutdown();

private:
	tTJSPPMap * PPValues;

	std::vector<tTJSScriptBlock*> ScriptBlocks;

	iTJSConsoleOutput *ConsoleOutput;

	tTJSCustomObject * Global;

	tTJSScriptCache * Cache;

public:
	iTJSDispatch2 * GetGlobal();
	iTJSDispatch2 * GetGlobalNoAddRef() const;

private:
	void AddScriptBlock(tTJSScriptBlock *block);
	void RemoveScriptBlock(tTJSScriptBlock *block);

public:
	void SetConsoleOutput(iTJSConsoleOutput *console);
	iTJSConsoleOutput * GetConsoleOutput() const { return ConsoleOutput; };
	void OutputToConsole(const tjs_char *msg) const;
	void OutputExceptionToConsole(const tjs_char *msg) const;
	void OutputToConsoleWithCentering(const tjs_char *msg, tjs_uint width) const;
	void OutputToConsoleSeparator(const tjs_char *text, tjs_uint count) const;

	void Dump(tjs_uint width = 80) const; // dumps all existing script block

	void ExecScript(const tjs_char *script, tTJSVariant *result = NULL,
		iTJSDispatch2 *context = NULL,
		const tjs_char *name = NULL, tjs_int lineofs = 0);

	void ExecScript(const ttstr &script, tTJSVariant *result = NULL,
		iTJSDispatch2 *context = NULL,
		const ttstr *name = NULL, tjs_int lineofs = 0);

	void EvalExpression(const tjs_char *expression, tTJSVariant *result,
		iTJSDispatch2 *context = NULL,
		const tjs_char *name = NULL, tjs_int lineofs = 0);

	void EvalExpression(const ttstr &expression, tTJSVariant *result,
		iTJSDispatch2 *context = NULL,
		const ttstr *name = NULL, tjs_int lineofs = 0);

	void SetPPValue(const tjs_char *name, const tjs_int32 value);
	tjs_int32 GetPPValue(const tjs_char *name);

	void DoGarbageCollection();

};
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// tTJSTextStream - used by Array.save/load Dictionaty.save/load
//---------------------------------------------------------------------------
class tTJSString;
class tTJSTextReadStream
{
public:
	virtual TJS_INTF_METHOD tjs_uint Read(tTJSString & targ, tjs_uint size) = 0;
	virtual ~tTJSTextReadStream() {;}
};
//---------------------------------------------------------------------------
class tTJSTextWriteStream
{
public:
	virtual TJS_INTF_METHOD void Write(const tTJSString & targ) = 0;
	virtual ~tTJSTextWriteStream() {;}
};
//---------------------------------------------------------------------------
extern tTJSTextReadStream * (*TJSCreateTextStreamForRead)(const tTJSString &name,
	const tTJSString &modestr);
extern tTJSTextWriteStream * (*TJSCreateTextStreamForWrite)(const tTJSString &name,
	const tTJSString &modestr);
//---------------------------------------------------------------------------

/*[*/
//---------------------------------------------------------------------------
// tTJSBinaryStream constants
//---------------------------------------------------------------------------
#define TJS_BS_READ 0
#define TJS_BS_WRITE 1
#define TJS_BS_APPEND 2
#define TJS_BS_UPDATE 3

#define TJS_BS_ACCESS_MASK 0x0f

#define TJS_BS_SEEK_SET 0
#define TJS_BS_SEEK_CUR 1
#define TJS_BS_SEEK_END 2
//---------------------------------------------------------------------------
/*]*/

//---------------------------------------------------------------------------
// tTJSBinaryStream base stream class
//---------------------------------------------------------------------------
class tTJSBinaryStream
{
private:
public:
	//-- must implement
	virtual tjs_uint64 TJS_INTF_METHOD Seek(tjs_int64 offset, tjs_int whence) = 0;
		/* if error, position is not changed */

	//-- optionally to implement
	virtual tjs_uint TJS_INTF_METHOD Read(void *buffer, tjs_uint read_size) = 0;
		/* returns actually read size */

	virtual tjs_uint TJS_INTF_METHOD Write(const void *buffer, tjs_uint write_size) = 0;
		/* returns actually written size */

	virtual void TJS_INTF_METHOD SetEndOfStorage();
		// the default behavior is raising a exception
		/* if error, raises exception */

	//-- should re-implement for higher performance
	virtual tjs_uint64 TJS_INTF_METHOD GetSize() = 0;

	virtual ~tTJSBinaryStream() {;}

	tjs_uint64 GetPosition();

	void SetPosition(tjs_uint64 pos);

	void ReadBuffer(void *buffer, tjs_uint read_size);
	void WriteBuffer(const void *buffer, tjs_uint write_size);

	tjs_uint64 ReadI64LE(); // reads little-endian integers
	tjs_uint32 ReadI32LE();
	tjs_uint16 ReadI16LE();
};
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------

}
#endif


text:
package com.siyeh.igtest.errorhandling.try_identical_catches;

import java.io.*;

class TryIdenticalCatches {
  public void notIdentical() {
    try {

    }
    catch(NumberFormatException e) {
      log(e);
    }
    catch(RuntimeException e) {
      throw e;
    }
  }

  String nonIdenticalButDuplicated(Object o) {
        try {
        } catch (NullPointerException e) {
            if (o instanceof String) {
                return a((String) o);
            }
        } catch (NumberFormatException e) {
            if (o instanceof String) {
                return b((String) o);
            }
        }
        return null;
  }

  String a(String s) { return s;}
  String b(String s) { return s;}

  public void nonIdenticalWithParameterValue() throws StorageException {
    try {
      throwAllExceptions();
    }
    catch (StorageInitializationException e) {
      throw e;
    }
    catch (java.io.IOException e) {
      throw new StorageInitializationException("Can not setup storage factory.", e);
    }
    catch (Exception e) {
      throw new StorageInitializationException("Unspecified exception occurs while DB storage initialization.", e);
    }
  }

  void throwAllExceptions() throws StorageInitializationException, java.io.IOException {
  }

  class StorageException extends Exception {
  }

  class StorageInitializationException extends StorageException {
    private StorageInitializationException(String m, Exception e) {
    }
  }

  public void identicalWithoutParams(boolean value) {
     try {
       if (value) {
         throw new ClassNotFoundException();
       }
       else {
         throw new NumberFormatException();
       }
     }
     catch(ClassNotFoundException cnfe) {
       System.out.println();
     }
     <warning descr="'catch' branch identical to 'ClassNotFoundException' branch">catch(NumberFormatException nfe)</warning> {
      System.out.println();
     }
   }

  public void identical(boolean value) {
    try {
      if (value) {
        throw new ClassNotFoundException();
      }
      else {
        throw new NumberFormatException();
      }
    }
    catch(ClassNotFoundException cnfe) {
      log(cnfe);
    }
    <warning descr="'catch' branch identical to 'ClassNotFoundException' branch">catch(NumberFormatException n<caret>fe)</warning> {
      log(nfe);
    }
  }

  private void log(Exception e) {
  }

  class E1 extends RuntimeException {}
  class E2 extends E1 {}
  class E3 extends RuntimeException {}
  class E4 extends E3 {}

  void p() {
    try {

    } catch (E4 e) {
    } <warning descr="'catch' branch identical to 'E4' branch">catch (E2 e)</warning> {
    } <warning descr="'catch' branch identical to 'E4' branch">catch (E3 e)</warning> {
    } <warning descr="'catch' branch identical to 'E2' branch">catch (E1 e)</warning> {
    }
  }

  void q() {
    try {
      Class.forName("bla").newInstance();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    } catch (<error descr="Cannot resolve symbol 'InstantiationException'">InstantiationException</error><error descr="Identifier expected"> </error>) {
      <error descr="Cannot resolve symbol 'e'">e</error>.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    } catch (IllegalAccessException e) {
      e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
  }

  public static void main() {
    Throwable causeException;
    try {
      throw new NullPointerException();
    } catch (final NullPointerException e) {
      causeException = e;
    } <warning descr="'catch' branch identical to 'NullPointerException' branch">catch (final IllegalArgumentException e)</warning> {
      causeException = e;
    } <warning descr="'catch' branch identical to 'NullPointerException' branch">catch (final IndexOutOfBoundsException e)</warning> {
      causeException = e;
    }
    System.out.println("causeException = " + causeException);
  }

  public void x() throws IOException {
    try {
      foo();
    } catch (FileNotFoundException e) {
      throw e;
    } catch (IOException e) {
      throw INSTANCE;
    }
  }

  public void y() throws IOException {
    try {

    } catch (RuntimeException g) {
      try {
        foo();
      } catch (FileNotFoundException e) {
        throw e;
      } catch (IOException e) {
        throw g;
      }
    }
  }

  void foo() throws IOException {}
  private static final IOException INSTANCE = new IOException();

  public boolean returning() {
    try {
      // work
    }
    catch(NumberFormatException e) {
      return true;
    }
    <warning descr="'catch' branch identical to 'NumberFormatException' branch">catch(RuntimeException e)</warning> {
      return true;
    }
    return false;
  }

  public void suppress() {
    try {
      // ...
    }
    catch (NumberFormatException e) {
      System.out.println(e);
    }
    catch (@SuppressWarnings("TryWithIdenticalCatches") RuntimeException e) {
      System.out.println(e);
    }
  }
}
class TestInspection {
  public void foo() throws MyException {
    try {
      toString();
    } catch (IllegalArgumentException e) {
      throw new MyException(e);
    } catch (IllegalStateException e) {
      throw new MyException(e);
    }
  }

  private static class MyException extends Exception {
    public MyException(IllegalArgumentException e) {}

    public MyException(IllegalStateException e) {}
  }
}


text:
Given a string containing brackets `[]`, braces `{}` and parentheses `()`,
verify that all the pairs are matched and nested correctly.

## Setup

Go through the project setup instructions for Xcode using Swift:

http://exercism.io/languages/swift
http://exercism.io/languages/swift/tests

Notably from the source directory:

`swift test` runs tests
`swift package generate-xcodeproj` creates an Xcode project

## Source

Ginna Baker

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
'use strict';
// https://github.com/mafintosh/is-my-json-valid
// http://json-schema.org/documentation.html
module.exports = {
    name: 'todo',
    type: 'object',
    additionalProperties: false,
    required: ['title'],
    properties: {
        id:         { type: 'string', maxLength: 64 },
        title:      { type: 'string', maxLength: 255 },
        isComplete: { type: 'boolean' }
    }
};


text:
package org.wso2.carbon.identity.oauth2.token.handlers.grant;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;

/**
 * Grant Handler for Grant Type : client_credentials
 */
public class ClientCredentialsGrantHandler extends AbstractAuthorizationGrantHandler {

    private static Log log = LogFactory.getLog(ClientCredentialsGrantHandler.class);

    @Override
    public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
            throws IdentityOAuth2Exception {

        if(!super.validateGrant(tokReqMsgCtx)){
            return false;
        }

        // By this time, we have already validated client credentials.
        tokReqMsgCtx.setScope(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getScope());
        return true;
    }

    public boolean issueRefreshToken() throws IdentityOAuth2Exception {
        return false;
    }

    public boolean isOfTypeApplicationUser() throws IdentityOAuth2Exception {
        return false;
    }
}


text:
from PySide import QtCore, QtGui

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(1081, 701)
        self.verticalLayout = QtGui.QVBoxLayout(Dialog)
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label = QtGui.QLabel(Dialog)
        self.label.setObjectName("label")
        self.horizontalLayout.addWidget(self.label)
        self.projects_comboBox = QtGui.QComboBox(Dialog)
        self.projects_comboBox.setObjectName("projects_comboBox")
        self.horizontalLayout.addWidget(self.projects_comboBox)
        self.client_label = QtGui.QLabel(Dialog)
        self.client_label.setObjectName("client_label")
        self.horizontalLayout.addWidget(self.client_label)
        self.client_name_label = QtGui.QLabel(Dialog)
        self.client_name_label.setObjectName("client_name_label")
        self.horizontalLayout.addWidget(self.client_name_label)
        spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.tabWidget = QtGui.QTabWidget(Dialog)
        self.tabWidget.setObjectName("tabWidget")
        self.assets_tab = QtGui.QWidget()
        self.assets_tab.setObjectName("assets_tab")
        self.verticalLayout_2 = QtGui.QVBoxLayout(self.assets_tab)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.assets_tableWidget = QtGui.QTableWidget(self.assets_tab)
        self.assets_tableWidget.setAutoFillBackground(True)
        self.assets_tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.assets_tableWidget.setObjectName("assets_tableWidget")
        self.assets_tableWidget.setColumnCount(2)
        self.assets_tableWidget.setRowCount(0)
        item = QtGui.QTableWidgetItem()
        self.assets_tableWidget.setHorizontalHeaderItem(0, item)
        item = QtGui.QTableWidgetItem()
        self.assets_tableWidget.setHorizontalHeaderItem(1, item)
        self.assets_tableWidget.horizontalHeader().setStretchLastSection(True)
        self.verticalLayout_2.addWidget(self.assets_tableWidget)
        self.tabWidget.addTab(self.assets_tab, "")
        self.shots_tab = QtGui.QWidget()
        self.shots_tab.setObjectName("shots_tab")
        self.verticalLayout_3 = QtGui.QVBoxLayout(self.shots_tab)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.shots_tableWidget = QtGui.QTableWidget(self.shots_tab)
        self.shots_tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.shots_tableWidget.setObjectName("shots_tableWidget")
        self.shots_tableWidget.setColumnCount(2)
        self.shots_tableWidget.setRowCount(0)
        item = QtGui.QTableWidgetItem()
        self.shots_tableWidget.setHorizontalHeaderItem(0, item)
        item = QtGui.QTableWidgetItem()
        self.shots_tableWidget.setHorizontalHeaderItem(1, item)
        self.shots_tableWidget.horizontalHeader().setStretchLastSection(True)
        self.verticalLayout_3.addWidget(self.shots_tableWidget)
        self.tabWidget.addTab(self.shots_tab, "")
        self.verticalLayout.addWidget(self.tabWidget)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setContentsMargins(-1, 10, -1, -1)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem1)
        self.close_pushButton = QtGui.QPushButton(Dialog)
        self.close_pushButton.setObjectName("close_pushButton")
        self.horizontalLayout_2.addWidget(self.close_pushButton)
        self.verticalLayout.addLayout(self.horizontalLayout_2)

        self.retranslateUi(Dialog)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("Dialog", "Project", None, QtGui.QApplication.UnicodeUTF8))
        self.client_label.setText(QtGui.QApplication.translate("Dialog", "Client:", None, QtGui.QApplication.UnicodeUTF8))
        self.client_name_label.setText(QtGui.QApplication.translate("Dialog", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
        self.assets_tableWidget.setToolTip(QtGui.QApplication.translate("Dialog", "
Right click to:

Change Status

Browse Outputs

", None, QtGui.QApplication.UnicodeUTF8))
        self.assets_tableWidget.horizontalHeaderItem(0).setText(QtGui.QApplication.translate("Dialog", "Name", None, QtGui.QApplication.UnicodeUTF8))
        self.assets_tableWidget.horizontalHeaderItem(1).setText(QtGui.QApplication.translate("Dialog", "Take", None, QtGui.QApplication.UnicodeUTF8))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.assets_tab), QtGui.QApplication.translate("Dialog", "Assets", None, QtGui.QApplication.UnicodeUTF8))
        self.shots_tableWidget.setToolTip(QtGui.QApplication.translate("Dialog", "
Right click to:

Change Status

Browse Outputs

", None, QtGui.QApplication.UnicodeUTF8))
        self.shots_tableWidget.horizontalHeaderItem(0).setText(QtGui.QApplication.translate("Dialog", "Sequence", None, QtGui.QApplication.UnicodeUTF8))
        self.shots_tableWidget.horizontalHeaderItem(1).setText(QtGui.QApplication.translate("Dialog", "Number", None, QtGui.QApplication.UnicodeUTF8))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.shots_tab), QtGui.QApplication.translate("Dialog", "Shots", None, QtGui.QApplication.UnicodeUTF8))
        self.close_pushButton.setText(QtGui.QApplication.translate("Dialog", "Close", None, QtGui.QApplication.UnicodeUTF8))


text:
@interface BookmarkAllCollectionView : BookmarkCollectionView
@property(nonatomic, assign) id<BookmarkCollectionViewDelegate> delegate;
@end

#endif  // IOS_CHROME_BROWSER_UI_BOOKMARKS_BOOKMARK_ALL_COLLECTION_VIEW_H_


text:
<?php

namespace PHP_CodeSniffer\Standards\Squiz\Tests\PHP;

use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;

class DisallowInlineIfUnitTest extends AbstractSniffUnitTest
{

    /**
     * Returns the lines where errors should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of errors that should occur on that line.
     *
     * @param string $testFile The name of the file being tested.
     *
     * @return array<int, int>
     */
    public function getErrorList($testFile='DisallowInlineIfUnitTest.inc')
    {
        switch ($testFile) {
        case 'DisallowInlineIfUnitTest.inc':
            return [
                8  => 1,
                18 => 1,
            ];
            break;
        case 'DisallowInlineIfUnitTest.js':
            return [1 => 1];
            break;
        default:
            return [];
            break;
        }//end switch

    }//end getErrorList()

    /**
     * Returns the lines where warnings should occur.
     *
     * The key of the array should represent the line number and the value
     * should represent the number of warnings that should occur on that line.
     *
     * @return array<int, int>
     */
    public function getWarningList()
    {
        return [];

    }//end getWarningList()

}//end class


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace Kolkata_Geeks.Pages
{
    public partial class About : PhoneApplicationPage
    {
        public About()
        {
            InitializeComponent();
        }

        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask web = new WebBrowserTask();
            web.Uri = new Uri("https://www.facebook.com/shaan.shahnawazalam", UriKind.RelativeOrAbsolute);
            web.Show();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            EmailComposeTask email = new EmailComposeTask();
            email.To = "don.coolbuddy.xxx@gmail.com";
            email.Subject = "Kolkata Geeks App | Feedback";
            email.Show();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            MarketplaceDetailTask market = new MarketplaceDetailTask();
            market.Show();
        }
    }
}


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

<title>Overview List</title>
<meta name="date" content="2016-12-22">
<link rel="stylesheet" type="text/css" href="javadoc-stylesheet.css" title="Style">

All Classes

Packages

edu.brown.cs.systems.baggage_buffers_examples

edu.brown.cs.systems.baggage_buffers.gen.example

edu.brown.cs.systems.tracingplane.atom_layer

edu.brown.cs.systems.tracingplane.atom_layer.impl

edu.brown.cs.systems.tracingplane.atom_layer.protocol

edu.brown.cs.systems.tracingplane.atom_layer.types

edu.brown.cs.systems.tracingplane.baggage_buffers

edu.brown.cs.systems.tracingplane.baggage_buffers.api

edu.brown.cs.systems.tracingplane.baggage_buffers.compiler

edu.brown.cs.systems.tracingplane.baggage_buffers.impl

edu.brown.cs.systems.tracingplane.baggage_layer

edu.brown.cs.systems.tracingplane.baggage_layer.impl

edu.brown.cs.systems.tracingplane.baggage_layer.protocol

edu.brown.cs.systems.tracingplane.transit_layer

edu.brown.cs.systems.tracingplane.transit_layer.impl

edu.brown.xtrace


text:
import * as React from 'react'
import * as Styles from '../styles'
import {Image, type ImageProps} from 'react-native'
import RNFI, {type OnProgressEvent} from 'react-native-fast-image'
import isArray from 'lodash/isArray'
import LoadingStateView from './loading-state-view'
import {memoize} from '../util/memoize'
import isEqual from 'lodash/isEqual'

export class NativeImage extends React.Component<ImageProps> {
  static getSize = Image.getSize
  render() {
    return <Image {...this.props} fadeDuration={0} />
  }
}

type FastImageImplState = {
  loading: boolean
  progress: number
}

class FastImageImpl extends React.PureComponent<
  ImageProps & {showLoadingStateUntilLoaded?: boolean},
  FastImageImplState
> {
  static resizeMode = RNFI.resizeMode
  static getSize = Image.getSize
  state = {
    loading: true,
    progress: 0,
  }

  _mounted = true
  componentWillUnmount() {
    this._mounted = false
  }

  private onLoadStart = () => {
    this._mounted && this.setState({loading: true})
    this.props.onLoadStart?.()
  }
  private onLoadEnd = () => {
    this._mounted && this.setState({loading: false})
    this.props.onLoadEnd?.()
  }
  private onProgress = (evt: OnProgressEvent) => {
    this._mounted && this.setState({progress: evt.nativeEvent?.loaded / evt.nativeEvent?.total || 0})
    this.props.onProgress?.(evt as any)
  }

  private getStyle = memoize((style, loading) => {
    return Styles.collapseStyles([style, loading ? styles.loading : styles.loaded] as const)
  }, isEqual)

  private getSource = memoize(source =>
    isArray(source)
      ? {uri: source[0].uri} // TODO smarter choice?
      : {uri: source.uri}
  )

  render() {
    if (typeof this.props.source === 'number') {
      return null
    }

    const source = this.getSource(this.props.source)

    if (!source.uri) {
      return null
    }

    // TODO maybe use reanimated2
    return (
      <>
        <RNFI
          {...(this.props as any)}
          style={this.getStyle(
            this.props.style,
            this.props.showLoadingStateUntilLoaded && this.state.loading
          )}
          onLoadStart={this.onLoadStart}
          onLoadEnd={this.onLoadEnd}
          onProgress={this.onProgress}
          source={source}
        />
        {this.props.showLoadingStateUntilLoaded ? (
          <LoadingStateView loading={this.state.loading} progress={this.state.progress} white={true} />
        ) : null}
      </>
    )
  }
}

const styles = Styles.styleSheetCreate(() => ({
  loaded: {opacity: 1},
  loading: {opacity: 0, position: 'absolute'},
}))

export const FastImage = FastImageImpl


text:
package org.apache.phoenix.hbase.index.covered.data;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;

public class TestLocalTable {
    private static final byte[] ROW = Bytes.toBytes("test_row");

    @Test
    public void testGetOldestTimestamp() {
        LocalTable localTable = new LocalTable(null);

        List<Cell> cellList1 = getCellList(new KeyValue(ROW, 5L), new KeyValue(ROW, 4L));
        assertEquals(4L, localTable.getOldestTimestamp(Collections.singletonList(cellList1)));

        List<Cell> cellList2 = getCellList(new KeyValue(ROW, 5L), new KeyValue(ROW, 2L));
        List<List<Cell>> set1 = new ArrayList<>(Arrays.asList(cellList1, cellList2));
        assertEquals(2L, localTable.getOldestTimestamp(set1));

        List<Cell> cellList3 = getCellList(new KeyValue(ROW, 1L));
        set1.add(cellList3);
        assertEquals(1L, localTable.getOldestTimestamp(set1));

        List<Cell> cellList4 =
                getCellList(new KeyValue(ROW, 3L), new KeyValue(ROW, 1L), new KeyValue(ROW, 0L));
        set1.add(cellList4);
        assertEquals(0L, localTable.getOldestTimestamp(set1));
    }

    private List<Cell> getCellList(KeyValue... kvs) {
        List<Cell> cellList = new ArrayList<>();
        for (KeyValue kv : kvs) {
            cellList.add(kv);
        }
        return cellList;
    }
}


text:
namespace Txt.Core
{
    /// Provides the interface for types that provide contextual information about their source data.
    public interface ITextContext
    {
        /// Gets the column number, relative to the beginning of the <see cref="Line" />.
        int Column { get; }

        /// Gets the line number, relative to the beginning of the text.
        int Line { get; }

        /// Gets the character position, relative to the beginning of the text.
        long Offset { get; }
    }
}


text:
/**
 * Module dependencies
 */

var mongoose = require('mongoose')

/**
 * Connect to MongoDb
 */

mongoose.connect('mongodb://localhost/crud')

/**
 * UserModel
 */

require('./Users')


text:
{% extends "base.html" %}
{% load Kraggne_tags %}

{% block page.body %}

        {% try_display object %}

{% endblock %}


text:
using CodeCracker.CSharp.Style;
using Microsoft.CodeAnalysis;
using System.Threading.Tasks;
using Xunit;

namespace CodeCracker.Test.CSharp.Style
{
    public class TaskNameAsyncTests : CodeFixVerifier<TaskNameAsyncAnalyzer, TaskNameAsyncCodeFixProvider>
    {
        [Fact]
        public async Task TaskNameAsyncMethodEqualsNameMethodInterface()
        {
            const string source = @"
            using System.Threading.Tasks;

            namespace ConsoleApplication1
            {
                public interface IBar
                {
                    Task Foo();
                }

                public class Bar : IBar
                {
                    public Task Foo()
                    { }
                }
            }";
            var expected = new DiagnosticResult
            {
                Id = DiagnosticId.TaskNameAsync.ToDiagnosticId(),
                Message = string.Format(TaskNameAsyncAnalyzer.MessageFormat, "FooAsync"),
                Severity = DiagnosticSeverity.Info,
                Locations = new[] { new DiagnosticResultLocation("Test0.cs", 8, 26) }
            };

            await VerifyCSharpDiagnosticAsync(source, expected);
        }

        [Fact]
        public async Task TaskNameAsyncMethodCorrect()
        {
            const string source = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            Task TestAsync() {};
        }
    }";
            await VerifyCSharpHasNoDiagnosticsAsync(source);
        }

        [Fact]
        public async Task TaskNameAsyncMethodWhithoutAsyncNameAndOverridesShouldNotCreateDiagnostic()
        {
            const string source = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            overrides Task Test() {};
        }
    }";

            await VerifyCSharpHasNoDiagnosticsAsync(source);
        }

        [Fact]
        public async Task TaskNameAsyncMethodWhithoutAsyncNameAndShadowsShouldNotCreateDiagnostic()
        {
            const string source = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            new Task Test() {};
        }
    }";

            await VerifyCSharpHasNoDiagnosticsAsync(source);
        }

        [Fact]
        public async Task TaskNameAsyncMethodWhithoutAsyncName()
        {
            const string source = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            Task Test() {};
        }
    }";
            var expected = new DiagnosticResult
            {
                Id = DiagnosticId.TaskNameAsync.ToDiagnosticId(),
                Message = string.Format(TaskNameAsyncAnalyzer.MessageFormat, "TestAsync"),
                Severity = DiagnosticSeverity.Info,
                Locations = new[] { new DiagnosticResultLocation("Test0.cs", 8, 18) }
            };
            await VerifyCSharpDiagnosticAsync(source, expected);
        }

        [Fact]
        public async Task ChangeTaskNameWhithoutAsync()
        {
            const string source = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            Task Test() {};
        }
    }";
            const string fixtest = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            Task TestAsync() {};
        }
    }";
            await VerifyCSharpFixAsync(source, fixtest);
        }

        [Fact]
        public async Task ChangeTaskNameWhithoutAsyncAndClassImplementation()
        {
            const string source = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            public methodTest()
            {
                await Test();
            }

            public Task<bool> Test()
            {
                return true;
            }
        }

    }";
            const string fixtest = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public class Foo
        {
            public methodTest()
            {
                await TestAsync();
            }

            public Task<bool> TestAsync()
            {
                return true;
            }
        }

    }";
            await VerifyCSharpFixAsync(source, fixtest);
        }

        [Fact]
        public async Task ChangeTaskNameWhithoutAsyncAndInterfaceImplementation()
        {
            const string source = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public interface IFoo
        {
            public Task Test()
        }

    }";
            const string fixtest = @"
    using System.Threading.Tasks;

    namespace ConsoleApplication1
    {
        public interface IFoo
        {
            public Task TestAsync()
        }

    }";
            await VerifyCSharpFixAsync(source, fixtest);
        }

        [Fact]
        public async Task IgnoreMethodFromImplicitlyImplementedInterface()
        {
            const string source = @"
using System.Threading.Tasks;
public interface IBar
{
    Task Foo();
}
public class Bar : IBar
{
    public Task Foo()
    {
        throw new System.NotImplementedException();
    }
}";
            //we still get the diagnostic for the interface itself
            var expected = new DiagnosticResult
            {
                Id = DiagnosticId.TaskNameAsync.ToDiagnosticId(),
                Message = string.Format(TaskNameAsyncAnalyzer.MessageFormat, "FooAsync"),
                Severity = DiagnosticSeverity.Info,
                Locations = new[] { new DiagnosticResultLocation("Test0.cs", 5, 10) }
            };
            await VerifyCSharpDiagnosticAsync(source, expected);
        }

        [Fact]
        public async Task IgnoreMethodFromExplicitlyImplementedInterface()
        {
            const string source = @"
using System.Threading.Tasks;
public interface IBar
{
    Task Foo();
}
public class Bar : IBar
{
    Task IBar.Foo()
    {
        throw new System.NotImplementedException();
    }
}";
            //we still get the diagnostic for the interface itself
            var expected = new DiagnosticResult
            {
                Id = DiagnosticId.TaskNameAsync.ToDiagnosticId(),
                Message = string.Format(TaskNameAsyncAnalyzer.MessageFormat, "FooAsync"),
                Severity = DiagnosticSeverity.Info,
                Locations = new[] { new DiagnosticResultLocation("Test0.cs", 5, 10) }
            };
            await VerifyCSharpDiagnosticAsync(source, expected);
        }
    }
}


text:
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner

USAGE = """\
Custom test runner to allow testing of celery delayed tasks.
"""

class CeleryTestSuiteRunner(DjangoTestSuiteRunner):
    def run_tests(self, test_labels, *args, **kwargs):
        """Django test runner allowing testing of celery delayed tasks.
        All tasks are run locally, not in a worker.
        """
        settings.CELERY_ALWAYS_EAGER = True
        return super(CeleryTestSuiteRunner, self).run_tests(test_labels,
                *args, **kwargs)


text:
<?php

namespace Tests;

use BookStack\Auth\Permissions\JointPermissionBuilder;
use BookStack\Auth\Permissions\PermissionsRepo;
use BookStack\Auth\Permissions\RolePermission;
use BookStack\Auth\Role;
use BookStack\Auth\User;
use BookStack\Entities\Models\Entity;
use BookStack\Settings\SettingService;
use BookStack\Uploads\HttpFetcher;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Testing\Assert as PHPUnit;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Psr\Http\Client\ClientInterface;
use Ssddanbrown\AssertHtml\TestsHtml;
use Tests\Helpers\EntityProvider;
use Tests\Helpers\TestServiceProvider;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    use DatabaseTransactions;
    use TestsHtml;

    protected ?User $admin = null;
    protected ?User $editor = null;
    protected EntityProvider $entities;

    protected function setUp(): void
    {
        $this->entities = new EntityProvider();
        parent::setUp();
    }

    /**
     * The base URL to use while testing the application.
     */
    protected string $baseUrl = 'http://localhost';

    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        /** @var \Illuminate\Foundation\Application  $app */
        $app = require __DIR__ . '/../bootstrap/app.php';
        $app->register(TestServiceProvider::class);
        $app->make(Kernel::class)->bootstrap();

        return $app;
    }

    /**
     * Set the current user context to be an admin.
     */
    public function asAdmin()
    {
        return $this->actingAs($this->getAdmin());
    }

    /**
     * Get the current admin user.
     */
    public function getAdmin(): User
    {
        if (is_null($this->admin)) {
            $adminRole = Role::getSystemRole('admin');
            $this->admin = $adminRole->users->first();
        }

        return $this->admin;
    }

    /**
     * Set the current user context to be an editor.
     */
    public function asEditor()
    {
        return $this->actingAs($this->getEditor());
    }

    /**
     * Get a editor user.
     */
    protected function getEditor(): User
    {
        if ($this->editor === null) {
            $editorRole = Role::getRole('editor');
            $this->editor = $editorRole->users->first();
        }

        return $this->editor;
    }

    /**
     * Set the current user context to be a viewer.
     */
    public function asViewer()
    {
        return $this->actingAs($this->getViewer());
    }

    /**
     * Get an instance of a user with 'viewer' permissions.
     */
    protected function getViewer(array $attributes = []): User
    {
        $user = Role::getRole('viewer')->users()->first();
        if (!empty($attributes)) {
            $user->forceFill($attributes)->save();
        }

        return $user;
    }

    /**
     * Get a user that's not a system user such as the guest user.
     */
    public function getNormalUser(): User
    {
        return User::query()->where('system_name', '=', null)->get()->last();
    }

    /**
     * Quickly sets an array of settings.
     */
    protected function setSettings(array $settingsArray): void
    {
        $settings = app(SettingService::class);
        foreach ($settingsArray as $key => $value) {
            $settings->put($key, $value);
        }
    }

    /**
     * Give the given user some permissions.
     */
    protected function giveUserPermissions(User $user, array $permissions = []): void
    {
        $newRole = $this->createNewRole($permissions);
        $user->attachRole($newRole);
        $user->load('roles');
        $user->clearPermissionCache();
    }

    /**
     * Completely remove the given permission name from the given user.
     */
    protected function removePermissionFromUser(User $user, string $permissionName)
    {
        $permissionBuilder = app()->make(JointPermissionBuilder::class);

        /** @var RolePermission $permission */
        $permission = RolePermission::query()->where('name', '=', $permissionName)->firstOrFail();

        $roles = $user->roles()->whereHas('permissions', function ($query) use ($permission) {
            $query->where('id', '=', $permission->id);
        })->get();

        /** @var Role $role */
        foreach ($roles as $role) {
            $role->detachPermission($permission);
            $permissionBuilder->rebuildForRole($role);
        }

        $user->clearPermissionCache();
    }

    /**
     * Create a new basic role for testing purposes.
     */
    protected function createNewRole(array $permissions = []): Role
    {
        $permissionRepo = app(PermissionsRepo::class);
        $roleData = Role::factory()->make()->toArray();
        $roleData['permissions'] = array_flip($permissions);

        return $permissionRepo->saveNewRole($roleData);
    }

    /**
     * Mock the HttpFetcher service and return the given data on fetch.
     */
    protected function mockHttpFetch($returnData, int $times = 1)
    {
        $mockHttp = Mockery::mock(HttpFetcher::class);
        $this->app[HttpFetcher::class] = $mockHttp;
        $mockHttp->shouldReceive('fetch')
            ->times($times)
            ->andReturn($returnData);
    }

    /**
     * Mock the http client used in BookStack.
     * Returns a reference to the container which holds all history of http transactions.
     *
     * @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
     */
    protected function &mockHttpClient(array $responses = []): array
    {
        $container = [];
        $history = Middleware::history($container);
        $mock = new MockHandler($responses);
        $handlerStack = new HandlerStack($mock);
        $handlerStack->push($history);
        $this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);

        return $container;
    }

    /**
     * Run a set test with the given env variable.
     * Remembers the original and resets the value after test.
     * Database config is juggled so the value can be restored when
     * parallel testing are used, where multiple databases exist.
     */
    protected function runWithEnv(string $name, $value, callable $callback)
    {
        Env::disablePutenv();
        $originalVal = $_SERVER[$name] ?? null;

        if (is_null($value)) {
            unset($_SERVER[$name]);
        } else {
            $_SERVER[$name] = $value;
        }

        $database = config('database.connections.mysql_testing.database');
        $this->refreshApplication();

        DB::purge();
        config()->set('database.connections.mysql_testing.database', $database);

        $callback();

        if (is_null($originalVal)) {
            unset($_SERVER[$name]);
        } else {
            $_SERVER[$name] = $originalVal;
        }
    }

    /**
     * Check the keys and properties in the given map to include
     * exist, albeit not exclusively, within the map to check.
     */
    protected function assertArrayMapIncludes(array $mapToInclude, array $mapToCheck, string $message = ''): void
    {
        $passed = true;

        foreach ($mapToInclude as $key => $value) {
            if (!isset($mapToCheck[$key]) || $mapToCheck[$key] !== $mapToInclude[$key]) {
                $passed = false;
            }
        }

        $toIncludeStr = print_r($mapToInclude, true);
        $toCheckStr = print_r($mapToCheck, true);
        self::assertThat($passed, self::isTrue(), "Failed asserting that given map:\n\n{$toCheckStr}\n\nincludes:\n\n{$toIncludeStr}");
    }

    /**
     * Assert a permission error has occurred.
     */
    protected function assertPermissionError($response)
    {
        PHPUnit::assertTrue($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response contains a permission error.');
    }

    /**
     * Assert a permission error has occurred.
     */
    protected function assertNotPermissionError($response)
    {
        PHPUnit::assertFalse($this->isPermissionError($response->baseResponse ?? $response->response), 'Failed asserting the response does not contain a permission error.');
    }

    /**
     * Check if the given response is a permission error.
     */
    private function isPermissionError($response): bool
    {
        return $response->status() === 302
            && (
                (
                    $response->headers->get('Location') === url('/')
                    && strpos(session()->pull('error', ''), 'You do not have permission to access') === 0
                )
                ||
                (
                    $response instanceof JsonResponse &&
                    $response->json(['error' => 'You do not have permission to perform the requested action.'])
                )
            );
    }

    /**
     * Assert that the session has a particular error notification message set.
     */
    protected function assertSessionError(string $message)
    {
        $error = session()->get('error');
        PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
    }

    /**
     * Assert the session contains a specific entry.
     */
    protected function assertSessionHas(string $key): self
    {
        $this->assertTrue(session()->has($key), "Session does not contain a [{$key}] entry");

        return $this;
    }

    protected function assertNotificationContains(\Illuminate\Testing\TestResponse $resp, string $text)
    {
        return $this->withHtml($resp)->assertElementContains('.notification[role="alert"]', $text);
    }

    /**
     * Set a test handler as the logging interface for the application.
     * Allows capture of logs for checking against during tests.
     */
    protected function withTestLogger(): TestHandler
    {
        $monolog = new Logger('testing');
        $testHandler = new TestHandler();
        $monolog->pushHandler($testHandler);

        Log::extend('testing', function () use ($monolog) {
            return $monolog;
        });
        Log::setDefaultDriver('testing');

        return $testHandler;
    }

    /**
     * Assert that an activity entry exists of the given key.
     * Checks the activity belongs to the given entity if provided.
     */
    protected function assertActivityExists(string $type, ?Entity $entity = null, string $detail = '')
    {
        $detailsToCheck = ['type' => $type];

        if ($entity) {
            $detailsToCheck['entity_type'] = $entity->getMorphClass();
            $detailsToCheck['entity_id'] = $entity->id;
        }

        if ($detail) {
            $detailsToCheck['detail'] = $detail;
        }

        $this->assertDatabaseHas('activities', $detailsToCheck);
    }
}


text:
/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 *   RemoteResult.java
 *   Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.gui.boundaryvisualizer;

import java.io.Serializable;

/**
 * Class that encapsulates a result (and progress info) for part
 * of a distributed boundary visualization. The result of a sub-task
 * is the probabilities necessary to display one row of the final
 * visualization.
 *
 * @author Mark Hall
 * @version $Revision: 8034 $
 * @since 1.0
 * @see Serializable
 */
public class RemoteResult
  implements Serializable {

  /** for serialization */
  private static final long serialVersionUID = 1873271280044633808L;

  /** the row number that this result corresponds to */
  private int m_rowNumber;

  /** how many pixels in a row */
  private int m_rowLength;

  /** the result - ie. the probability distributions produced by the
   * classifier for this row in the visualization */
  private double [][] m_probabilities;

  /** progress on computing this row */
  private int m_percentCompleted;

  /**
   * Creates a new RemoteResult instance.
   *
   * @param rowNum the row number
   * @param rowLength the number of pixels in the row
   */
  public RemoteResult(int rowNum, int rowLength) {
    m_probabilities = new double[rowLength][0];
  }

  /**
   * Store the classifier's distribution for a particular pixel in the
   * visualization
   *
   * @param index the pixel
   * @param distribution the probability distribution from the classifier
   */
  public void setLocationProbs(int index, double [] distribution) {
    m_probabilities[index] = distribution;
  }

  /**
   * Return the probability distributions  for this row in the visualization
   *
   * @return the probability distributions
   */
  public double [][] getProbabilities() {
    return m_probabilities;
  }

  /**
   * Set the progress for this row so far
   *
   * @param pc a percent completed value
   */
  public void setPercentCompleted(int pc) {
    m_percentCompleted = pc;
  }

  /**
   * Return the progress for this row
   *
   * @return a percent completed value
   */
  public int getPercentCompleted() {
    return m_percentCompleted;
  }
}


text:
using System;

namespace Microsoft.TemplateEngine.Cli
{
    internal class Reporter
    {
        private static readonly Reporter NullReporter = new Reporter(console: null);
        private static object _lock = new object();

        private readonly AnsiConsole _console;

        static Reporter()
        {
            Reset();
        }

        private Reporter(AnsiConsole console)
        {
            _console = console;
        }

        public static Reporter Output { get; private set; }
        public static Reporter Error { get; private set; }
        public static Reporter Verbose { get; private set; }

        /// <summary>
        /// Resets the Reporters to write to the current Console Out/Error.
        /// </summary>
        public static void Reset()
        {
            lock (_lock)
            {
                Output = new Reporter(AnsiConsole.GetOutput());
                Error = new Reporter(AnsiConsole.GetError());
                Verbose = IsVerbose ?
                    new Reporter(AnsiConsole.GetOutput()) :
                    NullReporter;
            }
        }

        public void WriteLine(string message)
        {
            lock (_lock)
            {
                if (ShouldPassAnsiCodesThrough)
                {
                    _console?.Writer?.WriteLine(message);
                }
                else
                {
                    _console?.WriteLine(message);
                }
            }
        }

        public void WriteLine()
        {
            lock (_lock)
            {
                _console?.Writer?.WriteLine();
            }
        }

        public void Write(string message)
        {
            lock (_lock)
            {
                if (ShouldPassAnsiCodesThrough)
                {
                    _console?.Writer?.Write(message);
                }
                else
                {
                    _console?.Write(message);
                }
            }
        }

        private static bool IsVerbose
        {
            get { return bool.TryParse(Environment.GetEnvironmentVariable("DOTNET_CLI_CONTEXT_VERBOSE") ?? "false", out bool value) && value; }
        }

        private bool ShouldPassAnsiCodesThrough
        {
            get { return bool.TryParse(Environment.GetEnvironmentVariable("DOTNET_CLI_CONTEXT_ANSI_PASS_THRU") ?? "false", out bool value) && value; }
        }
    }
}


text:
import React from "react";

export default function NotFoundPage() {
  return (

NOT FOUND

You just hit a route that doesn't exist... the sadness.

  );
}


text:
# OCP

## Definition

Objects or entities should be open for extension, but closed for modification.

## Violation Example

Back to our example of the `AreaCalculator` class.

```

 ,----------------------------------.
 |AreaCalculator                    |
 |----------------------------------|
 |+AreaCalculator(shapes : object[])|
 |+Sum() : double                   |
 `----------------------------------'
         |                 |
         v                 v
,----------------.  ,----------------.
|Circle          |  |Square          |
|----------------|  |----------------|
|+Radius : double|  |+Length : double|
`----------------'  `----------------'

```

Now we add a third shape "equilateral triangle" to our structure. Because of this
new shape we need to add another class `EquilateralTrinale` AND make some changes
in the `Sum()` method of the class `AreaCalculator`.

```

 ,----------------------------------.
 |AreaCalculator                    |
 |----------------------------------|
 |+AreaCalculator(shapes : object[])|
 |+Sum() : double                   |----------.
 `----------------------------------'           `
         |                 |                    |
         v                 v                    v
,----------------.  ,----------------.  ,--------------------.
|Circle          |  |Square          |  |EquilateralTriangle |
|----------------|  |----------------|  |--------------------|
|+Radius : double|  |+Length : double|  |+Length : double    |
`----------------'  `----------------'  `--------------------'

```

Is there a better way to solve this issue?

## Possible Solution

Another issue we did not mentioned is that the class `AreaCalculator` accepts
any objects! In order for the `AreaCalculator` to be more stable we can
introduce a marker interface `IShape` which allows us to restric the range of
possible parameter values and prevent other issues.

```

 ,----------------------------------.                         ,-----------------.
 |AreaCalculator                    |------------------------>| << interface >> |
 |----------------------------------|                         | IShape          |
 |+AreaCalculator(shapes : IShape[])|                         `-----------------'
 |+Sum() : double                   |------------.                     A
 `----------------------------------'             `                    |
         |                  |                     |                    |
         |                  |                     |                    |
         v                  v                     v                    |
,----------------.  ,----------------.  ,--------------------.         |
|Circle          |  |Square          |  |EquilateralTriangle |         |
|----------------|  |----------------|  |--------------------|         |
|+Radius : double|  |+Length : double|  |+Length : double    |         |
`----------------'  `----------------'  `--------------------'         |
         |                  |                     |                    |
          `-----------------------------------------------------------´

```

But this approach does not yet solve the issue that we have to make changes
to the `AreaCalculator` for new shapes. As a possible solution we can further
extend the `IShape` interface with a specific `GetArea()` method and move the
logic of calculating the different shape areas into the specific shape classes.
The class `AreaCalculator` will then only be in charge of summing up all the
individual shape areas.

```

 ,----------------------------------.                          ,-------------------.
 |AreaCalculator                    |------------------------->| << interface >>   |
 |----------------------------------|                          | IShape            |
 |+AreaCalculator(shapes : IShape[])|                          |-------------------|
 |+Sum() : double                   |                          |+GetArea() : double|
 `----------------------------------'                          `-------------------'
                                                                       A
                                                                       |
         -------------------------------------------------------------´
         |                  |                     |
,----------------.  ,----------------.  ,--------------------.
|Circle          |  |Square          |  |EquilateralTriangle |
|----------------|  |----------------|  |--------------------|
|-radius : double|  |-length : double|  |-length : double    |
`----------------'  `----------------'  `--------------------'

```

With this appreach we do not need to touch the `AreaCalculator` class anymore
if we add additional shapes. Further the `AreaCalculator` even does not need to
depend on any concrete implementations of the `IShape` interface. We can even hide the
properties of the shape classes because there are not needed by the
`AreaCalculator` class anymore and further loosen some dependencies.