text:
local setmetatable = setmetatable

local GetLocale = GetLocale

local L = {}

if (GetLocale() == "ruRU") then
    -- Races
    L["Human"] = "Человек"
    L["Dwarf"] = "Дворф"
    L["Night Elf"] = "Ночной эльф"
    L["Gnome"] = "Гном"
    L["Draenei"] = "Дреней"
    L["Orc"] = "Орк"
    L["Undead"] = "Нежить"
    L["Tauren"] = "Таурен"
    L["Troll"] = "Тролль"
    L["Blood Elf"] = "Эльф крови"

    -- Classes
    L["Druid"] = "Друид"
    L["Hunter"] = "Охотник"
    L["Mage"] = "Маг"
    L["Paladin"] = "Паладин"
    L["Priest"] = "Жрец"
    L["Rogue"] = "Разбойник"
    L["Shaman"] = "Шаман"
    L["Warlock"] = "Чернокнижник"
    L["Warrior"] = "Воин"

    -- Specs
    L["Balance"] = "Баланс"
    L["Feral"] = "Сила зверя"
    L["Restoration"] = "Исцеление"
    L["Beast Mastery"] = "Повелитель зверей"
    L["Marksmanship"] = "Стрельба"
    L["Survival"] = "Выживание"
    L["Arcane"] = "Тайная магия"
    L["Fire"] = "Огонь"
    L["Frost"] = "Лед"
    L["Holy"] = "Свет"
    L["Protection"] = "Защита"
    L["Retribution"] = "Возмездие"
    L["Discipline"] = "Послушание"
    L["Shadow"] = "Тьма"
    L["Assassination"] = "Ликвидация"
    L["Combat"] = "Бой"
    L["Subtlety"] = "Скрытность"
    L["Elemental"] = "Cтихии"
    L["Enhancement"] = "Совершенствование"
    L["Affliction"] = "Колдовство"
    L["Demonology"] = "Демонология"
    L["Destruction"] = "Разрушение"
    L["Arms"] = "Оружие"
    L["Fury"] = "Неистовство"

    -- Gladdy.lua
    L["Welcome to Gladdy!"] = "Вас приветствует Gladdy!"
    L["First run has been detected, displaying test frame."] = "Обнаружен первый запуск, показываем тестовое окно."
    L["Valid slash commands are:"] = "Валидные команды:"
    L["If this is not your first run please lock or move the frame to prevent this from happening."] = "Если это не первый запуск, переместите, либо закрепите окно во избежание показа окна."

    -- Frame.lua
    L["Gladdy - drag to move"] = "Gladdy - тащите для перемещения"

    -- Options.lua
    L["Announcements"] = "Оповещения"
    L["Announcement settings"] = "Настройки оповещения"
    L["Auras"] = "Ауры"
    L["Auras settings"] = "Настройки аур"
    L["Castbar"] = "Полоса применения"
    L["Castbar settings"] = "Настройки полосы применения"
    L["Classicon"] = "Иконка класса"
    L["Classicon settings"] = "Настройки иконки класса"
    L["Clicks"] = "Клики"
    L["Clicks settings"] = "Настройки кликов"
    L["Diminishings"] = "Диминишинги"
    L["Diminishings settings"] = "Настройки диминишингов"
    L["Healthbar"] = "Полоса жизней"
    L["Healthbar settings"] = "Настройки полосы жизней"
    L["Highlight"] = "Подсветка"
    L["Highlight settings"] = "Настройки подсветки"
    L["Nameplates"] = "Индикаторы здоровья"
    L["Nameplates settings"] = "Настройки индикаторов здоровья "
    L["Powerbar"] = "Полоса маны"
    L["Powerbar settings"] = "Настройки полосы маны"
    L["Score"] = "Счет"
    L["Score settings"] = "Настройки счета"
    L["Trinket"] = "Тринкет"
    L["Trinket settings"] = "Настройки тринкета"
    L["Reset module"] = "Сбросить настройки"
    L["Reset module to defaults"] = "Сбросить настройки модуля к начальным"
    L["No settings"] = "Нет настроек"
    L["Module has no settings"] = "Модуль не имеет настроек"
    L["General"] = "Основные"
    L["General settings"] = "Основные настройки"
    L["Lock frame"] = "Закрепить фрейм"
    L["Toggle if frame can be moved"] = "Включите, если фрейм можно двигать"
    L["Grow frame upwards"] = "Расти вверх"
    L["If enabled the frame will grow upwards instead of downwards"] = "Если включено, то фрейм будет расти вверх, а не вниз"
    L["Frame scale"] = "Масштаб фрейма"
    L["Scale of the frame"] = "Масштаб фрейма"
    L["Frame padding"] = "Отступы фрейма"
    L["Padding of the frame"] = "Отступы фрейма"
    L["Frame color"] = "Цвет фрейма"
    L["Color of the frame"] = "Цвет фрейма"
    L["Bar width"] = "Ширина полос"
    L["Width of the bars"] = "Ширина полос"
    L["Bottom margin"] = "Нижняя граница полосы"
    L["Margin between each button"] = "Отступ до следующей полосы"

    -- Announcements.lua
    L["RESURRECTING: %s (%s)"] = "ВОСКРЕШАЕТ: %s (%s)"
    L["SPEC DETECTED: %s - %s (%s)"] = "СПЕЦИАЛИЗАЦИЯ ОПРЕДЕЛЕНА: %s - %s (%s)"
    L["LOW HEALTH: %s (%s)"] = "МАЛО ЗДОРОВЬЯ: %s (%s)"
    L["TRINKET USED: %s (%s)"] = "ТРИНКЕТ ИСПОЛЬЗОВАН: %s (%s)"
    L["TRINKET READY: %s (%s)"] = "ТРИНКЕТ ГОТОВ: %s (%s)"
    L["DRINKING: %s (%s)"] = "ПЬЁТ: %s (%s)"
    L["Self"] = "Сам"
    L["Party"] = "Группа"
    L["Raid Warning"] = "Объявление рейду"
    L["Blizzard's Floating Combat Text"] = "Стандартный текст боя"
    L["MikScrollingBattleText"] = "MikScrollingBattleText"
    L["Scrolling Combat Text"] = "Scrolling Combat Text"
    L["Parrot"] = "Parrot"
    L["Drinking"] = "Питьё"
    L["Announces when enemies sit down to drink"] = "Оповещать, когда вражеский игрок начинает пить"
    L["Resurrection"] = "Воскрешение"
    L["Announces when an enemy tries to resurrect a teammate"] = "Оповещать, когда вражеский игрок начинает воскрешать союзника"
    L["New enemies"] = "Новые враги"
    L["Announces when new enemies are discovered"] = "Оповещать о найденных вражеских игроках"
    L["Spec Detection"] = "Обнаружение специализации"
    L["Announces when the spec of an enemy was detected"] = "Оповещать, когда обнаружена специализация вражеского игрока"
    L["Low health"] = "Мало жизней"
    L["Announces when an enemy drops below a certain health threshold"] = "Оповещать, когда уровень здоровья вражеского игрока падает ниже определенного количества"
    L["Low health threshold"] = "Процент малого количества здоровья"
    L["Choose how low an enemy must be before low health is announced"] = "Укажите процент здоровья вражеского игрока, когда нужно показать оповещение"
    L["Trinket used"] = "Использование пвп-тринкета"
    L["Announce when an enemy's trinket is used"] = "Оповещать об использовании пвп-тринкета вражеским игроком"
    L["Trinket ready"] = "Готовность пвп-тринкета"
    L["Announce when an enemy's trinket is ready again"] = "Оповещать, когда пвп-тринкет вражеского игрока готов"
    L["Destination"] = "Вариант оповещений"
    L["Choose how your announcements are displayed"] = "Выберать, как показывать оповещения"

    -- Auras.lua
    L["Font color"] = "Цвет текста"
    L["Color of the text"] = "Цвет текста"
    L["Font size"] = "Размер текста"
    L["Size of the text"] = "Размер текста"

    -- Castbar.lua
    L["Bar height"] = "Высота полосы"
    L["Height of the bar"] = "Высота полосы"
    L["Bar texture"] = "Текстура полосы"
    L["Texture of the bar"] = "Текстура полосы"
    L["Bar color"] = "Цвет полосы"
    L["Color of the cast bar"] = "Цвет полосы применений"
    L["Background color"] = "Цвет фона полосы"
    L["Color of the cast bar background"] = "Цвет фона полосы применений"

    -- Clicks.lua
    L["Action #%d"] = "Действие #%d"
    L["Left Click Enemy 1"] = "Левый клик по цели 1"
    L["Left Click Enemy 2"] = "Левый клик по цели 2"
    L["Left Click Enemy 3"] = "Левый клик по цели 3"
    L["Left Click Enemy 4"] = "Левый клик по цели 4"
    L["Left Click Enemy 5"] = "Левый клик по цели 5"
    L["Right Click Enemy 1"] = "Правый клик по цели 1"
    L["Right Click Enemy 2"] = "Правый клик по цели 2"
    L["Right Click Enemy 3"] = "Правый клик по цели 3"
    L["Right Click Enemy 4"] = "Правый клик по цели 4"
    L["Right Click Enemy 5"] = "Правый клик по цели 5"
    L["Trinket Used Enemy 1"] = "Использование пвп-тринкета целью 1"
    L["Trinket Used Enemy 2"] = "Использование пвп-тринкета целью 2"
    L["Trinket Used Enemy 3"] = "Использование пвп-тринкета целью 3"
    L["Trinket Used Enemy 4"] = "Использование пвп-тринкета целью 4"
    L["Trinket Used Enemy 5"] = "Использование пвп-тринкета целью 5"
    L["Left button"] = "Левая кнопка"
    L["Right button"] = "Правая кнопка"
    L["Middle button"] = "Средняя кнопка"
    L["Button 4"] = "Кнопка 4"
    L["Button 5"] = "Кнопка 5"
    L["None"] = "Не назначено"
    L["CTRL"] = "CTRL"
    L["SHIFT"] = "SHIFT"
    L["ALT"] = "ALT"
    L["Cast Spell"] = "Применить заклинание"
    L["Name"] = "Название"
    L["Select the name of the click option"] = "Выбрать название опции клика"
    L["Button"] = "Кнопка"
    L["Select which mouse button to use"] = "Выбрать кнопку мыши для использования"
    L["Modifier"] = "Модификатор"
    L["Select which modifier to use"] = "Выбрать модификатор для использования"
    L["Action"] = "Действите"
    L["Select what action this mouse button does"] = "Выбрать действие, производимое данной кнопкой мыши"
    L["Spell name / Macro text"] = "Название заклинания / Текст макроса"
    L["Use *name* as unit's name. Like a '/rofl *name*'"] = "Используйте *name* в качестве имени игрока. Например, '/rofl *name*'"

    -- Diminishings.lua
    L["DR Cooldown position"] = "Позиция ДР таймеров"
    L["Position of the cooldown icons"] = "Позиция ДР таймеров"
    L["Left"] = "Слева"
    L["Right"] = "Справа"
    L["Icon Size"] = "Размер иконок"
    L["Size of the DR Icons"] = "Размер ДР иконок"

    -- Healthbar.lua
    L["Show the actual health"] = "Показывать текущее здоровье"
    L["Show the actual health on the health bar"] = "Показывать текущее здоровье на полосе жизней"
    L["Show max health"] = "Показывать максимальное здоровье"
    L["Show max health on the health bar"] = "Показывать максимальное здоровье на полосе жизней"
    L["Show health percentage"] = "Показывать здоровье в процентах"
    L["Show health percentage on the health bar"] = "Показывать здоровье в процентах на полосе жизней"

    -- Highlight.lua
    L["Target border color"] = "Цвет контура цели"
    L["Color of the selected targets border"] = "Цвет контура цели"
    L["Focus border color"] = "Цвет контура фокуса"
    L["Color of the focus border"] = "Цвет контура фокуса"
    L["Raid leader border color"] = "Цвет контура цели рейд лидера"
    L["Color of the raid leader border"] = "Цвет контура цели рейд лидера"
    L["Highlight target"] = "Подсвечивать цель"
    L["Toggle if the selected target should be highlighted"] = "Включите, если необходима подсветка цели"
    L["Show border around target"] = "Показывать контур вокруг цели"
    L["Toggle if a border should be shown around the selected target"] = "Включите, если необходимо показывать контур вокруг цели"
    L["Show border around focus"] = "Показывать контур вокруг фокуса"
    L["Toggle of a border should be shown around the current focus"] = "Включите, если необходимо показывать контур вокруг фокуса"
    L["Show border around raid leader"] = "Показывать контур вокруг цели рейд лидера"
    L["Toggle if a border should be shown around the raid leader"] = "Включите, если необходимо показывать контур вокруг цели рейд лидера"

    -- Powerbar.lua
    L["Show the actual power"] = "Показывать текущую ману"
    L["Show the actual power on the power bar"] = "Показывать текущую ману на полосе маны"
    L["Show max power"] = "Показывать максимальную ману"
    L["Show max power on the power bar"] = "Показывать максимальную ману на полосе маны"
    L["Show power percentage"] = "Показывать ману в процентах"
    L["Show power percentage on the power bar"] = "Показывать ману в процентах на полосе маны"

    -- Trinket.lua
    L["No cooldown count (OmniCC)"] = "Не показывать кулдаун (OmniCC)"
    L["Disable cooldown timers by addons (reload UI to take effect)"] = "Отключить таймер кулдаунов для аддонов (необходима перезагрузка интерфейса)"
