text:
require 'base64'
require 'redmine'
require 'json'

module RedmineDrawio
    module Macros

        Redmine::WikiFormatting::Macros.register do
            desc <<EOF
This macro is deprecated. Use the drawio_attach macro instead.
EOF

            macro :drawio do |obj, args|
                return "«The drawio macro is deprecated, use the drawio_attach macro instead»"
            end
        end

        Redmine::WikiFormatting::Macros.register do
            desc <<EOF
Macro for embedding www.draw.io diagrams stored as attachments. Example usage:

{{drawio_attach(myDiagram[, ...options...])}}

The diagram is drawn from the attachment myDiagram.png (diagram esported as png+xml);
if the attachment doesn't exists a default diagram wil be drawn. Double click it to start
editing.

Supported diagrams format are:
* png: diagram exported as png+xml (embedded source diagram)
* svg: diagram exported as svg+xml (embedded source diagram)
* xml: classic diagram xml source

Every time a diagram is saved, a new attachment will be created; for now you must
manually delete old attachments (missing Redmine API; version 3.3.0 seems to have included
an API to delete attachments but need investigation).

options:
size=number     : forced width of the diagram image, in pixels

options specific for diagrams in XML format:
tbautohide=true : show the toolbar only when the mouse is over the diagram
hilight=#0000ff : color to hilight hyperlinks
layers=false    : enable layer selector (only for multi-layer diagrams)
page=false      : enable page control (only for multi-page diagrams)
zoom=false      : enable zoom controls
lightbox=false  : enable lightbox usage
EOF

            macro :drawio_attach do |obj, args|
                return "«Please save content first»" unless obj
                return "«Drawio diagrams are available only in issues and wiki pages»" unless obj.is_a?(WikiContent) or obj.is_a?(Issue) or obj.is_a?(Journal)

                args, options = extract_macro_options(args, :size, :hilight, :tbautohide, :lightbox, :zoom, :page, :layers)
                diagramName   = RedmineDrawio::Macros.strip_non_filename_chars(args.first)

                return "«Please set a diagram name»".html_safe unless diagramName
                return "«Only png, svg and xml diagram formats are supported»".html_safe unless diagramName =~ /.*(\.(png|svg|xml))?$/i
                return "svg diagrams are disabled by the administrator" unless RedmineDrawio::Macros.svg_enabled? || not(diagramName =~ /.*\.svg$/i)

                # defalts
                hilight    = "#0000ff"
                tbautohide = true
                lightbox   = false
                size       = nil
                page       = 0
                layers     = ''
                zoom       = false

                size = options[:size].to_i unless options[:size].blank? or not options[:size][/^\d+$/]
                # parameters checkings
                hilight    = options[:hilight]            unless options[:hilight].blank?
                tbautohide = options[:tbautohide].to_bool unless options[:tbautohide].blank?
                lightbox   = options[:lightbox].to_bool   unless options[:lightbox].blank?
                #size       = options[:fit].to_i           unless options[:fit].blank?
                zoom       = options[:zoom].to_bool       unless options[:zoom].blank?
                page       = options[:page].to_i          unless options[:page].blank?
                layers     = options[:layers]             unless options[:layers].blank?

                inlineStyle = ""
                inlineStyle = "width:#{size}px;" if size

                if obj.is_a?(WikiContent)
                    container = obj.page
                    title     = container.title
                    canEdit   = User.current.allowed_to?(:edit_wiki_pages, @project)
                elsif obj.is_a?(Journal)
                    container = obj
                    title     = nil  # not necessary
                    canEdit   = container.editable_by?(User.current)
                else
                    container = obj
                    title     = nil  # not necessary
                    canEdit   = container.editable?(User.current)
                end

                # Add an extension, if missing
                diagramName += ".png" if File.extname(diagramName.strip) == ""
                diagramExt  = File.extname(diagramName.strip)

                # Search attachment position
                attach = container.attachments.select { |attachment| attachment.filename == diagramName } .last

                if canEdit
                    # Diagram and document are editable
                    if Redmine::Plugin.installed?(:easy_redmine)
                        # EasyRedmine can update the attachment without duplications
                        saveName = diagramName
                    else
                        if diagramName =~ /_\d+\./
                            saveName = diagramName.sub(/_(\d+)/) {|v| v.next } # increment version
                        else
                            saveName = diagramName.sub(/(\.\w+)$/, '_1\1') # set version to _1
                        end
                    end
                else
                    # Diagram cannot be saved, it will become not editable
                    saveName = nil
                end

                if attach
                    filename = attach.diskfile
                else
                    filename = RedmineDrawio::Macros.imagePath('defaultImage'+diagramExt)
                end

                if attach && RedmineDrawio::Macros.pdf?(self.controller)
                  url = download_named_attachment_url(attach, attach.filename, :only_path => true )
                  return ActionController::Base.helpers.image_tag(url, :style => "#{inlineStyle}")
                end

                diagram = File.read(filename, mode: 'rb')

                if RedmineDrawio::Macros.svg? diagramName
                    return RedmineDrawio::Macros.encapsulateSvg(RedmineDrawio::Macros.adaptSvg(diagram, size), inlineStyle, diagramName, title, saveName, false)
                elsif RedmineDrawio::Macros.png? diagramName
                    # if png, encode image and remove newlines (required by Internet Explorer)
                    diagram = Base64.encode64(diagram).gsub("\n", '')
                    return RedmineDrawio::Macros.encapsulatePng(diagram, inlineStyle, diagramName, title, saveName, false)
                else
                    tb = []
                    tb << 'pages'    unless options[:page].blank?
                    tb << 'layers'   unless layers.blank?
                    tb << 'zoom'     if zoom
                    tb << 'lightbox' if lightbox

                    toolbar = if tb.empty? then nil else tb.join(' ') end
                    #style   = if size then 'style="max-width:'+size+'px;"' else "" end

                    # https://desk.draw.io/support/solutions/articles/16000042542-embed-html
                    # https://desk.draw.io/support/solutions/articles/16000042544-embed-mode
                    graphOpts = {
                        'highlight'      => hilight,
                        'nav'            => false,
                        'edit'           => '_blank',
                        'lightbox'       => lightbox,
                        'resize'         => true,
                        'auto-fit'       => true,
                        'editable'       => false,
                        ##'zoom'           => zoom,
                        'page'           => page,
                        'layers'         => if layers == '*' then nil else layers end,
                        'toolbar-nohide' => (not tbautohide),
                        'toolbar'        => toolbar,
                        'xml'            => diagram
                    }
                    return RedmineDrawio::Macros.encapsulateXml(graphOpts, inlineStyle, diagramName, title, saveName, false)
                end
            end
        end

        if Redmine::Plugin.installed?(:redmine_dmsf)
            Redmine::WikiFormatting::Macros.register do
                desc <<EOF