elseif (GetLocale() == "deDE") then
    -- Races
    L["Human"] = "Mensch"
    L["Dwarf"] = "Zwerg"
    L["Night Elf"] = "Nachtelf"
    L["Gnome"] = "Gnom"
    L["Draenei"] = "Draenei"
    L["Orc"] = "Ork"
    L["Undead"] = "Untoter"
    L["Tauren"] = "Taure"
    L["Troll"] = "Тroll"
    L["Blood Elf"] = "Blutelf"

    -- Classes
    L["Druid"] = "Druide"
    L["Hunter"] = "Jäger"
    L["Mage"] = "Magier"
    L["Paladin"] = "Paladin"
    L["Priest"] = "Priester"
    L["Rogue"] = "Schurke"
    L["Shaman"] = "Schamane"
    L["Warlock"] = "Hexenmeister"
    L["Warrior"] = "Krieger"

    -- Specs
    L["Balance"] = "Gleichgewicht"
    L["Feral"] = "Wilder Kampf"
    L["Restoration"] = "Wiederherstellung"
    L["Beast Mastery"] = "Tierherrschaft"
    L["Marksmanship"] = "Treffsicherheit"
    L["Survival"] = "Überleben"
    L["Arcane"] = "Arkan"
    L["Fire"] = "Feuer"
    L["Frost"] = "Frost"
    L["Holy"] = "Heilig"
    L["Protection"] = "Schutz"
    L["Retribution"] = "Vergeltung"
    L["Discipline"] = "Disziplin"
    L["Shadow"] = "Schatten"
    L["Assassination"] = "Meucheln"
    L["Combat"] = "Kampf"
    L["Subtlety"] = "Täuschung"
    L["Elemental"] = "Elemental"
    L["Enhancement"] = "Verstärkung"
    L["Affliction"] = "Gebrechen"
    L["Demonology"] = "Demonologie"
    L["Destruction"] = "Zerstörung"
    L["Arms"] = "Waffen"
    L["Fury"] = "Furor"

    -- Gladdy.lua
    L["Welcome to Gladdy!"] = "Willkommen bei Gladdy!"
    L["First run has been detected, displaying test frame."] = "Erster Start wurde entdeckt, zeige Testbild an."
    L["Valid slash commands are:"] = "Gültige slash Befehle sind:"
    L["If this is not your first run please lock or move the frame to prevent this from happening."] = "Wenn dies nicht dein erster Start ist, sperre oder bewege das Bild um diese Meldung zu verhindern."

    -- Frame.lua
    L["Gladdy - drag to move"] = "Gladdy - ziehe um zu bewegen"

    -- Options.lua
    L["Announcements"] = "Meldungen"
    L["Announcement settings"] = "Meldungseinstellungen"
    L["Auras"] = "Auren"
    L["Auras settings"] = "Aureneinstellungen"
    L["Castbar"] = "Zauberleiste"
    L["Castbar settings"] = "Zauberleisteneinstellungen"
    L["Classicon"] = "Klassensymbol"
    L["Classicon settings"] = "Klassensymboleinstellungen"
    L["Clicks"] = "Klicks"
    L["Clicks settings"] = "Klickeinstellungen"
    L["Diminishings"] = "DR"
    L["Diminishings settings"] = "DR Einstellungen"
    L["Healthbar"] = "Lebensleiste"
    L["Healthbar settings"] = "Lebensleisteneinstellungen"
    L["Highlight"] = "warnung"
    L["Highlight settings"] = "Warnungseinstellungen"
    L["Nameplates"] = "Namensplaketten"
    L["Nameplates settings"] = "Namensplaketteneinstellungen"
    L["Powerbar"] = "Powerleiste"
    L["Powerbar settings"] = "Powerleisteneinstellungen"
    L["Score"] = "Score"
    L["Score settings"] = "Scoreeinstellungen"
    L["Trinket"] = "Insignie"
    L["Trinket settings"] = "Insignieneinstellungen"
    L["Reset module"] = "Model zurücksetzen"
    L["Reset module to defaults"] = "Modul auf Standardeinstellungen zurücksetzen"
    L["No settings"] = "Keine Einstellungen"
    L["Module has no settings"] = "Modul hat keine Einstellungen"
    L["General"] = "ОAllgemein"
    L["General settings"] = "Allgemeine Einstellungen"
    L["Lock frame"] = "Sperre Bild"
    L["Toggle if frame can be moved"] = "Aktivieren falls das Bild bewegt werden kann"
    L["Grow frame upwards"] = "Bild von unten nach oben aufbauen"
    L["If enabled the frame will grow upwards instead of downwards"] = "Falls aktiviert, wird das Bild von unten nach oben aufgebaut"
    L["Frame scale"] = "Bildskalierung"
    L["Scale of the frame"] = "Skalierung des Bildes"
    L["Frame padding"] = "Bild Unterlage"
    L["Padding of the frame"] = "Unterlage des Bildes"
    L["Frame color"] = "Bildfarbe"
    L["Color of the frame"] = "Farbe des Bildes"
    L["Bar width"] = "Leistenbreite"
    L["Width of the bars"] = "Breite der Leisten"
    L["Bottom margin"] = "Unterer Abstand"
    L["Margin between each button"] = "Abstand zwischen jedem Buttom"

    -- Announcements.lua
    L["RESURRECTING: %s (%s)"] = "Wiederbeleben: %s (%s) "
    L["SPEC DETECTED: %s - %s (%s)"] = "Talenspezalisierung entdeckt: %s - %s (%s)"
    L["LOW HEALTH: %s (%s)"] = "Niedriges Leben: %s (%s)"
    L["TRINKET USED: %s (%s)"] = "Insiginie benutzt: %s (%s)"
    L["TRINKET READY: %s (%s)"] = "Insignie bereit: %s (%s)"
    L["DRINKING: %s (%s)"] = "Trinken: %s (%s)"
    L["Self"] = "Selbst"
    L["Party"] = "Gruppe"
    L["Raid Warning"] = "Schlachtzugwarnung"
    L["Blizzard's Floating Combat Text"] = "Blizzard Kampftext"
    L["MikScrollingBattleText"] = "MikScrollingBattleText"
    L["Scrolling Combat Text"] = "Scrolling Combat Text"
    L["Parrot"] = "Parrot"
    L["Drinking"] = "Trinken"
    L["Announces when enemies sit down to drink"] = "Warnt wenn Gegner sich zum Trinken hinsetzen"
    L["Resurrection"] = "Wiederbelebung"
    L["Announces when an enemy tries to resurrect a teammate"] = "Warnt wenn Gegner versuchen Teammitglieder wiederzubeleben"
    L["New enemies"] = "Neue Gegner"
    L["Announces when new enemies are discovered"] = "Gibt an, wenn neue Gegner entdeckt wurden"
    L["Spec Detection"] = "Talent Entdeckung"
    L["Announces when the spec of an enemy was detected"] = "Gibt an, wenn Talente eines Gegners entdeckt wurden"
    L["Low health"] = "Wenig Leben"
    L["Announces when an enemy drops below a certain health threshold"] = "Warnt, wenn das Leben eines Gegners unter einen bestimmten Prozentwert fällt"
    L["Low health threshold"] = "Prozentwert: Wenig Leben"
    L["Choose how low an enemy must be before low health is announced"] = "Bestimme wie wenig Leben ein Gegner haben muss, damit vor wenig Leben gewarnt wird"
    L["Trinket used"] = "Insignie benutzt"
    L["Announce when an enemy's trinket is used"] = "Warnt, wenn ein Gegner seine Insignie benutzt"
    L["Trinket ready"] = "Insignie bereit"
    L["Announce when an enemy's trinket is ready again"] = "Warnt wenn die Insignie eines Gegner wieder bereit ist"
    L["Destination"] = "Ziel"
    L["Choose how your announcements are displayed"] = "Bestimme wo Warnungen dargestellt werden"

    -- Auras.lua
    L["Font color"] = "Schriftfarbe"
    L["Color of the text"] = "Farbe der Schrift"
    L["Font size"] = "Schriftgröße"
    L["Size of the text"] = "Größe der Schrift"

    -- Castbar.lua
    L["Bar height"] = "Leistenhöhe"
    L["Height of the bar"] = "Höhe der Leiste"
    L["Bar texture"] = "Leistentextur"
    L["Texture of the bar"] = "Textur der Leiste"
    L["Bar color"] = "Leistenfarbe"
    L["Color of the cast bar"] = "Farbe der Zauberleiste"
    L["Background color"] = "Hintergrundfarbe"
    L["Color of the cast bar background"] = "Hintergrundfarbe der Zauberleiste"

    -- Clicks.lua
    L["Action #%d"] = "Aktion #%d"
    L["Left Click Enemy 1"] = "Linksklick Gegner 1"
    L["Left Click Enemy 2"] = "Linksklick Gegner 2"
    L["Left Click Enemy 3"] = "Linksklick Gegner 3"
    L["Left Click Enemy 4"] = "Linksklick Gegner 4"
    L["Left Click Enemy 5"] = "Linksklick Gegner 5"
    L["Right Click Enemy 1"] = "Rechtsklick Gegner 1"
    L["Right Click Enemy 2"] = "Rechtsklick Gegner 2"
    L["Right Click Enemy 3"] = "Rechtsklick Gegner 3"
    L["Right Click Enemy 4"] = "Rechtsklick Gegner 4"
    L["Right Click Enemy 5"] = "Rechtsklick Gegner 5"
    L["Trinket Used Enemy 1"] = "Insiginie Benutzt Gegner 1"
    L["Trinket Used Enemy 2"] = "Insiginie Benutzt Gegner 2"
    L["Trinket Used Enemy 3"] = "Insiginie Benutzt Gegner 3"
    L["Trinket Used Enemy 4"] = "Insiginie Benutzt Gegner 4"
    L["Trinket Used Enemy 5"] = "Insiginie Benutzt Gegner 5"
    L["Left button"] = "Linke Taste"
    L["Right button"] = "Rechte Taste"
    L["Middle button"] = "Mittlere Taste"
    L["Button 4"] = "Maus 4"
    L["Button 5"] = "Maus 5"
    L["None"] = "Keine"
    L["CTRL"] = "STRG"
    L["SHIFT"] = "SHIFT"
    L["ALT"] = "ALT"
    L["Cast Spell"] = "Wirke Zauber"
    L["Name"] = "Name"
    L["Select the name of the click option"] = "Wähle einen Namen für die Klickoption"
    L["Button"] = "Taste"
    L["Select which mouse button to use"] = "Wähle welche Maustaste genutzt werden soll"
    L["Modifier"] = "Modifier"
    L["Select which modifier to use"] = "Wähle welcher Modifier benutzt werdne soll"
    L["Action"] = "Aktion"
    L["Select what action this mouse button does"] = "Wähle welche Aktion die Maustaste durchführt"
    L["Spell name / Macro text"] = "Zaubername / Makrotext"
    L["Use *name* as unit's name. Like a '/rofl *name*'"] = "Benutzt *name* als Gegnername. Zum Beispiel '/rofl *name*'"

    -- Diminishings.lua
    L["DR Cooldown position"] = "Position des DR Cooldowns"
    L["Position of the cooldown icons"] = "Position des DR Cooldowns"
    L["Left"] = "Links"
    L["Right"] = "Rechts"
    L["Icon Size"] = "Symbolgröße"
    L["Size of the DR Icons"] = "Größe des DR Symbols"

    -- Healthbar.lua
    L["Show the actual health"] = "Zeige das Leben an"
    L["Show the actual health on the health bar"] = "Zeige das Leben auf der Lebensanzeige an"
    L["Show max health"] = "Zeige Maximalleben an"
    L["Show max health on the health bar"] = "Zeige Maximalleben auf der Lebensanzeige an"
    L["Show health percentage"] = "Zeige prozentuales Leben"
    L["Show health percentage on the health bar"] = "Zeige prozentuales Leben auf der Lebensanzeige an"

    -- Highlight.lua
    L["Target border color"] = "Zielrahmenfarbe"
    L["Color of the selected targets border"] = "Farbe des Rahmens des gewählten Ziels"
    L["Focus border color"] = "Focusrahmenfarbe"
    L["Color of the focus border"] = "Farbe des Focusrahmens"
    L["Raid leader border color"] = "Schlachtzugleiterrahmenfarbe"
    L["Color of the raid leader border"] = "Farbe des Rahmens für den Schlachtzugleiter"
    L["Highlight target"] = "Highlight Ziel"
    L["Toggle if the selected target should be highlighted"] = "Включите, если необходима подсветка цели"
    L["Show border around target"] = "Zeige Rahmen um das Ziel an"
    L["Toggle if a border should be shown around the selected target"] = "Auswählen wenn ein Ramhen um das ausgewählte Ziel angezeigt werden soll"
    L["Show border around focus"] = "Zeige Rahmen um Focus"
    L["Toggle of a border should be shown around the current focus"] = "Auswählen wenn ein Ramhen um das ausgewählte Focusziel angezeigt werden soll"
    L["Show border around raid leader"] = "Zeige Rahmen um Schlachtzugleiter"
    L["Toggle if a border should be shown around the raid leader"] = "Auswählen wenn ein Ramhen um den ausgewählten SChlachtzugleiter angezeigt werden soll"

    -- Powerbar.lua
    L["Show the actual power"] = "Zeige genaue Power"
    L["Show the actual power on the power bar"] = "Zeige die genaue Power in der Powerleiste "
    L["Show max power"] = "Zeige Maximalpower"
    L["Show max power on the power bar"] = "Zeige Maximalpower in der Powerbau"
    L["Show power percentage"] = "Zeige prozentuale Power"
    L["Show power percentage on the power bar"] = "Zeige prozentuale Power in der Powerbau"

    -- Trinket.lua
    L["No cooldown count (OmniCC)"] = "Keine Cooldownanzeige (OmniCC)"
    L["Disable cooldown timers by addons (reload UI to take effect)"] = "Deaktiviere Cooldownanzeige durch Addons (UI neu laden um zu wirken)"