Macro for embedding www.draw.io diagrams stored as DMSF documents. Example usage:

{{drawio_dmsf(myDiagram[, ...options...])}}

The diagram is drawn from the DMSF document myDiagram.png(diagram esported as png+xml);
if the attachment doesn't exists a default diagram wil be drawn. Double click it to start
editing.

Supported diagrams format are:
* png: diagram exported as png+xml (embedded source diagram)
* svg: diagram exported as svg+xml (embedded source diagram)
* xml: classic diagram xml source

The diagram name can contain a path. For example:

{{drawio_dmsf(path/to/folder/myDiagram.svg)}}

will create/edit the document myDiagram.svg in the DMSF folder path/to/folder of
the current project (the folder must exists).

options:
size=number     : forced width of the diagram image, in pixels

options specific for diagrams in XML format:
tbautohide=true : show the toolbar only when the mouse is over the diagram
hilight=#0000ff : color to hilight hyperlinks
layers=false    : enable layer selector (only for multi-layer diagrams)
page=false      : enable page control (only for multi-page diagrams)
zoom=false      : enable zoom controls
lightbox=false  : enable lightbox usage
EOF

                macro :drawio_dmsf do |obj, args|
                    return "«Please save content first»" unless obj
                    return "«Drawio diagrams are available only in issues and wiki pages»" unless obj.is_a?(WikiContent) or obj.is_a?(Issue) or obj.is_a?(Journal)

                    args, options = extract_macro_options(args, :size, :hilight, :tbautohide, :lightbox, :zoom, :page, :layers)
                    diagramName   = RedmineDrawio::Macros.strip_non_filename_chars(args.first).force_encoding("UTF-8")

                    return "«Please set a diagram name»".html_safe unless diagramName
                    return "«Only png and svg diagram formats are supported»".html_safe unless diagramName =~ /.*(\.(png|svg))?$/i
                    return "svg diagrams are disabled by the administrator" unless RedmineDrawio::Macros.svg_enabled? || not(diagramName =~ /.*\.svg$/i)

                    # Add an extension, if missing
                    diagramName += ".png" if File.extname(diagramName.strip) == ""
                    diagramExt  = File.extname(diagramName.strip)

                    size = options[:size].to_i unless options[:size].blank? or not options[:size][/^\d+$/]
                    # parameters checkings
                    hilight    = options[:hilight]            unless options[:hilight].blank?
                    tbautohide = options[:tbautohide].to_bool unless options[:tbautohide].blank?
                    lightbox   = options[:lightbox].to_bool   unless options[:lightbox].blank?
                    #size       = options[:fit].to_i           unless options[:fit].blank?
                    zoom       = options[:zoom].to_bool       unless options[:zoom].blank?
                    page       = options[:page].to_i          unless options[:page].blank?
                    layers     = options[:layers]             unless options[:layers].blank?

                    inlineStyle = ""
                    inlineStyle = "width:#{size}px;" if size

                    if obj.is_a?(WikiContent)
                        container = obj.page
                        title     = container.title
                        project   = container.wiki.project
                        canEdit   = User.current.allowed_to?(:edit_wiki_pages, @project)
                    elsif obj.is_a?(Journal)
                        container = obj
                        title     = nil # not necessary
                        project   = container.project
                        canEdit   = container.editable_by?(User.current)
                    else
                        container = obj
                        title     = nil # not necessary
                        project   = container.project
                        canEdit   = container.editable?(User.current)
                    end

                    # Search the DMSF folder containing the diagram
                    folderName = File.dirname(diagramName)
                    folder     = RedmineDrawio::Helpers::DrawioDmsfHelper.deep_folder_search(project, folderName)

                    # Search the document in DMSF
                    file = DmsfFile.find_file_by_name project, folder, File.basename(diagramName)

                    if canEdit
                        # Diagram and document are editable
                        saveName = RedmineDrawio::Macros.dmsf_save_name project, diagramName
                    else
                        # Diagram cannot be saved, it will become not editable
                        saveName = nil
                    end

                    if file
                        # Document exists, get the file path
                        filename = file.last_revision.disk_file project
                        canEdit  = canEdit && User.current && User.current.allowed_to?(:file_manipulation, file.project)
                    else
                        # Document does not exists: use a predefined diagram to start editing
                        filename = RedmineDrawio::Macros.imagePath('defaultImage'+diagramExt)
                        canEdit  = canEdit && User.current && User.current.allowed_to?(:file_manipulation, project)
                    end

                    diagram = File.read(filename, mode: 'rb')

                    if file && RedmineDrawio::Macros.pdf?(self.controller)
                        member = Member.find_by(user_id: User.current.id, project_id: file.project.id)
                        filename = file.last_revision.formatted_name(member)
                        url = static_dmsf_file_url(file, filename, :only_path => true)
                        return ActionController::Base.helpers.image_tag(url, :style => "#{inlineStyle}")
                    end

                    if RedmineDrawio::Macros.svg? diagramName
                        return RedmineDrawio::Macros.encapsulateSvg(RedmineDrawio::Macros.adaptSvg(diagram, size), inlineStyle, diagramName, title, saveName, true)
                    elsif RedmineDrawio::Macros.png? diagramName
                        # if png, encode image and remove newlines (required by Internet Explorer)
                        diagram = Base64.encode64(diagram).gsub("\n", '')
                        return RedmineDrawio::Macros.encapsulatePng(diagram, inlineStyle, diagramName, title, saveName, true)
                    else
                        tb = []
                        tb << 'pages'    unless options[:page].blank?
                        tb << 'layers'   unless layers.blank?
                        tb << 'zoom'     if zoom
                        tb << 'lightbox' if lightbox

                        toolbar = if tb.empty? then nil else tb.join(' ') end
                        #style   = if size then 'style="max-width:'+size+'px;"' else "" end

                        graphOpts = {
                            'highlight'      => hilight,
                            'nav'            => false,
                            'edit'           => '_blank',
                            'lightbox'       => lightbox,
                            'resize'         => true,
                            'auto-fit'       => true,
                            'editable'       => false,
                            ##'zoom'           => zoom,
                            'page'           => page,
                            'layers'         => if layers == '*' then nil else layers end,
                            'toolbar-nohide' => (not tbautohide),
                            'toolbar'        => toolbar,
                            'xml'            => diagram
                        }
                        return RedmineDrawio::Macros.encapsulateXml(graphOpts, inlineStyle, diagramName, title, saveName, false)
                    end
                end
            end
        end

        class << self
            def drawio_url
                return '//embed.diagrams.net' if Setting.plugin_redmine_drawio['drawio_service_url'].to_s.strip.empty?
                Setting.plugin_redmine_drawio['drawio_service_url']
            end

            def dmsf_version
                Redmine::Plugin.find(:redmine_dmsf).version
            end

            def dmsf_save_name(project, diagramName)
                if Setting.plugin_redmine_dmsf['dmsf_webdav_use_project_names']
                    Rails.logger.error "dmsf_version=#{RedmineDrawio::Macros.dmsf_version}"

                    if RedmineDrawio::Macros.dmsf_version <= '1.5.8'
                        # Prior to DMSF 1.5.9 project names cannot be used for folder names
                        "#{project.id}/#{diagramName}"
                    elsif RedmineDrawio::Macros.dmsf_version <= '1.6.0'
                        # DMSF 1.5.9+ can use project name as folder
                        "#{project.name} -#{project.id}-/#{diagramName}"
                    else
                        # With DMSF 1.6.1+ the path is changed
                        "#{project.name} #{project.id}/#{diagramName}"
                    end
                else
                    "#{project.identifier}/#{diagramName}"
                end
            end

            def imagePath(defaultImage)
                File.expand_path(File.join(File.dirname(__FILE__), '../../spec', defaultImage))
            end

            def adaptSvg(svg, size)
                # Remove some scripts from the SVG (prevent some XSS issues)
                localSvg = svg.sub(/(?:<script\b[^>]*>(?:.*?)<\/script>)|(?:\\s*javascript:.*\))|(?:\\bon\w+.*?=[^>]+)|(?:src=.?(&#x?[0-9a-f]+)+)/i, '')
                # Adapt SVG to make it resizable
                localSvg = localSvg.sub(/<svg /, '<svg preserve_aspect_ratio="xMaxYMax meet" ') unless svg =~ /.* preserve_aspect_ratio=.*/
                localSvg = localSvg.sub(/<svg /, '<svg style="max-width:100%" ')
                # Add a viewBox, if missing
                localSvg = localSvg.sub(/<svg (.*) width="([0-9]+)px" height="([0-9]+)px"/,
                                            '<svg viewBox="0 0 \2 \3" \1') unless localSvg=~ /.* viewBox="(.*)"/
                # Fix size, if forced
                if localSvg =~ /<svg (.*) width="(?:[0-9]+)px"/
                    # width attribute presente, replace it with fized size, if present
                    localSvg = localSvg.sub(/<svg (.*) width="(?:[0-9]+)px"/, "<svg \1 width=\"#{size}\"") unless size.nil?
                elsif size.nil?
                    # no forced size and no width attribute: in no height, try to extract size from viewbox
                    localSvg = localSvg.sub(/<svg (.*) viewBox="([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)"/,
                                            '<svg \1 viewBox="\2 \3 \4 \5" width="\4px"') if localSvg =~ /.* viewBox=".*"/
                else
                    # no width attribute, but the height attribute may be present: replace it with the fixed size, if present
                    localSvg = localSvg.sub(/<svg ([^>]+?)(?: height="([0-9]+)px")?/, "<svg \1 width=\"#{size}\"")
                end

                localSvg
            end

            def encapsulateSvg(svg, inlineStyle, diagramName, title, saveName, isDmsf)
                dblClick = ""
                tooltip  = ""
                style    = ""
                style    = inlineStyle unless inlineStyle.blank?

                unless saveName.nil?
                    tagType  = if Setting.plugin_redmine_drawio['drawio_svg_enabled'] then 'svg' else 'img' end
                    dblClick = " ondblclick=\"editDiagram($(this).find('#{tagType}')[0],'#{saveName}',#{isDmsf}, '#{RedmineDrawio::Macros.js_safe(title)}', '#{diagramName}');\""
                    tooltip  = " title='Double click to edit diagram'"
                    style    = " style='#{inlineStyle}cursor:pointer'"
                end

                if Setting.plugin_redmine_drawio['drawio_svg_enabled']
                    "<span class='drawioDiagram'#{style}#{tooltip}#{dblClick}>#{svg.force_encoding("UTF-8")}</span>".html_safe
                else
                    "<span class='drawioDiagram'#{style}#{tooltip}#{dblClick}><img src='data:image/svg+xml;base64,#{Base64.strict_encode64(svg.force_encoding("UTF-8"))}'></span>".html_safe
                end
            end

            def encapsulatePng(png, inlineStyle, diagramName, title, saveName, isDmsf)
                if saveName.nil?
                    return ActionController::Base.helpers.image_tag("data:image/png;charset=utf-8;base64,#{png}",
                                    :alt   => "Diagram #{diagramName}",
                                    :class => "drawioDiagram",
                                    :style => "#{inlineStyle}")
                else
                    return ActionController::Base.helpers.image_tag("data:image/png;charset=utf-8;base64,#{png}",
                                    :alt        => "Diagram #{diagramName}",
                                    :title      => "Double click to edit diagram",
                                    :class      => "drawioDiagram",
                                    :style      => "#{inlineStyle}cursor:pointer;",
                                    :ondblclick => "editDiagram(this,'#{saveName}', #{isDmsf}, '#{RedmineDrawio::Macros.js_safe(title)}', '#{diagramName}');")
                end
            end

            def encapsulateXml(graphOpts, inlineStyle, diagramName, title, saveName, isDmsf)
                randomId = 'dg_'+('a'..'z').to_a.shuffle[0,8].join

                unless saveName.nil?
                    # Diagram is editable, add toolbar declarations for editing
                    graphOpts['toolbar'] = "#{graphOpts['toolbar']} edit"
                    graphOpts['toolbar-buttons'] = {
                        'edit' => {
                            'title'   => 'Edit',
                            'handler' => "(function(){editDiagram($('##{randomId}'),'#{saveName}', #{isDmsf}, '#{RedmineDrawio::Macros.js_safe(title)}', '#{diagramName}');})",
                            'image'   => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAQAAAADHm0dAAAAbUlEQVQoz93NoRGAMBAAwXNIZCQlUEZKoQRkOqAESqAEJBIZiURGYh/DhKjPS4bTO3Pw2TwrK2MdOhKCIAQdtkD/4KTBwEGX8aVBQQq86LDErgZfbIAKHayw4bTOvRXCZIUQM9x1CBtCZMbzi25WtlGUbURavAAAAABJRU5ErkJggg==',
                        }
                    }
                end

                tag = "<div id=\"#{randomId}\" class=\"mxgraph\" data-mxgraph=\"#{CGI::escapeHTML(JSON.generate(graphOpts))}\"></div>".html_safe

                return tag if inlineStyle.empty?

                return "<div style=\"#{inlineStyle}\">#{tag}</div>".html_safe
            end

            def svg?(diagramName)
                diagramName =~ /\.svg$/i
            end

            def png?(diagramName)
                diagramName =~ /\.png$/i
            end

            def strip_non_filename_chars(filename)
                # Replace directory separator from \ to /
                filename = filename.gsub(/\\/, '/')
                return filename.gsub(/[\x00:*?"'<>|,;]/, '_') if Gem.win_platform?
                # *nix
                filename.gsub(/[,;|"']/, '_')
            end

            def js_safe(string)
                string.gsub(/'/){ %q(\') } if string
                ''
            end

            def svg_enabled?
                RedmineDrawio::Helpers::DrawioSettingsHelper.svg_enabled?
            end

            def pdf?(controller)
                controller.params[:format] == "pdf"
            end

        end
    end
end


text:
<?php declare(strict_types=1);

namespace Koldy;

/**
 * The Koldy root exception.
 *
 */
class Exception extends \Exception
{

}

redpajama_set_name: RedPajamaGithub


text:
// Generated by genprov 1.2.5
#include "Buzzer_Provider.h"
#include "log.h"

CIMPLE_NAMESPACE_BEGIN

static void _send(
    Indication_Handler<Buzzer>* handler,
    const String& key,
    const String& message)
{
    Buzzer* buzzer = Buzzer::create();
    buzzer->key.set(key);
    buzzer->message.set(message);
    handler->handle(buzzer);
}

Buzzer_Provider::Buzzer_Provider() : _indication_handler(0)
{
}

Buzzer_Provider::~Buzzer_Provider()
{
}

Load_Status Buzzer_Provider::load()
{
    return LOAD_OK;
}

Unload_Status Buzzer_Provider::unload()
{
    return UNLOAD_OK;
}

Enable_Indications_Status Buzzer_Provider::enable_indications(
    Indication_Handler<Buzzer>* indication_handler)
{
    __log("Buzzer_Provider::enable_indications()");

    _indication_handler = indication_handler;

    return ENABLE_INDICATIONS_OK;
}

Disable_Indications_Status Buzzer_Provider::disable_indications()
{
    __log("Buzzer_Provider::disable_indications()");

    if (_indication_handler)
    {
        delete _indication_handler;
        _indication_handler = 0;
    }

    return DISABLE_INDICATIONS_OK;
}

Invoke_Method_Status Buzzer_Provider::trigger(
    Property<uint32>& return_value)

{
    if (_indication_handler)
    {
        _send(_indication_handler, "YELLOW", "400");
    }

    return INVOKE_METHOD_OK;
}

/*@END@*/

CIMPLE_NAMESPACE_END


text:
layout: home
excerpt: Software Developer. Podcaster. Home Barista. Runner. Photographer. Aspiring Stoic. Incurably curious. Not necessarily in that order.
tags: [miha, rekar, ruby, develper, php, event, photography]
image:
  feature: features/ultra-fire.jpg
  credit: Miha Rekar - Fire @ Ultra 2014
  creditlink: https://mr.si/
---


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using XenAdmin.Plugins;
using XenAdmin;

namespace XenAdminTests.PluginTests
{
    internal class TestPluginLoader : IDisposable
    {
        private readonly string _name;
        private readonly string _xml;
        private readonly PluginManager _pluginManager;
        private string _fullFolder;

        public TestPluginLoader(string name, PluginManager pluginManager)
        {
            _name = name;
            _pluginManager = pluginManager;
        }

        public TestPluginLoader(string name, PluginManager pluginManager, string xml)
            : this(name, pluginManager)
        {
            _xml = xml;
        }

        public void Load()
        {
            string tempPath = Path.GetTempPath();
            string pluginsFolder = Guid.NewGuid().ToString();
            string vendorDir = "plugin-vendor";

            _fullFolder = tempPath + "\\" + pluginsFolder + "\\" + vendorDir + "\\" + _name;
            string fullFile = _fullFolder + "\\" + _name + ".xcplugin.xml";

            Directory.CreateDirectory(_fullFolder);

            if (_xml == null)
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                Stream s = assembly.GetManifestResourceStream("XenAdminTests.TestResources.PluginResources." + _name + ".xcplugin.xml");

                byte[] bytes = new byte[s.Length];
                s.Read(bytes, 0, bytes.Length);

                File.WriteAllBytes(fullFile, bytes);
            }
            else
            {
                File.WriteAllText(fullFile, _xml);
            }

            _pluginManager.LoadPlugins(tempPath + "\\" + pluginsFolder);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (Directory.Exists(_fullFolder))
            {
                Directory.Delete(_fullFolder, true);
            }
        }

        #endregion
    }
}


text:
require_app_root_dir

function sql-copy_help {
  cat << EOF
Make PostgreSQL database copy using pg_dump
Note: For development use only. Doesn't handle big databases

boo sql-copy server_name
EOF
}

function sql-copy {
  local server_name=$1

  source_deploy_conf ${server_name}

  . ${BOO_ROOT_PATH}/sql.sh

  start_sql_proxy

  echo "Making DB copy..."
  pg_dump "${POSTGRE_PROXY_URL}" > "${dump_dir}/${server_name}.sql"
  exit_res="$?"

  stop_sql_proxy

  if [ "$exit_res" = "0" ]; then
    echo_success "Done!"
  else
    echo_error "Failed!"
    exit "$exit_res"
  fi
}


text:
import * as Bitrate from '../src/parser/bitrate';

describe('updateEstimatedBitrate', () => {
  beforeEach(() => {
    Bitrate.estimatedBitrate = 0;
  });

  it('does not update estimated bitrate if one value is missing', () => {
    Bitrate.updateEstimatedBitrate(1000, null);
    expect(Bitrate.estimatedBitrate).toEqual(0);
    Bitrate.updateEstimatedBitrate(null, 1234);
    expect(Bitrate.estimatedBitrate).toEqual(0);
  });

  it('does not update estimated bitrate if one value is negative', () => {
    Bitrate.updateEstimatedBitrate(1000, -12);
    expect(Bitrate.estimatedBitrate).toEqual(0);
    Bitrate.updateEstimatedBitrate(-243, 1234);
    expect(Bitrate.estimatedBitrate).toEqual(0);
  });

  it('updates estimated bitrate if values are both positive and make the average from cumulated values', () => {
    Bitrate.updateEstimatedBitrate(1000, 200);
    expect(Bitrate.estimatedBitrate).toEqual(40);
    Bitrate.updateEstimatedBitrate(100, 200);
    expect(Bitrate.estimatedBitrate).toEqual(22);
    Bitrate.updateEstimatedBitrate(2050, 200);
    expect(Bitrate.estimatedBitrate).toEqual(42);
  });
});


text:
package org.droidparts.test;

import android.content.Context;

import org.droidparts.AbstractDependencyProvider;
import org.droidparts.test.persist.DBOpenHelper;

public class DependencyProvider extends AbstractDependencyProvider {

	private DBOpenHelper dbOpenHelper;

	public DependencyProvider(Context ctx) {
		super(ctx);
		dbOpenHelper = new DBOpenHelper(ctx);
	}

	@Override
	public DBOpenHelper getDBOpenHelper() {
		return dbOpenHelper;
	}

}


text:
By Yunzhu Li, Jiaming Song, Stefano Ermon

### Introduction

Modified codebase of TORCS, with the ability to extract dashboard views.

InfoGAIL implementation, attached with two examples: *pass* & *turn*.

### Citing InfoGAIL

If you find this codebase useful in your research, please consider citing:

	@article{li2017inferring,
  	    title={InfoGAIL: Interpretable Imitation Learning from Visual Demonstrations},
  	    author={Li, Yunzhu and Song, Jiaming and Ermon, Stefano},
  	    journal={arXiv preprint arXiv:1703.08840},
  	    year={2017}
	}

### Requirements

1. Python 2.7
2. Tensorflow 0.12.1
3. Keras 1.2.2
4. xautomation

### Install and Configure TORCS

In the following section, we only show the commands for running example 0 (indicating *pass*). Users can replace 0 with 1 to run example 1 (indicating *turn*).

1. Install all the dependencies of TORCS, including but not limited to:

```
sudo apt-get install libplib-dev
sudo apt-get install libopenal-dev
sudo apt-get install libalut-dev
```

See http://torcs.sourceforge.net/ for more information

2. cd to the `torcs-1.3.4/` folder, type the following commands to install TORCS:

```
./configure
make
sudo make install
sudo make datainstall
```

Default installation directories are:

```
/usr/local/bin
/usr/local/lib/torcs
/usr/local/share/games/torcs
```

Run the `torcs` command to play TORCS.

3. Copy the modified tracks files in the `modified_tracks/` folder to the torcs folder `/usr/local/share/games/torcs/tracks/road`
4. Type the following commands to configure the running environment:

```
rm -rf ~/.torcs
cp -r torcs_config_ai_0 ~/.torcs
```

### Download training data and pretrained weights

1. Training data
- example 0 *(pass)* [DropBox](https://www.dropbox.com/s/4tbwvidrb1l5p7v/human_0.zip?dl=0)
- example 1 *(turn)* [DropBox](https://www.dropbox.com/s/0c93lxrwvg5kze1/human_1.zip?dl=0)

2. Pretrained weights
- example 0 [DropBox](https://www.dropbox.com/s/e8f8cv11eoavpji/wgail_info_params_0.zip?dl=0)
- example 1 [DropBox](https://www.dropbox.com/s/oagd8uc94au5tjf/wgail_info_params_1.zip?dl=0)

### Run with pretrained weights

1. cd to `wgail_info_0/`

2. open `drive.py` and edit line 20-21 in concert with downloaded data and weights

3. change variable `code` in line 14 into different values (`0` or `1`) to observe different behaviors

4. type the `python drive.py` to run *pass* with pretrained weights

   Run *pass* with different latent codes (`0` or `1`):

   ![](pass_code_0.gif) ![](pass_code_1.gif)

   Run *turn* with different latent codes (`0` or `1`):

   ![](turn_code_1.gif) ![](turn_code_0.gif)

### Training

1. cd to `wgail_info_0/`
2. open `wgail_info.py` and edit line 17-19 in concert with downloaded data and weights
3. open `models.py` and edit line 508 to specify the place to store the weights, edit line 422 to specify the place to store the log file
4. type `python wgail_info.py` to train on *pass*, note that the weights trained via behavior cloning are used to initialize the policy network

### Misc.

1. Track selection:
   * *pass*: chenyi-Street 1
   * *turn*: chenyi-Brondehach

2. torcs-1.3.4 in this repository is a modified version of the original codebase released by Bernhard Wymann. This version holds the ability of extracting and transmitting visual information.

### References

[DeepDriving](http://deepdriving.cs.princeton.edu/)

[Using Keras and Deep Deterministic Policy Gradient to play TORCS](https://yanpanlau.github.io/2016/10/11/Torcs-Keras.html)

[TORCS - The Open Race Car Simulator](http://xed.ch/h/torcs.html)

[SnakeOil](http://xed.ch/project/snakeoil/index.html)

[Simulated Car Racing Championship Competition Software Manual](https://pdfs.semanticscholar.org/9b1d/e5d93854d9dc364a4bc6a462193ccc3ea895.pdf)


text:
export class Team {
  public members: Member[];

  constructor(public id: number, public name: string, members: {name: string}[], public host = '', public lang = '') {
    this.members = members.map((member) => {
      return new Member(member.name);
    });
  }

  countFreeMembers() {
    return 3 - this.members.length;
  }
}

class Member {
  constructor(public name: string) {}

  get icon() {
    // change here
    return 'https://s.yimg.jp/images/riff/3.10.0/images/icon/png/user_box.png';
  }
}


text:
//package org.springlearning.aop.dynamic_data_source.aspect;
//
//import java.util.Iterator;
//import java.util.List;
//
//import org.apache.ibatis.annotations.Param;
//import org.aspectj.lang.JoinPoint;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Before;
//import org.aspectj.lang.annotation.Pointcut;
//import org.springframework.stereotype.Component;
//
//import com.google.common.collect.Lists;
//
//import org.springlearning.aop.dynamic_data_source.ContextDataSourceKeyHolder;
//import org.springlearning.aop.dynamic_data_source.aspect.exception.ServiceException;
//
//import com.yanke.backend.api.dal.model.IndexUserPhone;
//import com.yanke.backend.api.dal.model.IndexUserPhoneExample;
//import com.yanke.backend.api.dal.model.IndexUserPhoneExample.Criteria;
//import com.yanke.backend.api.dal.model.IndexUserPhoneExample.Criterion;
//
//
////@Aspect
////@Component
//public class DynamicDataSourceAspect {
//
//	public final static String modelClassName = "com.yanke.backend.api.dal.model.IndexUserPhone";
//	public final static String modelExampleClassName = "com.yanke.backend.api.dal.model.IndexUserPhoneExample";
///*
//   @Pointcut("execution (public com.yanke.backend.api.dal.dao.IndexUserPhoneMapper.insert(..)")
//    public void insertPointcut(){}
//
//    @Before("serviceExecution()")
//    public void setDynamicDataSource(JoinPoint jp) {
//        for(Object o : jp.getArgs()) {
//            //处理具体的逻辑 ,根据具体的境况CustomerContextHolder.setCustomerType()选取DataSource
//        }
//    }
//*/
//
//	@Around(value="execution(public * com.yanke.backend.api.dal.dao.IndexUserPhoneMapper.insert("+modelClassName+")) && args(indexUserPhone)",argNames="indexUserPhone")
//	public Object applyOnInsert(ProceedingJoinPoint joinPoint,IndexUserPhone indexUserPhone) throws Throwable {
//		System.out.println("---------------------------------");
//		System.out.println("joinPoint.getTarget()="+joinPoint.getTarget());
//		System.out.println("joinPoint.getSignature().getName()="+joinPoint.getSignature().getName());
//        for(Object o : joinPoint.getArgs()) {
//    		System.out.println("arg-"+o);
//        }
//        System.out.println("---------------------------------");
//      /**
//      //另一种实现方式:使用策略模式
//      //1.根据UserGameInfo.uid 进行数据源路由选择
//      //DataSourceRouter.setRouterStrategy(
//      //          RouterStrategy.SRATEGY_TYPE_CLUSTER ,
//      //          null,
//      //         userGameInfo.getUid());
//      */
//		Integer result = -1;
//		try{
//			ContextDataSourceKeyHolder.setDataSourceKey(indexUserPhone.getMobilePhoneNumber());
//			result = (Integer)joinPoint.proceed();
//		}
//		catch (Throwable throwable) {
//			throw new ServiceException("IndexUserPhoneMapper.insert Aspect Exception,Reason:"+throwable.getMessage(),throwable);
//		}
//		return result;
//
//	}
//
//
//	@Before(value="execution(public java.util.List<"+modelClassName+"> com.yanke.backend.api.dal.dao.IndexUserPhoneMapper.selectByExample("+modelExampleClassName+")) && args(example)",argNames="example")
//	public void applyOnSelectByExample(IndexUserPhoneExample example) throws Throwable {
//
//		try{
//			boolean hasMobilePhoneNumberClause = false;
//			Iterator<Criteria> iterator = example.getOredCriteria().iterator();
//			while(iterator.hasNext()){
//				List<Criterion> getCriteriaResult =  iterator.next().getCriteria();
//				for(Criterion criterion:getCriteriaResult){
//					//mobile_phone_number =
//					if(criterion.isSingleValue() && criterion.getCondition().contains("mobile_phone_number")){
//						ContextDataSourceKeyHolder.setDataSourceKey(String.valueOf(criterion.getValue()));
//						hasMobilePhoneNumberClause = true;
//					}
//				}
//			}
//			if(!hasMobilePhoneNumberClause){
//				throw new IllegalArgumentException("no mobile_phone_number in query parmameter");
//			}
//		}
//		catch (Throwable throwable) {
//			throw new ServiceException("IndexUserPhoneMapper.selectByExample Aspect Exception,Reason:"+throwable.getMessage(),throwable);
//		}
//
//
//	}
//
//	@Before(value="execution(public * com.yanke.backend.api.dal.dao.IndexUserPhoneMapper.updateByExampleSelective("+modelClassName+","+modelExampleClassName+")) && args(model,example)",argNames="model,example")
//	public void applyOnUpdateByExampleSelective(IndexUserPhone model,IndexUserPhoneExample example) throws Throwable {
//
//		try{
//			boolean hasMobilePhoneNumberClause = false;
//			Iterator<Criteria> iterator = example.getOredCriteria().iterator();
//			while(iterator.hasNext()){
//				List<Criterion> getCriteriaResult =  iterator.next().getCriteria();
//				for(Criterion criterion:getCriteriaResult){
//					//mobile_phone_number =
//					if(criterion.isSingleValue() && criterion.getCondition().contains("mobile_phone_number")){
//						ContextDataSourceKeyHolder.setDataSourceKey(String.valueOf(criterion.getValue()));
//						hasMobilePhoneNumberClause = true;
//					}
//				}
//			}
//			if(!hasMobilePhoneNumberClause){
//				throw new IllegalArgumentException("no mobile_phone_number in update parmameter");
//			}
//		}
//		catch (Throwable throwable) {
//			throw new ServiceException("IndexUserPhoneMapper.updateByExampleSelective Aspect Exception,Reason:"+throwable.getMessage(),throwable);
//		}
//
//
//	}
//
//
//
//}