end

-- Superhack allowing use key as value if not present in table
LibStub("Gladdy").L = setmetatable(L, {
    __index = function(t, k)
        return k
    end
})


text:
module rl.utilities.services.boolean {
	'use strict';

	export var moduleName: string = 'rl.utilities.services.boolean';
	export var serviceName: string = 'booleanUtility';

	export interface IBooleanUtility {
		toBool(object: any): boolean;
	}

	class BooleanUtility implements IBooleanUtility {
		toBool(object: any): boolean {
			return !!object;
		}
	}

	angular.module(moduleName, [])
		.service(serviceName, BooleanUtility);
}

redpajama_set_name: RedPajamaGithub


text:
namespace network {

HttpRawRequestResponseInfo::HttpRawRequestResponseInfo()
    : http_status_code(0) {}

HttpRawRequestResponseInfo::~HttpRawRequestResponseInfo() {}

scoped_refptr<HttpRawRequestResponseInfo> HttpRawRequestResponseInfo::DeepCopy()
    const {
  auto new_info = base::MakeRefCounted<HttpRawRequestResponseInfo>();
  new_info->http_status_code = http_status_code;
  new_info->http_status_text = http_status_text;
  new_info->request_headers = request_headers;
  new_info->response_headers = response_headers;
  new_info->request_headers_text = request_headers_text;
  new_info->response_headers_text = response_headers_text;
  return new_info;
}

}  // namespace network


text:
#include <device.h>
#include <soc.h>
#include <dma.h>

#include <logging/log.h>
LOG_MODULE_REGISTER(dma_sam0, CONFIG_DMA_LOG_LEVEL);

#define DMA_REGS	((Dmac *)DT_ATMEL_SAM0_DMAC_0_BASE_ADDRESS)

typedef void (*dma_callback)(void *callback_arg, u32_t channel,
			     int error_code);

struct dma_sam0_channel {
	dma_callback cb;
	void *cb_arg;
};

struct dma_sam0_data {
	__aligned(16) DmacDescriptor descriptors[DMAC_CH_NUM];
	__aligned(16) DmacDescriptor descriptors_wb[DMAC_CH_NUM];
	struct dma_sam0_channel channels[DMAC_CH_NUM];
};

#define DEV_DATA(dev) \
	((struct dma_sam0_data *const)(dev)->driver_data)

/* Handles DMA interrupts and dispatches to the individual channel */
static void dma_sam0_isr(void *arg)
{
	struct device *dev = arg;
	struct dma_sam0_data *data = DEV_DATA(dev);
	struct dma_sam0_channel *chdata;
	u16_t pend = DMA_REGS->INTPEND.reg;
	u32_t channel;

	/* Acknowledge all interrupts for the channel in pend */
	DMA_REGS->INTPEND.reg = pend;

	channel = (pend & DMAC_INTPEND_ID_Msk) >> DMAC_INTPEND_ID_Pos;
	chdata = &data->channels[channel];

	if (pend & DMAC_INTPEND_TERR) {
		if (chdata->cb) {
			chdata->cb(chdata->cb_arg, channel, -DMAC_INTPEND_TERR);
		}
	} else if (pend & DMAC_INTPEND_TCMPL) {
		if (chdata->cb) {
			chdata->cb(chdata->cb_arg, channel, 0);
		}
	}

	/*
	 * If more than one channel is pending, we'll just immediately
	 * interrupt again and handle it through a different INTPEND value.
	 */
}

/* Configure a channel */
static int dma_sam0_config(struct device *dev, u32_t channel,
			   struct dma_config *config)
{
	struct dma_sam0_data *data = DEV_DATA(dev);
	DmacDescriptor *desc = &data->descriptors[channel];
	struct dma_block_config *block = config->head_block;
	struct dma_sam0_channel *channel_control;
	DMAC_BTCTRL_Type btctrl = { .reg = 0 };
	int key;

	if (channel >= DMAC_CH_NUM) {
		LOG_ERR("Unsupported channel");
		return -EINVAL;
	}

	if (config->block_count > 1) {
		LOG_ERR("Chained transfers not supported");
		/* TODO: add support for chained transfers. */
		return -ENOTSUP;
	}

	if (config->dma_slot >= DMAC_TRIG_NUM) {
		LOG_ERR("Invalid trigger number");
		return -EINVAL;
	}

	/* Lock and page in the channel configuration */
	key = irq_lock();

	/*
	 * The "bigger" DMAC on some SAM0 chips (e.g. SAMD5x) has
	 * independently accessible registers for each channel, while
	 * the other ones require an indirect channel selection before
	 * accessing shared registers.  The simplest way to detect the
	 * difference is the presence of the DMAC_CHID_ID macro from the
	 * ASF HAL (i.e. it's only defined if indirect access is required).
	 */
#ifdef DMAC_CHID_ID
	/* Select the channel for configuration */
	DMA_REGS->CHID.reg = DMAC_CHID_ID(channel);
	DMA_REGS->CHCTRLA.reg = 0;

	/* Connect the peripheral trigger */
	if (config->channel_direction == MEMORY_TO_MEMORY) {
		/*
		 * A single software trigger will start the
		 * transfer
		 */
		DMA_REGS->CHCTRLB.reg = DMAC_CHCTRLB_TRIGACT_TRANSACTION |
				    DMAC_CHCTRLB_TRIGSRC(config->dma_slot);
	} else {
		/* One peripheral trigger per beat */
		DMA_REGS->CHCTRLB.reg = DMAC_CHCTRLB_TRIGACT_BEAT |
				    DMAC_CHCTRLB_TRIGSRC(config->dma_slot);
	}

	/* Set the priority */
	if (config->channel_priority >= DMAC_LVL_NUM) {
		LOG_ERR("Invalid priority");
		goto inval;
	}

	DMA_REGS->CHCTRLB.bit.LVL = config->channel_priority;

	/* Enable the interrupts */
	DMA_REGS->CHINTENSET.reg = DMAC_CHINTENSET_TCMPL;
	if (!config->error_callback_en) {
		DMA_REGS->CHINTENSET.reg = DMAC_CHINTENSET_TERR;
	} else {
		DMA_REGS->CHINTENCLR.reg = DMAC_CHINTENSET_TERR;
	}

	DMA_REGS->CHINTFLAG.reg = DMAC_CHINTFLAG_TERR | DMAC_CHINTFLAG_TCMPL;
#else
	/* Channels have separate configuration registers */
	DmacChannel * chcfg = &DMA_REGS->Channel[channel];

	if (config->channel_direction == MEMORY_TO_MEMORY) {
		/*
		 * A single software trigger will start the
		 * transfer
		 */
		chcfg->CHCTRLA.reg = DMAC_CHCTRLA_TRIGACT_TRANSACTION |
				     DMAC_CHCTRLA_TRIGSRC(config->dma_slot);
	} else {
		/* One peripheral trigger per beat */
		chcfg->CHCTRLA.reg = DMAC_CHCTRLA_TRIGACT_BURST |
				     DMAC_CHCTRLA_TRIGSRC(config->dma_slot);
	}

	/* Set the priority */
	if (config->channel_priority >= DMAC_LVL_NUM) {
		LOG_ERR("Invalid priority");
		goto inval;
	}

	chcfg->CHPRILVL.bit.PRILVL = config->channel_priority;

	/* Set the burst length */
	if (config->source_burst_length != config->dest_burst_length) {
		LOG_ERR("Source and destination burst lengths must be equal");
		goto inval;
	}

	if (config->source_burst_length > 16U) {
		LOG_ERR("Invalid burst length");
		goto inval;
	}

	if (config->source_burst_length > 0U) {
		chcfg->CHCTRLA.reg |= DMAC_CHCTRLA_BURSTLEN(
			config->source_burst_length - 1U);
	}

	/* Enable the interrupts */
	chcfg->CHINTENSET.reg = DMAC_CHINTENSET_TCMPL;
	if (!config->error_callback_en) {
		chcfg->CHINTENSET.reg = DMAC_CHINTENSET_TERR;
	} else {
		chcfg->CHINTENCLR.reg = DMAC_CHINTENSET_TERR;
	}

	chcfg->CHINTFLAG.reg = DMAC_CHINTFLAG_TERR | DMAC_CHINTFLAG_TCMPL;
#endif

	/* Set the beat (single transfer) size */
	if (config->source_data_size != config->dest_data_size) {
		LOG_ERR("Source and destination data sizes must be equal");
		goto inval;
	}

	switch (config->source_data_size) {
	case 1:
		btctrl.bit.BEATSIZE = DMAC_BTCTRL_BEATSIZE_BYTE_Val;
		break;
	case 2:
		btctrl.bit.BEATSIZE = DMAC_BTCTRL_BEATSIZE_HWORD_Val;
		break;
	case 4:
		btctrl.bit.BEATSIZE = DMAC_BTCTRL_BEATSIZE_WORD_Val;
		break;
	default:
		LOG_ERR("Invalid data size");
		goto inval;
	}

	/* Set up the one and only block */
	desc->BTCNT.reg = block->block_size / config->source_data_size;
	desc->DESCADDR.reg = 0;

	/* Set the automatic source / dest increment */
	switch (block->source_addr_adj) {
	case DMA_ADDR_ADJ_INCREMENT:
		desc->SRCADDR.reg = block->source_address + block->block_size;
		btctrl.bit.SRCINC = 1;
		break;
	case DMA_ADDR_ADJ_NO_CHANGE:
		desc->SRCADDR.reg = block->source_address;
		break;
	default:
		LOG_ERR("Invalid source increment");
		goto inval;
	}

	switch (block->dest_addr_adj) {
	case DMA_ADDR_ADJ_INCREMENT:
		desc->DSTADDR.reg = block->dest_address + block->block_size;
		btctrl.bit.DSTINC = 1;
		break;
	case DMA_ADDR_ADJ_NO_CHANGE:
		desc->DSTADDR.reg = block->dest_address;
		break;
	default:
		LOG_ERR("Invalid destination increment");
		goto inval;
	}

	btctrl.bit.VALID = 1;
	desc->BTCTRL = btctrl;

	channel_control = &data->channels[channel];
	channel_control->cb = config->dma_callback;
	channel_control->cb_arg = config->callback_arg;

	LOG_DBG("Configured channel %d for %08X to %08X (%u)",
		channel,
		block->source_address,
		block->dest_address,
		block->block_size);

	irq_unlock(key);
	return 0;

inval:
	irq_unlock(key);
	return -EINVAL;
}

static int dma_sam0_start(struct device *dev, u32_t channel)
{
	int key = irq_lock();

	ARG_UNUSED(dev);

#ifdef DMAC_CHID_ID
	DMA_REGS->CHID.reg = channel;
	DMA_REGS->CHCTRLA.reg = DMAC_CHCTRLA_ENABLE;

	if (DMA_REGS->CHCTRLB.bit.TRIGSRC == 0) {
		/* Trigger via software */
		DMA_REGS->SWTRIGCTRL.reg = 1U << channel;
	}

#else
	DmacChannel * chcfg = &DMA_REGS->Channel[channel];

	chcfg->CHCTRLA.bit.ENABLE = 1;

	if (chcfg->CHCTRLA.bit.TRIGSRC == 0) {
		/* Trigger via software */
		DMA_REGS->SWTRIGCTRL.reg = 1U << channel;
	}
#endif

	irq_unlock(key);

	return 0;
}

static int dma_sam0_stop(struct device *dev, u32_t channel)
{
	int key = irq_lock();

	ARG_UNUSED(dev);

#ifdef DMAC_CHID_ID
	DMA_REGS->CHID.reg = channel;
	DMA_REGS->CHCTRLA.reg = 0;
#else
	DmacChannel * chcfg = &DMA_REGS->Channel[channel];

	chcfg->CHCTRLA.bit.ENABLE = 0;
#endif

	irq_unlock(key);

	return 0;
}

static int dma_sam0_reload(struct device *dev, u32_t channel,
			   u32_t src, u32_t dst, size_t size)
{
	struct dma_sam0_data *data = DEV_DATA(dev);
	DmacDescriptor *desc = &data->descriptors[channel];
	int key = irq_lock();

	switch (desc->BTCTRL.bit.BEATSIZE) {
	case DMAC_BTCTRL_BEATSIZE_BYTE_Val:
		desc->BTCNT.reg = size;
		break;
	case DMAC_BTCTRL_BEATSIZE_HWORD_Val:
		desc->BTCNT.reg = size / 2U;
		break;
	case DMAC_BTCTRL_BEATSIZE_WORD_Val:
		desc->BTCNT.reg = size / 4U;
		break;
	default:
		goto inval;
	}

	if (desc->BTCTRL.bit.SRCINC) {
		desc->SRCADDR.reg = src + size;
	} else {
		desc->SRCADDR.reg = src;
	}

	if (desc->BTCTRL.bit.DSTINC) {
		desc->DSTADDR.reg = dst + size;
	} else {
		desc->DSTADDR.reg = dst;
	}

	LOG_DBG("Reloaded channel %d for %08X to %08X (%u)",
		channel, src, dst, size);

	irq_unlock(key);
	return 0;

inval:
	irq_unlock(key);
	return -EINVAL;
}

DEVICE_DECLARE(dma_sam0_0);

#define DMA_SAM0_IRQ_CONNECT(n)						 \
	do {								 \
		IRQ_CONNECT(DT_ATMEL_SAM0_DMAC_0_IRQ_ ## n,		 \
			    DT_ATMEL_SAM0_DMAC_0_IRQ_ ## n ## _PRIORITY, \
			    dma_sam0_isr, DEVICE_GET(dma_sam0_0), 0);	 \
		irq_enable(DT_ATMEL_SAM0_DMAC_0_IRQ_ ## n);		 \
	} while (0)

static int dma_sam0_init(struct device *dev)
{
	struct dma_sam0_data *data = DEV_DATA(dev);

	/* Enable clocks. */
#ifdef MCLK
	MCLK->AHBMASK.bit.DMAC_ = 1;
#else
	PM->AHBMASK.bit.DMAC_ = 1;
	PM->APBBMASK.bit.DMAC_ = 1;
#endif

	/* Set up the descriptor and write back addresses */
	DMA_REGS->BASEADDR.reg = (uintptr_t)&data->descriptors;
	DMA_REGS->WRBADDR.reg = (uintptr_t)&data->descriptors_wb;

	/* Statically map each level to the same numeric priority */
	DMA_REGS->PRICTRL0.reg =
		DMAC_PRICTRL0_LVLPRI0(0) | DMAC_PRICTRL0_LVLPRI1(1) |
		DMAC_PRICTRL0_LVLPRI2(2) | DMAC_PRICTRL0_LVLPRI3(3);

	/* Enable the unit and enable all priorities */
	DMA_REGS->CTRL.reg = DMAC_CTRL_DMAENABLE | DMAC_CTRL_LVLEN(0x0F);

#ifdef DT_ATMEL_SAM0_DMAC_0_IRQ_0
	DMA_SAM0_IRQ_CONNECT(0);
#endif
#ifdef DT_ATMEL_SAM0_DMAC_0_IRQ_1
	DMA_SAM0_IRQ_CONNECT(1);
#endif
#ifdef DT_ATMEL_SAM0_DMAC_0_IRQ_2
	DMA_SAM0_IRQ_CONNECT(2);
#endif
#ifdef DT_ATMEL_SAM0_DMAC_0_IRQ_3
	DMA_SAM0_IRQ_CONNECT(3);
#endif
#ifdef DT_ATMEL_SAM0_DMAC_0_IRQ_4
	DMA_SAM0_IRQ_CONNECT(4);
#endif

	return 0;
}

static struct dma_sam0_data dmac_data;

static const struct dma_driver_api dma_sam0_api = {
	.config = dma_sam0_config,
	.start = dma_sam0_start,
	.stop = dma_sam0_stop,
	.reload = dma_sam0_reload,
};

DEVICE_AND_API_INIT(dma_sam0_0, CONFIG_DMA_0_NAME, &dma_sam0_init,
		    &dmac_data, NULL, POST_KERNEL,
		    CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &dma_sam0_api);


text:
class CreateInMessages < ActiveRecord::Migration
  def change
    create_table :in_messages do |t|
      t.string :type
      t.string :to
      t.string :msisdn
      t.string :network_code
      t.text :message_id
      t.datetime :message_timestamp
      t.text :text
      t.boolean :concat
      t.string :concat_ref
      t.integer :concat_total
      t.integer :concat_part
      t.string :status

      t.timestamps
    end
  end
end


text:
package gc

import (
	"context"
	"errors"
	"fmt"

	bstore "github.com/ipfs/go-ipfs/blocks/blockstore"
	dag "github.com/ipfs/go-ipfs/merkledag"
	pin "github.com/ipfs/go-ipfs/pin"

	cid "gx/ipfs/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ/go-cid"
	node "gx/ipfs/QmPN7cwmpcc4DWXb4KTB9dNAJgjuPY69h3npsMfhRrQL9c/go-ipld-format"
	logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
)

var log = logging.Logger("gc")

// Result represents an incremental output from a garbage collection
// run.  It contains either an error, or the cid of a removed object.
type Result struct {
	KeyRemoved *cid.Cid
	Error      error
}

// GC performs a mark and sweep garbage collection of the blocks in the blockstore
// first, it creates a 'marked' set and adds to it the following:
// - all recursively pinned blocks, plus all of their descendants (recursively)
// - bestEffortRoots, plus all of its descendants (recursively)
// - all directly pinned blocks
// - all blocks utilized internally by the pinner
//
// The routine then iterates over every block in the blockstore and
// deletes any block that is not found in the marked set.
//
func GC(ctx context.Context, bs bstore.GCBlockstore, ls dag.LinkService, pn pin.Pinner, bestEffortRoots []*cid.Cid) <-chan Result {

	elock := log.EventBegin(ctx, "GC.lockWait")
	unlocker := bs.GCLock()
	elock.Done()
	elock = log.EventBegin(ctx, "GC.locked")
	emark := log.EventBegin(ctx, "GC.mark")

	ls = ls.GetOfflineLinkService()

	output := make(chan Result, 128)

	go func() {
		defer close(output)
		defer unlocker.Unlock()
		defer elock.Done()

		gcs, err := ColoredSet(ctx, pn, ls, bestEffortRoots, output)
		if err != nil {
			output <- Result{Error: err}
			return
		}
		emark.Append(logging.LoggableMap{
			"blackSetSize": fmt.Sprintf("%d", gcs.Len()),
		})
		emark.Done()
		esweep := log.EventBegin(ctx, "GC.sweep")

		keychan, err := bs.AllKeysChan(ctx)
		if err != nil {
			output <- Result{Error: err}
			return
		}

		errors := false
		var removed uint64

	loop:
		for {
			select {
			case k, ok := <-keychan:
				if !ok {
					break loop
				}
				if !gcs.Has(k) {
					err := bs.DeleteBlock(k)
					removed++
					if err != nil {
						errors = true
						output <- Result{Error: &CannotDeleteBlockError{k, err}}
						//log.Errorf("Error removing key from blockstore: %s", err)
						// continue as error is non-fatal
						continue loop
					}
					select {
					case output <- Result{KeyRemoved: k}:
					case <-ctx.Done():
						break loop
					}
				}
			case <-ctx.Done():
				break loop
			}
		}
		esweep.Append(logging.LoggableMap{
			"whiteSetSize": fmt.Sprintf("%d", removed),
		})
		esweep.Done()
		if errors {
			output <- Result{Error: ErrCannotDeleteSomeBlocks}
		}
	}()

	return output
}

func Descendants(ctx context.Context, getLinks dag.GetLinks, set *cid.Set, roots []*cid.Cid) error {
	for _, c := range roots {
		set.Add(c)

		// EnumerateChildren recursively walks the dag and adds the keys to the given set
		err := dag.EnumerateChildren(ctx, getLinks, c, set.Visit)
		if err != nil {
			return err
		}
	}

	return nil
}

// ColoredSet computes the set of nodes in the graph that are pinned by the
// pins in the given pinner.
func ColoredSet(ctx context.Context, pn pin.Pinner, ls dag.LinkService, bestEffortRoots []*cid.Cid, output chan<- Result) (*cid.Set, error) {
	// KeySet currently implemented in memory, in the future, may be bloom filter or
	// disk backed to conserve memory.
	errors := false
	gcs := cid.NewSet()
	getLinks := func(ctx context.Context, cid *cid.Cid) ([]*node.Link, error) {
		links, err := ls.GetLinks(ctx, cid)
		if err != nil {
			errors = true
			output <- Result{Error: &CannotFetchLinksError{cid, err}}
		}
		return links, nil
	}
	err := Descendants(ctx, getLinks, gcs, pn.RecursiveKeys())
	if err != nil {
		errors = true
		output <- Result{Error: err}
	}

	bestEffortGetLinks := func(ctx context.Context, cid *cid.Cid) ([]*node.Link, error) {
		links, err := ls.GetLinks(ctx, cid)
		if err != nil && err != dag.ErrNotFound {
			errors = true
			output <- Result{Error: &CannotFetchLinksError{cid, err}}
		}
		return links, nil
	}
	err = Descendants(ctx, bestEffortGetLinks, gcs, bestEffortRoots)
	if err != nil {
		errors = true
		output <- Result{Error: err}
	}

	for _, k := range pn.DirectKeys() {
		gcs.Add(k)
	}

	err = Descendants(ctx, getLinks, gcs, pn.InternalPins())
	if err != nil {
		errors = true
		output <- Result{Error: err}
	}

	if errors {
		return nil, ErrCannotFetchAllLinks
	}

	return gcs, nil
}

var ErrCannotFetchAllLinks = errors.New("garbage collection aborted: could not retrieve some links")

var ErrCannotDeleteSomeBlocks = errors.New("garbage collection incomplete: could not delete some blocks")

type CannotFetchLinksError struct {
	Key *cid.Cid
	Err error
}

func (e *CannotFetchLinksError) Error() string {
	return fmt.Sprintf("could not retrieve links for %s: %s", e.Key, e.Err)
}

type CannotDeleteBlockError struct {
	Key *cid.Cid
	Err error
}

func (e *CannotDeleteBlockError) Error() string {
	return fmt.Sprintf("could not remove %s: %s", e.Key, e.Err)
}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe BlogPost do

  before(:each) do
    @post = blogs(:one).posts.build(:title => "First post!",
                                    :body => "Hey there")
  end

  it "should be valid" do
    @post.should be_valid
  end

  it "should require a title" do
    post = BlogPost.new
    post.should_not be_valid
    post.errors.on(:title).should_not be_empty
  end

  it "should require a body" do
    post = BlogPost.new
    post.should_not be_valid
    post.errors.on(:body).should_not be_empty
  end

  it "should have a maximum body length" do
    @post.should have_maximum(:body, BlogPost::MAX_BODY)
  end

  describe "post activity associations" do

    before(:each) do
      @post.save!
      @activity = Activity.find_by_item_id(@post)
    end

    it "should have an activity" do
      @activity.should_not be_nil
    end

    it "should add an activity to the poster" do
      @post.blog.owner.recent_activity.should contain(@activity)
    end
  end

  describe "comment associations" do

    before(:each) do
      @post.save
      @comment = @post.comments.unsafe_create(:body => "The body",
                                              :commenter => dogs(:nola))
    end

    it "should have associated comments" do
      @post.comments.should_not be_empty
    end

    it "should add activities to the poster" do
      @post.comments.each do |comment|
        activity = Activity.find_by_item_id(comment)
        @post.blog.owner.activities.should contain(activity)
      end
    end

    it "should destroy the comments if the post is destroyed" do
      comments = @post.comments
      @post.destroy
      comments.each do |comment|
        comment.should_not exist_in_database
      end
    end

    it "should destroy the comments activity if the post is destroyed" do
      comments = @post.comments
      @post.destroy
      comments.each do |comment|
        Activity.find_by_item_id(comment).should be_nil
      end
    end
  end
end


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _mzCrypto = require('mz/crypto');

var _token = require('./token');

var _token2 = _interopRequireDefault(_token);

/**
 * Generate a salt.
 *
 * @method
 * @param {Number} len
 * @param {String} encoding
 * @return {Promise} by default 32 of slat length.
 */
function genSalt() {
  var len = arguments[0] === undefined ? 16 : arguments[0];
  var encoding = arguments[1] === undefined ? 'hex' : arguments[1];

  return (0, _token2['default'])(len, encoding);
}

/**
 * Compare hash and  password + salt.
 *
 * @method
 * @param {String} hashstr
 * @param {String} password
 * @param {string} salt
 * @param {Number} [iterations] 1024
 * @param {Number} [keylen] 32
 * @param {String} [digest] sha256
 * @param {String} [encoding] hex
 * @return {Promise}
 */
function compare(hashstr, password, salt) {
  var iterations = arguments[3] === undefined ? 1024 : arguments[3];
  var keylen = arguments[4] === undefined ? 32 : arguments[4];
  var digest = arguments[5] === undefined ? 'sha256' : arguments[5];
  var encoding = arguments[6] === undefined ? 'hex' : arguments[6];

  return hash(password, salt, iterations, keylen, digest, encoding).then(function (data) {
    return hashstr === data;
  });
}

/**
 * Hash a password with salt.
 *
 * @method
 * @param {String} password
 * @param {string} salt
 * @param {Number} [iterations] 1024
 * @param {Number} [keylen] 32
 * @param {String} [digest] sha256
 * @param {String} [encoding] hex
 * @return {Promise} by default 64 of password_hash length.
 */
function hash(password, salt) {
  var iterations = arguments[2] === undefined ? 1024 : arguments[2];
  var keylen = arguments[3] === undefined ? 32 : arguments[3];
  var digest = arguments[4] === undefined ? 'sha256' : arguments[4];
  var encoding = arguments[5] === undefined ? 'hex' : arguments[5];

  return (0, _mzCrypto.pbkdf2)(password, salt, iterations, keylen, digest).then(function (buf) {
    return buf.toString(encoding);
  });
}

exports['default'] = {
  genSalt: genSalt, compare: compare, hash: hash
};
module.exports = exports['default'];


text:
package com.stratio.sparta.plugin.output.cassandra

import java.io.{Serializable => JSerializable}

import com.stratio.sparta.sdk.pipeline.output.Output._
import com.stratio.sparta.sdk.pipeline.output.{Output, SaveModeEnum}
import com.stratio.sparta.sdk.properties.ValidatingPropertyMap._
import org.apache.spark.sql._

class CassandraOutput(name: String, properties: Map[String, JSerializable]) extends Output(name, properties) {

  val MaxTableNameLength = 48

  val keyspace = properties.getString("keyspace", "sparta")
  val cluster = properties.getString("cluster", "default")

  override def supportedSaveModes: Seq[SaveModeEnum.Value] =
    Seq(SaveModeEnum.Append, SaveModeEnum.ErrorIfExists, SaveModeEnum.Ignore, SaveModeEnum.Overwrite)

  override def save(dataFrame: DataFrame, saveMode: SaveModeEnum.Value, options: Map[String, String]): Unit = {
    val tableNameVersioned = getTableName(getTableNameFromOptions(options).toLowerCase)

    validateSaveMode(saveMode)

    dataFrame.write
      .format("org.apache.spark.sql.cassandra")
      .mode(getSparkSaveMode(saveMode))
      .options(Map("table" -> tableNameVersioned, "keyspace" -> keyspace, "cluster" -> cluster) ++ getCustomProperties
      )
      .save()
  }

  def getTableName(table: String): String =
    if (table.length > MaxTableNameLength - 3) table.substring(0, MaxTableNameLength - 3) else table

}

object CassandraOutput {

  final val DefaultHost = "127.0.0.1"
  final val DefaultPort = "9042"

  def getSparkConfiguration(configuration: Map[String, JSerializable]): Seq[(String, String)] = {
    val connectionHost = configuration.getString("connectionHost", DefaultHost)
    val connectionPort = configuration.getString("connectionPort", DefaultPort)

    val sparkProperties = getSparkCassandraProperties(configuration)

    sparkProperties ++
      Seq(
        ("spark.cassandra.connection.host", connectionHost),
        ("spark.cassandra.connection.port", connectionPort)
      )
  }

  private def getSparkCassandraProperties(configuration: Map[String, JSerializable]): Seq[(String, String)] = {
    configuration.get("sparkProperties") match {
      case Some(properties) =>
        val conObj = configuration.getMapFromJsoneyString("sparkProperties")
        conObj.map(propKeyPair => {
          val key = propKeyPair("sparkPropertyKey")
          val value = propKeyPair("sparkPropertyValue")
          (key, value)
        })
      case None => Seq()
    }
  }
}


text:
using namespace System;
using namespace Ultrasonix::Porta;

int PreRunCallback(void* param)
{
	Porta^ porta = static_cast<Porta^>(GCHandle::operator GCHandle(IntPtr(param)).Target);
	porta->RaisePreRunning();

	return 0;
}

int RawDataCallback(void* param, unsigned char* data, int cineBlock, int header)
{
	Porta^ porta = static_cast<Porta^>(GCHandle::operator GCHandle(IntPtr(param)).Target);

	RawDataEventArgs^ args = gcnew RawDataEventArgs(IntPtr(data), cineBlock, header);
	porta->RaiseRawDataCallback(args);

	return 0;
}

int DisplayCallback(void* param, int id, int header)
{
	Porta^ porta = static_cast<Porta^>(GCHandle::operator GCHandle(IntPtr(param)).Target);

	DisplayCallbackEventArgs^ args = gcnew DisplayCallbackEventArgs(id, header);
	porta->RaiseDisplayImageReceived(args);

	return 0;
}


text:
package iso20022

// Statistical data related to the price change of a security.
type StatisticsByUserDefinedTimePeriod2 struct {

	// Reference period for the valuation.
	Period *DateOrDateTimePeriodChoice `xml:"Prd"`

	// Highest price for the referenced period.
	HighestPriceValue *PriceValue5 `xml:"HghstPricVal,omitempty"`

	// Lowest price for the referenced period.
	LowestPriceValue *PriceValue5 `xml:"LwstPricVal,omitempty"`

	// Change in price since the previous valuation date.
	PriceChange *PriceValueChange1 `xml:"PricChng,omitempty"`

	// Rate of income from the financial instrument, usually calculated as total dividends or coupon interest available to investors in the last year,divided by the current price.
	Yield *PercentageRate `xml:"Yld,omitempty"`
}

func (s *StatisticsByUserDefinedTimePeriod2) AddPeriod() *DateOrDateTimePeriodChoice {
	s.Period = new(DateOrDateTimePeriodChoice)
	return s.Period
}

func (s *StatisticsByUserDefinedTimePeriod2) AddHighestPriceValue() *PriceValue5 {
	s.HighestPriceValue = new(PriceValue5)
	return s.HighestPriceValue
}

func (s *StatisticsByUserDefinedTimePeriod2) AddLowestPriceValue() *PriceValue5 {
	s.LowestPriceValue = new(PriceValue5)
	return s.LowestPriceValue
}

func (s *StatisticsByUserDefinedTimePeriod2) AddPriceChange() *PriceValueChange1 {
	s.PriceChange = new(PriceValueChange1)
	return s.PriceChange
}

func (s *StatisticsByUserDefinedTimePeriod2) SetYield(value string) {
	s.Yield = (*PercentageRate)(&value)
}


text:
			<input id="back" type="button" value="go back"/>
			<input id="ahead" type="button" value="go ahead"/>
			<input id="slideto" type="button" value="slideto 2-2"/>


text:
Basic Layout Utilities

## Dependencies
* NodeJs
* Grunt
* SASS (v3.3 or higher)
* [extract-sass-vars](https://github.com/chriseppstein/extract-sass-vars)


text:
@implementation IMLayer

- (void)drawInContext:(CGContextRef)ctx{

}

@end


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
  ~
  ~   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.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.streams</groupId>
        <artifactId>streams-components</artifactId>
        <version>0.6.2-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>streams-http</artifactId>

    <name>streams-http</name>

    <description>HTTP Utility Components</description>

    <dependencies>

        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-pojo</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-pojo-extensions</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.streams</groupId>
            <artifactId>streams-testing</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
            <type>test-jar</type>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <groupId>org.apache.streams.plugins</groupId>
                <artifactId>streams-plugin-pojo</artifactId>
                <version>${project.version}</version>
                <configuration>
                    <sourcePaths>
                        <sourcePath>${project.basedir}/src/main/jsonschema</sourcePath>
                    </sourcePaths>
                    <targetDirectory>${project.basedir}/target/generated-sources/pojo</targetDirectory>
                    <targetPackage>org.apache.streams.http</targetPackage>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.streams</groupId>
                        <artifactId>streams-converters</artifactId>
                        <version>${project.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>add-source</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>add-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>target/generated-sources/pojo</source>
                            </sources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
using omaha::CreateDir;
using omaha::ConcatenatePath;
using omaha::File;
using omaha::GetCurrentDir;
using omaha::GetDirectoryFromPath;
using omaha::GetFileFromPath;

int _tmain(int argc, TCHAR* argv[]) {
  if (argc != 4 && argc != 5) {
    _tprintf(_T("Incorrect number of arguments!\n"));
    _tprintf(_T("Usage: ApplyTag <signed_file> <outputfile> <tag> [append]\n"));
    return -1;
  }

  const TCHAR* file = argv[1];
  if (!File::Exists(file)) {
    _tprintf(_T("File \"%s\" not found!\n"), file);
    return -1;
  }

  bool append = false;
  if (argc == 5 && _tcsicmp(argv[4], _T("append")) == 0) {
    append = true;
  }

  CString dir = GetDirectoryFromPath(argv[2]);
  CString path = ConcatenatePath(GetCurrentDir(), dir);
  ASSERT1(!path.IsEmpty());
  if (!File::Exists(path)) {
    HRESULT hr = CreateDir(path, NULL);
    if (FAILED(hr)) {
      _tprintf(_T("Could not create dir %s\n"), path);
      return hr;
    }
  }

  CString file_name = GetFileFromPath(argv[2]);
  CString out_path = ConcatenatePath(path, file_name);
  ASSERT1(!out_path.IsEmpty());
  ASSERT1(File::Exists(path));
  omaha::ApplyTag tag;
  HRESULT hr = tag.Init(argv[1],
                        CT2CA(argv[3]),
                        lstrlenA(CT2CA(argv[3])),
                        out_path,
                        append);
  if (hr == E_INVALIDARG) {
    _tprintf(_T("The tag_string %s contains invalid characters."), argv[3]);
    _tprintf(_T("  We accept the following ATL RegEx '[-%{}/\a&=._]*'\n"));
    return hr;
  }

  if (FAILED(hr)) {
    _tprintf(_T("Tag.Init Failed hr = %x\n"), hr);
    return hr;
  }

  hr = tag.EmbedTagString();
  if (hr == APPLYTAG_E_ALREADY_TAGGED) {
    _tprintf(_T("The binary %s is already tagged."), argv[1]);
    _tprintf(_T(" In order to append the tag string, use the append flag.\n"));
    _tprintf(_T("Usage: ApplyTag <signed_file> <outputfile> <tag> [append]\n"));
  }

  return 0;
}


text:
""" Setup script for PyPI """
from setuptools import setup

setup(
    name='dynamic-dynamodb',
    version='1.6.0',
    license='Apache License, Version 2.0',
    description='Automatic provisioning for AWS DynamoDB tables',
    author='Sebastian Dahlgren',
    author_email='sebastian.dahlgren@gmail.com',
    url='http://sebdah.github.com/dynamic-dynamodb/',
    keywords="dynamodb aws provisioning amazon web services",
    platforms=['Any'],
    packages=['dynamic_dynamodb'],
    scripts=['dynamic-dynamodb'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'boto >= 2.6.0',
        'requests >= 0.14.1'
    ],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python'
    ]
)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Salic. Japan 59, t. 13A-D. 1903

#### Original name
null

### Remarks
null


text:
package info.globalbus.blueprint.plugin.model;

import info.globalbus.blueprint.plugin.handlers.Handlers;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import org.apache.aries.blueprint.plugin.spi.CustomDependencyAnnotationHandler;
import org.apache.aries.blueprint.plugin.spi.NamedLikeHandler;
import org.apache.aries.blueprint.plugin.spi.XmlWriter;

import static info.globalbus.blueprint.plugin.model.AnnotationHelper.findName;
import static info.globalbus.blueprint.plugin.model.NamingHelper.getBeanName;

@EqualsAndHashCode(of = "name")
@RequiredArgsConstructor
class Property implements Comparable<Property>, XmlWriter {
    public final String name;
    public final String ref;
    public final String value;
    final boolean isField;
    private final RefCollection refCollection;

    static Property create(BlueprintRegistry blueprintRegistry, Field field) {
        if (needsInject(field)) {
            String value = AnnotationHelper.findValue(field.getAnnotations());
            if (value != null) {
                return new Property(field.getName(), null, value, true, null);
            }

            RefCollection refCollection = RefCollection.getRefCollection(blueprintRegistry, field);
            if (refCollection != null) {
                return new Property(field.getName(), null, null, true, refCollection);
            }

            String ref = getForcedRefName(field);
            String refFromCustomDependencyHandler = getRefFromCustomDependencyHandlers(blueprintRegistry, field, ref);
            if (refFromCustomDependencyHandler != null) {
                ref = refFromCustomDependencyHandler;
            }
            if (ref != null) {
                return new Property(field.getName(), ref, null, true, null);
            }
            BeanRef matching = blueprintRegistry.getMatching(new BeanTemplate(field));
            ref = (matching == null) ? getDefaultRefName(field) : matching.id;
            return new Property(field.getName(), ref, null, true, null);
        } else {
            // Field is not a property
            return null;
        }
    }

    private static String getRefFromCustomDependencyHandlers(BlueprintRegistry blueprintRegistry, AnnotatedElement
        annotatedElement, String ref) {
        for (CustomDependencyAnnotationHandler customDependencyAnnotationHandler : Handlers
            .CUSTOM_DEPENDENCY_ANNOTATION_HANDLERS) {
            Annotation annotation = (Annotation) AnnotationHelper.findAnnotation(annotatedElement.getAnnotations(),
                customDependencyAnnotationHandler.getAnnotation());
            if (annotation != null) {
                String generatedRef = customDependencyAnnotationHandler.handleDependencyAnnotation(annotatedElement,
                    ref, blueprintRegistry);
                if (generatedRef != null) {
                    return generatedRef;
                }
            }
        }
        return null;
    }

    static Property create(BlueprintRegistry blueprintRegistry, Method method) {
        String propertyName = resolveProperty(method);
        if (propertyName == null) {
            return null;
        }

        String value = AnnotationHelper.findValue(method.getAnnotations());
        if (value != null) {
            return new Property(propertyName, null, value, false, null);
        }

        if (needsInject(method)) {
            RefCollection refCollection = RefCollection.getRefCollection(blueprintRegistry, method);
            if (refCollection != null) {
                return new Property(propertyName, null, null, true, refCollection);
            }

            String ref = getForcedRefName(method);
            if (ref == null) {
                ref = findName(method.getParameterAnnotations()[0]);
            }
            String refFromCustomDependencyHandler = getRefFromCustomDependencyHandlers(blueprintRegistry, method, ref);
            if (refFromCustomDependencyHandler != null) {
                ref = refFromCustomDependencyHandler;
            }

            if (ref != null) {
                return new Property(propertyName, ref, null, false, null);
            }

            for (CustomDependencyAnnotationHandler customDependencyAnnotationHandler : Handlers
                .CUSTOM_DEPENDENCY_ANNOTATION_HANDLERS) {
                Annotation annotation = (Annotation) AnnotationHelper.findAnnotation(method.getParameterAnnotations()
                    [0], customDependencyAnnotationHandler.getAnnotation());
                if (annotation != null) {
                    String generatedRef = customDependencyAnnotationHandler.handleDependencyAnnotation(method
                        .getParameterTypes()[0], annotation, null, blueprintRegistry);
                    if (generatedRef != null) {
                        ref = generatedRef;
                        break;
                    }
                }
            }
            if (ref != null) {
                return new Property(propertyName, ref, null, false, null);
            }

            BeanTemplate template = new BeanTemplate(method);
            BeanRef matching = blueprintRegistry.getMatching(template);
            ref = (matching == null) ? getBeanName(method.getParameterTypes()[0]) : matching.id;
            return new Property(propertyName, ref, null, false, null);
        }

        return null;
    }

    private static String resolveProperty(Method method) {
        if (method.getParameterTypes().length != 1) {
            return null;
        }
        String propertyName = method.getName().substring(3);
        return makeFirstLetterLower(propertyName);
    }

    /**
     * Assume it is defined in another manually created blueprint context with default name
     *
     * @param field
     * @return
     */
    private static String getDefaultRefName(Field field) {
        return getBeanName(field.getType());
    }

    private static String getForcedRefName(Field field) {
        return getForcedRefName(field.getType(), field);
    }

    private static String getForcedRefName(Method method) {
        return getForcedRefName(method.getParameterTypes()[0], method);
    }

    private static String getForcedRefName(Class<?> clazz, AnnotatedElement annotatedElement) {
        for (NamedLikeHandler<? extends Annotation> namedLikeHandler : Handlers.NAMED_LIKE_HANDLERS) {
            if (annotatedElement.getAnnotation(namedLikeHandler.getAnnotation()) != null) {
                String name = namedLikeHandler.getName(clazz, annotatedElement);
                if (name != null) {
                    return name;
                }
            }
        }
        return null;
    }

    private static boolean needsInject(AnnotatedElement annotatedElement) {
        for (Class<? extends Annotation> injectDependencyAnnotation :
            AnnotationHelper.injectDependencyAnnotations) {
            if (annotatedElement.getAnnotation(injectDependencyAnnotation) != null) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int compareTo(Property other) {
        return name.compareTo(other.name);
    }

    private static String makeFirstLetterLower(String name) {
        return name.substring(0, 1).toLowerCase() + name.substring(1);
    }

    @Override
    public void write(XMLStreamWriter writer) throws XMLStreamException {
        writer.writeStartElement("property");
        writer.writeAttribute("name", name);
        if (ref != null) {
            writer.writeAttribute("ref", ref);
        } else if (value != null) {
            writer.writeAttribute("value", value);
        } else if (refCollection != null) {
            refCollection.write(writer);
        }
        writer.writeEndElement();
    }
}


text:
<?php

define('MSGPACK_CLASS_OPT_PHPONLY', -1001);

/**
 * \MessagePackUnpacker.
 *
 * @see https://github.com/msgpack/msgpack-php
 */
class MessagePackUnpacker
{
    /**
     * MessagePackUnpacker constructor.
     *
     * @param bool $opt
     */
    public function __construct($opt = null)
    {
    }

    /**
     * MessagePack destructor.
     */
    public function __destruct()
    {
    }

    /**
     * @param int  $option
     * @param bool $value
     */
    public function setOption($option, $value)
    {
    }

    /**
     * @param string $str
     */
    public function feed($str)
    {
    }

    /**
     * @param string $str
     * @param int    $offset
     */
    public function execute($str = null, &$offset = null)
    {
    }

    /**
     * @param mixed $object
     */
    public function data($object = null)
    {
    }

    public function reset()
    {
    }
}

/**
 * \MessagePack.
 *
 * @see https://github.com/msgpack/msgpack-php
 */
class MessagePack
{
    /**
     * MessagePack constructor.
     *
     * @param bool $opt
     */
    public function __construct($opt = null)
    {
    }

    /**
     * @param int  $option
     * @param bool $value
     */
    public function setOption($option, $value)
    {
    }

    /**
     * @param mixed $value
     *
     * @return string
     */
    public function pack($value)
    {
    }

    /**
     * @param string $str
     * @param mixed  $object
     *
     * @return mixed
     */
    public function unpack($str, $object = null)
    {
    }

    /**
     * @return MessagePackUnpacker
     */
    public function unpacker()
    {
    }
}

/**
 * @param mixed $value
 *
 * @return string
 */
function msgpack_pack($value)
{
}

/**
 * @param string $str
 *
 * @return mixed
 */
function msgpack_unpack($str)
{
}

/**
 * @param mixed $value
 *
 * @return string
 */
function msgpack_serialize($value)
{
}

/**
 * @param string $str
 *
 * @return mixed
 */
function msgpack_unserialize($str)
{
}


text:
<?php
/**
 * @link       http://zoopcommerce.github.io/shard
 * @package    Zoop
 * @license    MIT
 */
namespace Zoop\Shard\User\DataModel;

use Zoop\Shard\Crypt\SaltGenerator;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Zoop\Shard\Annotation\Annotations as Shard;

/**
 * Implementation of Zoop\Common\User\PasswordInterface
 *
 * @since   1.0
 * @author  Tim Roediger <superdweebie@gmail.com>
 */
trait PasswordTrait
{
    /**
     * @ODM\String
     * @Shard\Serializer\Ignore
     * @Shard\Validator\Chain({
     *     @Shard\Validator\Required,
     *     @Shard\Validator\Password
     * })
     * @Shard\Crypt\Hash
     */
    protected $password;

    /**
     * @ODM\String
     * @Shard\Serializer\Ignore
     */
    protected $salt;

    /**
     * Returns encrypted password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     *
     * @param string $plaintext
     */
    public function setPassword($plaintext)
    {
        $this->password = (string) $plaintext;
    }

    public function getSalt()
    {
        if (!isset($this->salt)) {
            $this->salt = SaltGenerator::generateSalt();
        }

        return $this->salt;
    }

    public function setSalt($value)
    {
        return $this->salt = (string) $value;
    }
}


text:
package luxmeter.functions;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static luxmeter.functions.Argument.bind;
import static luxmeter.functions.Argument.free;
import static luxmeter.functions.Functions.partial;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class FunctionsTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testPartialApplication2() {
        PartialFunction<Integer> partial = Functions.<Integer, Integer, Integer>partial(
                this::add, free(), bind(2));
        Integer result = partial.apply(5);
        assertThat(result, is(add(5, 2)));
    }

    @Test
    public void testPartialApplication3() {
        PartialFunction<Integer> partial = Functions.<Integer, Integer, Integer, Integer>partial(
                this::add, bind(2), free(), bind(3));
        Integer result = partial.apply(5);
        assertThat(result, is(add(2, 5, 3)));
    }

    @Test
    public void testPartialApplicationFail() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("Cannot invoke partial function. Expected 1 argument(s) but were 2");
        PartialFunction<Integer> partial = partial(this::sub, bind(10), free());
        partial.apply(5, 2); // should fail since there is no third parameter
    }

    private int add(int a, int b, int c) {
        return a + b + c;
    }

    private int add(int a, int b) {
        return a + b;
    }

    private int sub(int a, int b) {
        return a - b;
    }
}


text:
@implementation NSObject (Swizzing)

+ (void)load {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        Class class = [self class];
        // When swizzling a class method, use the following:
        // Class class = object_getClass((id)self);
        SEL originalSelector = NSSelectorFromString(@"crash");
        SEL swizzledSelector = @selector(crash_replace);
        Method originalMethod = class_getInstanceMethod(class, originalSelector);

        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        if (didAddMethod) {
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        }
        else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });

}

- (void)crash_replace {

    if ([self isKindOfClass:NSClassFromString(@"FirstViewController")]) {

    }
}

@end


text:
'use strict';

angular.module('sdm.navigation',
    ['sdm.navigation.controllers.sdmNavigation'])


text:
<BOUCLE_article(ARTICLES){id_article}{statut IN prop,prepa,publie,refuse,poubelle}>#CACHE{0}
[(#HTTP_HEADER{Content-type: text/plain[; charset=(#CHARSET)]}
)][(#HTTP_HEADER{Content-Disposition: attachment; filename="[(#DATE|date_iso|couper{10})]-[(#URL_ARTICLE|replace{.*/,})].md"}
)]#INCLURE{fond=article2markdown-contenu,id_article}</BOUCLE_article>


text:
package com.github.jacopofar.fleximatcherrestinterface;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.jacopofar.fleximatcher.FlexiMatcher;
import com.github.jacopofar.fleximatcher.annotations.MatchingResults;
import com.github.jacopofar.fleximatcher.annotations.TextAnnotation;
import com.github.jacopofar.fleximatcher.importer.FileTagLoader;
import com.github.jacopofar.fleximatcherrestinterface.annotators.HTTPRuleFactory;
import com.github.jacopofar.fleximatcherrestinterface.exceptions.RuntimeJSONCarryingException;
import com.github.jacopofar.fleximatcherrestinterface.messages.AnnotatorPayload;
import com.github.jacopofar.fleximatcherrestinterface.messages.CompleteTagPayload;
import com.github.jacopofar.fleximatcherrestinterface.messages.ParseRequestPayload;
import com.github.jacopofar.fleximatcherrestinterface.messages.TagRulePayload;
import org.json.JSONException;
import org.json.JSONObject;
import spark.Response;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import static spark.Spark.*;

public class Fri {
    private static FlexiMatcher fm;
    private static  ConcurrentHashMap<String,AnnotatorPayload> annotators=new ConcurrentHashMap<>();

    public static void main(String[] args) throws IOException {
        System.out.println("Starting matcher...");
        fm = new FlexiMatcher();
        System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "info");

        String fname="rule_list.tsv";
        FileTagLoader.readTagsFromTSV(fname, fm);

        if(System.getenv("FRI_API_KEY") != null){
            String apiKey = System.getenv("FRI_API_KEY");
            System.out.println("the apiKey in X-FRI-API-KEY will have to be '" + apiKey + "'");
            before((request, response) -> {
                if(!apiKey.equals(request.headers("X-FRI-API-KEY"))){
                    System.out.println("refused a " + request.requestMethod() + " to " + request.pathInfo() + " due to a wrong or missing X-FRI-API-KEY header. It was " + request.headers("X-FRI-API-KEY"));
                    halt(401, "wrong or missing X-FRI-API-KEY header");
                }
            });
        }
        else {
            System.out.println("no FRI_API_KEY environment variable, any request will be accepted");
        }

        //staticFiles.externalLocation("static");

        //staticFiles.externalLocation("/static");
        //  port(5678); <- Uncomment this if you want spark to listen to port 5678 in stead of the default 4567

        //show exceptions in console and HTTP responses
        exception(Exception.class, (exception, request, response) -> {
            //show the exceptions using stdout
            System.out.println("Exception dealing with " + request.requestMethod() + " " + request.contextPath());
            exception.printStackTrace(System.out);
            response.status(400);
            if(exception instanceof RuntimeJSONCarryingException){
                response.type("application/json; charset=utf-8");
                response.body(exception.toString());
                return;
            }
            response.body(exception.toString());

        });

        //show each requested path in the console
        after((request, response) -> {
            //TODO currently not working, waiting for this merge to appear in Maven:
            //https://github.com/perwendel/spark/pull/579
            /*
            System.out.println(ZonedDateTime.now().format( DateTimeFormatter.ISO_INSTANT)
                    + " \t " + request.requestMethod()
                    + " \t " + request.pathInfo()
                    + " \t " + response.status()
                    + " \t " + response.body().length());*/
        });

/* old code, used by the old interface
        get("/parse", (request, response) -> {

            String text = request.queryMap().get("text").value();
            String pattern = request.queryMap().get("pattern").value();
            System.out.println(text+" -- "+pattern);

            MatchingResults results;
            JSONObject retVal = new JSONObject();
            long start=System.currentTimeMillis();
            results = fm.matches(text, pattern, FlexiMatcher.getDefaultAnnotator(), true, false, true);

            retVal.put("time_to_parse", System.currentTimeMillis()-start);
            retVal.put("is_matching", results.isMatching());
            retVal.put("empty_match", results.isEmptyMatch());
            for(LinkedList<TextAnnotation> interpretation:results.getAnnotations().get()){
                JSONObject addMe = new JSONObject();

                for(TextAnnotation v:interpretation){
                    addMe.append("annotations", new JSONObject(v.toJSON()));
                }
                retVal.append("interpretations", addMe);
            }
            return sendJSON(response, retVal);

        });
*/

        put("/tags/:tagname/:tag_identifier", (request, response) -> {
            ObjectMapper mapper = new ObjectMapper();
            TagRulePayload newPost = mapper.readValue(request.body(), TagRulePayload.class);
            if(newPost.errorMessages().size() != 0){
                response.status(400);
                return "invalid request body. Errors: " + newPost.errorMessages() ;
            }
            System.out.println("RULE TO BE CREATED: " + newPost.toString());
            fm.addTagRule(request.params(":tagname"),newPost.getPattern(), request.params(":tag_identifier"),newPost.getAnnotationTemplate());
            return "rule for tag " + request.params(":tagname") + " having id " + request.params(":tag_identifier") + " : " + newPost.toString();
        });

        post("/tags/:tagname", (request, response) -> {
            String tagName = request.params(":tagname");
            int newId = 1;

            while(fm.getTagRule(tagName, tagName + "_" + newId).isPresent()){
                newId++;
            }
            ObjectMapper mapper = new ObjectMapper();
            TagRulePayload newPost = mapper.readValue(request.body(), TagRulePayload.class);
            if(newPost.errorMessages().size() != 0){
                response.status(400);
                return "invalid request body. Errors: " + newPost.errorMessages() ;
            }
            System.out.println("RULE TO BE CREATED: " + newPost.toString());
            fm.addTagRule(tagName,newPost.getPattern(), tagName + "_" + newId,newPost.getAnnotationTemplate());

            return "rule for tag " + tagName + " having id " + tagName + "_" + newId + " : " + newPost.toString();
        });

        post("/parse", (request, response) -> {
            ObjectMapper mapper = new ObjectMapper();
            ParseRequestPayload parseRequest = mapper.readValue(request.body(), ParseRequestPayload.class);
            if(parseRequest.errorMessages().size() != 0){
                response.status(400);
                return "invalid request body. Errors: " + parseRequest.errorMessages() ;
            }
            System.out.println("PARSE REQUEST: " + parseRequest.toString());
            MatchingResults results;
            JSONObject retVal = new JSONObject();
            long start=System.currentTimeMillis();
            //the flags are: fullyAnnotate,  matchWhole, populateResult

            results = fm.matches(parseRequest.getText(),parseRequest.getPattern(),FlexiMatcher.getDefaultAnnotator(), parseRequest.isFullyAnnotate(), parseRequest.isMatchWhole(), parseRequest.isPopulateResult());
            retVal.put("time_to_parse", System.currentTimeMillis()-start);
            retVal.put("is_matching", results.isMatching());
            retVal.put("empty_match", results.isEmptyMatch());
            if(results.isMatching()){
                for(LinkedList<TextAnnotation> interpretation:results.getAnnotations().get()){
                    JSONObject addMe = new JSONObject();

                    for(TextAnnotation v:interpretation){
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                    }
                    retVal.append("interpretations", addMe);
                }
            }
            return sendJSON(response, retVal);
        });

        /**
         * Add a new annotator
         * */
        put("/rules/:rulename", (request, response) -> {
            ObjectMapper mapper = new ObjectMapper();
            AnnotatorPayload newPost = mapper.readValue(request.body(), AnnotatorPayload.class);
            if(newPost.errorMessages().size() != 0){
                response.status(400);
                return "invalid request body. Errors: " + newPost.errorMessages();
            }
            System.out.println("Creating annotator for: " + newPost.toString());
            boolean replaced = fm.bind(request.params(":rulename"), new HTTPRuleFactory(newPost.getEndpoint(), newPost.getSampler_endpoint(), null));
            annotators.put(request.params(":rulename"), newPost);
            return (replaced ? "annotator updated": "annotator added") + " for rule " + request.params(":rulename");
        });

        /**
         * Retrieve annotator details
         * */
        get("/rules/:rulename", (request, response) -> {
            response.type("application/json");
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(annotators.get(request.params(":rulename")));
        });

        /**
         * Delete a specific tag rule
         * */
        delete("/tags/:tagname/:tag_identifier", (request, response) -> {
            if(!fm.getTagNames().anyMatch(n -> n.equals(request.params(":tagname")))){
                response.status(404);
                return "tag " + request.params(":tagname") + " unknown";
            }
            if(fm.removeTagRule(request.params(":tagname"), request.params(":tag_identifier"))){
                response.status(200);
                return "rule removed";
            }
            else {
                response.status(404);
                return "rule not found";
            }
        });

        /**
         * List the known tags
         * */
        get("/tags", (request, response) -> {
            response.type("application/json");
            ServletOutputStream os = response.raw().getOutputStream();
            os.write("[".getBytes());
            final boolean[] first = {true};
            fm.getTagNames().forEach( tn -> {
                try {
                    if(!first[0]) os.write(",".getBytes());
                    first[0] = false;
                    os.write(JSONObject.quote(tn).getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            os.write("]".getBytes());

            os.flush();
            os.close();
            return response.raw();

        });

        /**
         * List the known rules for a given tag
         * */
        get("/tags/:tagname", (request, response) -> {
            response.type("application/json");
            ServletOutputStream os = response.raw().getOutputStream();
            os.write("[".getBytes());
            final boolean[] first = {true};
            fm.getTagDefinitions(request.params(":tagname")).forEach( td -> {
                try {
                    if(!first[0]) os.write(",".getBytes());
                    first[0] = false;
                    JSONObject jo = new JSONObject();
                    jo.put("id", td.getIdentifier());
                    jo.put("pattern", td.getPattern());
                    if(td.getAnnotationExpression() != null)
                        jo.put("annotation", td.getAnnotationExpression());
                    os.write(jo.toString().getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    //can never happen, key is hardcoded and not null
                    e.printStackTrace();
                }
            });
            os.write("]".getBytes());

            os.flush();
            os.close();
            return response.raw();
        });

        /**
         * Explains with a human-readable text how an interpretation was given
         * */
        post("/parse_explain", (request, response) -> {
            ObjectMapper mapper = new ObjectMapper();
            ParseRequestPayload parseRequest = mapper.readValue(request.body(), ParseRequestPayload.class);
            if(parseRequest.errorMessages().size() != 0){
                response.status(400);
                return "invalid request body. Errors: " + parseRequest.errorMessages() ;
            }
            System.out.println("PARSE REQUEST: " + parseRequest.toString());
            MatchingResults results;
            JSONObject retVal = new JSONObject();
            long start=System.currentTimeMillis();
            //the flags are: fullyAnnotate,  matchWhole, populateResult

            results = fm.matches(parseRequest.getText(),parseRequest.getPattern(),FlexiMatcher.getDefaultAnnotator(true), true, parseRequest.isMatchWhole(), true);

            retVal.put("time_to_parse", System.currentTimeMillis()-start);
            retVal.put("is_matching", results.isMatching());
            retVal.put("empty_match", results.isEmptyMatch());
            if(results.isMatching()){
                for(LinkedList<TextAnnotation> interpretation:results.getAnnotations().get()){
                    JSONObject addMe = new JSONObject();

                    for(TextAnnotation v:interpretation){
                        addMe.append("annotations", new JSONObject(v.toJSON()));
                    }
                    retVal.append("interpretations", addMe);
                }
            }
            return sendJSON(response, retVal);
        });

        post("/generate", (request, response) -> {
            String pattern = new JSONObject(request.body()).getString("pattern");

            System.out.println("REQUEST TO GENERATE SAMPLE FOR: " + pattern);
            JSONObject retVal = new JSONObject();
            long start=System.currentTimeMillis();
            String sample = fm.generateSample(pattern);
            retVal.put("time_to_generate", System.currentTimeMillis()-start);
            retVal.put("sample", sample);
            return sendJSON(response, retVal);
        });

        get("/export_full", (request, response) -> {
            response.type("application/json");

            ServletOutputStream os = response.raw().getOutputStream();
            os.write("[".getBytes());
            final boolean[] first = {true};
            fm.getTagNames().forEach(tagName -> {
                fm.getTagDefinitions(tagName).forEach( td -> {
                    try {
                        if(!first[0]) os.write(",".getBytes());
                        first[0] = false;
                        JSONObject jo = new JSONObject();
                        jo.put("tag_name", tagName);
                        jo.put("id", td.getIdentifier());
                        jo.put("pattern", td.getPattern());
                        if(td.getAnnotationExpression() != null)
                            jo.put("annotation", td.getAnnotationExpression());
                        os.write(jo.toString().getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        //can never happen, key is hardcoded and not null
                        e.printStackTrace();
                    }
                });
            });

            os.write("]".getBytes());

            os.flush();
            os.close();
            return response.raw();
        });

        post("/import_full", (request, response) -> {
            ObjectMapper mapper = new ObjectMapper();
            List<CompleteTagPayload> tagsToImport = mapper.readValue(request.body(), mapper.getTypeFactory().constructCollectionType(List.class, CompleteTagPayload.class));
            LinkedList<String> overWritten = new LinkedList<String>();
            for(CompleteTagPayload newTag: tagsToImport){
                if(fm.addTagRule(newTag.getTag_name(), newTag.getPattern(), newTag.getId(), newTag.getAnnotation()))
                    overWritten.add(newTag.getTag_name() + "/" + newTag.getId());
            }
            JSONObject retVal = new JSONObject();
            retVal.put("imported", tagsToImport.size());
            retVal.put("overwritten", overWritten);
            return sendJSON(response, retVal);

        });
    }

    private static String sendJSON(Response r, JSONObject obj) {
        r.type("application/json");
        return obj.toString();
    }
}


text:
class AddReportToDelayedJobs < ActiveRecord::Migration
  def up
    add_column :delayed_jobs, :report_id, :integer
    add_index :delayed_jobs, :report_id
  end

  def down
    remove_index :delayed_jobs, :report_id
    remove_column :delayed_jobs, :report_id
  end
end


text:
Button groups

Group a series of buttons together on a single line with the button group. Add on optional JavaScript radio and checkbox style behavior with our buttons plugin.

Tooltips & popovers in button groups require special setting

When using tooltips or popovers on elements within a .btn-group, you'll have to specify the option container: 'body' to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the tooltip or popover is triggered).

Ensure correct role and provide a label

In order for assistive technologies – such as screen readers – to convey that a series of buttons is grouped, an appropriate role attribute needs to be provided. For button groups, this would be role="group", while toolbars should have a role="toolbar".

One exception are groups which only contain a single control (for instance the justified button groups with <button> elements) or a dropdown.

In addition, groups and toolbars should be given an explicit label, as most assistive technologies will otherwise not announce them, despite the presence of the correct role attribute. In the examples provided here, we use aria-label, but alternatives such as aria-labelledby can also be used.

Basic example

Wrap a series of buttons with .btn in .btn-group.

      <button type="button" class="btn btn-default">Left</button>
      <button type="button" class="btn btn-default">Middle</button>
      <button type="button" class="btn btn-default">Right</button>

{% highlight html %}

  <button type="button" class="btn btn-default">Left</button>
  <button type="button" class="btn btn-default">Middle</button>
  <button type="button" class="btn btn-default">Right</button>

{% endhighlight %}

Button toolbar

Combine sets of <div class="btn-group"> into a <div class="btn-toolbar"> for more complex components.

        <button type="button" class="btn btn-default">1</button>
        <button type="button" class="btn btn-default">2</button>
        <button type="button" class="btn btn-default">3</button>
        <button type="button" class="btn btn-default">4</button>

        <button type="button" class="btn btn-default">5</button>
        <button type="button" class="btn btn-default">6</button>
        <button type="button" class="btn btn-default">7</button>

      <button type="button" class="btn btn-default">8</button>

{% highlight html %}

...

...

  <button type="button" class="btn btn-default">...</button>

{% endhighlight %}

Button toolbar collapse

.btn-toolbar collapses to use full-width buttons on smaller screens.
    Use modifier classes to adjust the breakpoint beneath which the tollbar collapses.

{% highlight html %}

...

...

...

...

{% endhighlight %}

Sizing

Instead of applying button sizing classes to every button in a group, just add .btn-group-* to each .btn-group, including when nesting multiple groups.

      <button type="button" class="btn btn-default">Left</button>
      <button type="button" class="btn btn-default">Middle</button>
      <button type="button" class="btn btn-default">Right</button>

      <button type="button" class="btn btn-default">Left</button>
      <button type="button" class="btn btn-default">Middle</button>
      <button type="button" class="btn btn-default">Right</button>

      <button type="button" class="btn btn-default">Left</button>
      <button type="button" class="btn btn-default">Middle</button>
      <button type="button" class="btn btn-default">Right</button>

      <button type="button" class="btn btn-default">Left</button>
      <button type="button" class="btn btn-default">Middle</button>
      <button type="button" class="btn btn-default">Right</button>

{% highlight html %}

...

...

...

...

{% endhighlight %}

Nesting

Place a .btn-group within another .btn-group when you want dropdown menus mixed with a series of buttons.

      <button type="button" class="btn btn-default">1</button>
      <button type="button" class="btn btn-default">2</button>

        <button id="btnGroupDrop1" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
          Dropdown

        </button>

Dropdown link

Dropdown link

{% highlight html %}

  <button type="button" class="btn btn-default">1</button>
  <button type="button" class="btn btn-default">2</button>

    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
      Dropdown

    </button>

Dropdown link

Dropdown link

{% endhighlight %}

Vertical variation

Make a set of buttons appear vertically stacked rather than horizontally. Split button dropdowns are not supported here.

      <button type="button" class="btn btn-default">Button</button>
      <button type="button" class="btn btn-default">Button</button>

        <button id="btnGroupVerticalDrop1" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
          Dropdown

        </button>

Dropdown link

Dropdown link

      <button type="button" class="btn btn-default">Button</button>
      <button type="button" class="btn btn-default">Button</button>

        <button id="btnGroupVerticalDrop2" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
          Dropdown

        </button>

Dropdown link

Dropdown link

        <button id="btnGroupVerticalDrop3" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
          Dropdown

        </button>

Dropdown link

Dropdown link

        <button id="btnGroupVerticalDrop4" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
          Dropdown

        </button>

Dropdown link

Dropdown link

{% highlight html %}

  ...

{% endhighlight %}

Justified button groups

Make a group of buttons stretch at equal sizes to span the entire width of its parent. Also works with button dropdowns within the button group.

Handling borders

Due to the specific HTML and CSS used to justify buttons (namely display: table-cell), the borders between them are doubled. In regular button groups, margin-left: -1px is used to stack the borders instead of removing them. However, margin doesn't work with display: table-cell. As a result, depending on your customizations to Bootstrap, you may wish to remove or re-color the borders.

IE8 and borders

Internet Explorer 8 doesn't render borders on buttons in a justified button group, whether it's on <a> or <button> elements. To get around that, wrap each button in another .btn-group.

See #12476 for more information.

With <a> elements

Just wrap a series of .btns in .btn-group.btn-group-justified.

      Left
      Middle
      Right

      Left
      Middle

          Dropdown

Action

Another action

Something else here

Separated link

{% highlight html %}

  ...

{% endhighlight %}

Links acting as buttons

If the <a> elements are used to act as buttons – triggering in-page functionality, rather than navigating to another document or section within the current page – they should also be given an appropriate role="button".

With <button> elements

To use justified button groups with <button> elements, you must wrap each button in a button group. Most browsers don't properly apply our CSS for justification to <button> elements, but since we support button dropdowns, we can work around that.

        <button type="button" class="btn btn-default">Left</button>

        <button type="button" class="btn btn-default">Middle</button>

        <button type="button" class="btn btn-default">Right</button>

{% highlight html %}

    <button type="button" class="btn btn-default">Left</button>

    <button type="button" class="btn btn-default">Middle</button>

    <button type="button" class="btn btn-default">Right</button>

{% endhighlight %}


text:
require 'carto/db/migration_helper'

include Carto::Db::MigrationHelper

migration(
  Proc.new do
    alter_table :widgets do
      set_column_not_null :source_id
    end
  end,
  Proc.new do
    alter_table :widgets do
      set_column_allow_null :source_id
    end
  end
)


text:
event: Symfony Live Paris 2012
title: "Advanced Service Container Utilization "
youtube_id: hSMMMQ7iXf8
authors:
    - Richard Miller

layout: youtube
date: 2012-06-06 00:00:00
---