text:
package com.dysania.artofandroid.chapter11;

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by DysaniazzZ on 14/07/2017.
 */

public class LocalIntentService extends IntentService {

    private static final String TAG = "LocalIntentService";

    public LocalIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String action = intent.getStringExtra("task_action");
        Log.d(TAG, "receive action: " + action);
        SystemClock.sleep(2000);
        if (MainActivity.ACTION_TASK01.equals(action)) {
            //TODO 这里执行后台任务
            Log.d(TAG, "handle task: " + action);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //所有任务执行完后,会自动停止服务
        Log.d(TAG, "LocalIntentService destroyed");
    }
}


text:
layout: page
title: About
permalink: /about/
feature-img: "img/coast.jpg"
---

I'm a full stack web developer and part time graphic designer living in Sydney, New South Wales.

I am looking for an opportunity to grow my skill set as well as help businesses develop their online presence. Aside from web development, my hobbies include:

* Hiking
* Basketball
* Coding
* Photography

redpajama_set_name: RedPajamaGithub


text:
/**
 * @ngdoc service
 * @name ngCordovaMocks.cordovaGlobalization
 *
 * @description
 * A service for testing features related to a user's locale and timezone.
 * in an app build with ngCordova.
 */
ngCordovaMocks.factory('$cordovaGlobalization', ['$q', function ($q) {
  var throwsError = false;
  var language = (navigator.language) ? navigator.language : 'en-US';
  var preferredLanguage = {value: language};
  var firstDayOfWeek = 'Sunday';
  var localeName = {value: language};

  return {
    /**
     * @ngdoc property
     * @name throwsError
     * @propertyOf ngCordovaMocks.cordovaGlobalization
     *
     * @description
     * A flag that signals whether a promise should be rejected or not.
     * This property should only be used in automated tests.
     **/
    throwsError: throwsError,

    /**
     * @ngdoc property
     * @name preferredLanguage
     * @propertyOf ngCordovaMocks.cordovaGlobalization
     *
     * @description
     * The user's preferred language.
     * This property should only be used in automated tests.
     **/
    preferredLanguage: preferredLanguage,

    /**
     * @ngdoc property
     * @name localeName
     * @propertyOf ngCordovaMocks.cordovaGlobalization
     *
     * @description
     * The name of the user's locale.
     * This property should only be used in automated tests.
     **/
    localeName: localeName,

    /**
     * @ngdoc property
     * @name firstDayOfWeek
     * @propertyOf ngCordovaMocks.cordovaGlobalization
     *
     * @description
     * The first day of the week based on the user's locale.
     * This property should only be used in automated tests.
     **/
    firstDayOfWeek: firstDayOfWeek,

    getPreferredLanguage: function () {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting the preferred language.');
      } else {
        defer.resolve(this.preferredLanguage);
      }

      return defer.promise;
    },

    getLocaleName: function () {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting the locale name.');
      } else {
        defer.resolve(this.localeName);
      }

      return defer.promise;
    },

    getFirstDayOfWeek: function () {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting the first day of week.');
      } else {
        defer.resolve(this.firstDayOfWeek);
      }

      return defer.promise;
    },

    dateToString: function (date, options) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting the string from the date.');
      } else {
        var result = '';

        // TODO: Review
        date = date;
        options = options;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    stringToDate: function (dateString, options) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting the date from the string.');
      } else {
        var result = '';

        // TODO: Review
        dateString = dateString;
        options = options;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    getDatePattern: function (options) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting the date pattern.');
      } else {
        var result = '';

        // TODO: Review
        options = options;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    getDateNames: function (options) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting the date names.');
      } else {
        var result = '';

        // TODO: Review
        options = options;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    isDayLightSavingsTime: function (date) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error getting if this is in daylight savings time mode.');
      } else {
        var result = '';

        // TODO: Review
        date = date;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    numberToString: function (number, options) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error convertng the number to a string.');
      } else {
        var result = '';

        // TODO: Review
        number = number;
        options = options;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    stringToNumber: function (numberString, options) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error convertng the string to a number.');
      } else {
        var result = '';

        // TODO: Review
        options = options;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    getNumberPattern: function (options) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error convertng the string to a number.');
      } else {
        var result = '';

        // TODO: Review
        options = options;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    },

    getCurrencyPattern: function (currencyCode) {
      var defer = $q.defer();
      if (this.throwsError) {
        defer.reject('There was an error convertng the string to a number.');
      } else {
        var result = '';

        // TODO: Review
        currencyCode = currencyCode;

        // END TODO: Review

        defer.resolve(result);
      }

      return defer.promise;
    }
  };
}]);


text:
function [alignedF, alignedFfrac, alignedSeq, HDist, nTrue, sortFeatIDs] = mapStateSeqLabelsToGroundTruth( F, Ffrac, stateSeq, data_struct )
% Align feature matrix F and state sequence recovered by inference
%  so that labels correspond to a known *ground truth* state sequence
% Output aligned F and state sequence
%    both correspond to the same ground truth sequences
% Also returns the Hamming distance between the aligned seq and truth
%    in struct format
% INPUT:
%  F     : N x K matrix
%           binary feature matrix
%  Ffrac : N x K matrix
%           real matrix, indicates average over number of posterior samps
%           for F
%  stateSeq : Nx1 struct
%           stateSeq(ii).z gives state labels for sequence ii
%  data_struct : Nx1 struct
%           data_struct(ii).true_labels gives TRUE labels for sequence ii
for ii = 1:length( stateSeq )
    Ts(ii) = length( stateSeq(ii).z );
end
est_seq = zeros( 1, sum( Ts ) );
true_seq = zeros( 1, sum(Ts)  );
TsCDF = [0 cumsum(Ts)];
for ii = 1:length( data_struct )
    Ttrue =  data_struct(ii).T;
    if Ttrue == Ts(ii)
        true_seq(  TsCDF(ii)+1:TsCDF(ii+1) ) = data_struct(ii).true_labels;
    elseif Ttrue == Ts(ii) + 1  % handle auto-regressive case!
        true_seq(  TsCDF(ii)+1:TsCDF(ii+1) ) = data_struct(ii).true_labels(2:end);
    else
        error( 'Mismatch in lengths between true and est sequences!' );
    end
    est_seq(   TsCDF(ii)+1:TsCDF(ii+1) ) = stateSeq(ii).z;
end

unique_true = unique( true_seq );
nTrue = length( unique_true );
[new_est_seq, HamDist, AlignedIDs] = mapEstLabels2Truth(true_seq,est_seq);
% AlignedIDs is a 1 x nUniqueEst vector
%   where entry kk says which true label the kk-th feature aligns to

alignedSeq = stateSeq;
for ii = 1:length( alignedSeq );
    alignedSeq(ii).z = new_est_seq( TsCDF(ii)+1:TsCDF(ii+1)  );

    est_z = new_est_seq( TsCDF(ii)+1:TsCDF(ii+1)  );
    true_z = true_seq( TsCDF(ii)+1:TsCDF(ii+1) );
    HDist.Ts(ii) = length( true_z );
    HDist.obj(ii) = sum( ( est_z ~= true_z ) )/length( true_z );
end
HDist.total = HamDist;
M = max( size(F,2), length(unique_true) );
unique_est = unique( est_seq );

if length( unique_est ) <= length( unique_true )
    alignedF = zeros( length(data_struct), M );
    alignedFfrac = zeros( length(data_struct), M );

    alignedF( :, AlignedIDs ) = F(:, unique_est );
    alignedFfrac( :, AlignedIDs ) = Ffrac(:, unique_est );

    % Finally, we need to fill in "bogus/deadbeat" features at the end
    deadIDs = setdiff( 1:size( F,2 ), unique_est );
    if ~isempty( deadIDs )
       alignedF( :, length(unique_est) + (1:length(deadIDs)) ) = F( :, deadIDs );
       alignedFfrac( :, length(unique_est) + (1:length(deadIDs)) ) = Ffrac( :, deadIDs );
    end

elseif size(F,2) > length( unique_true )

    % sortFeatIDs is a 1 x M vector
    %   that when applied as indices to a (expanded) version of F
    %   sorts the cols so that it aligns with Ftrue
    sortFeatIDs = zeros( 1,  M );
    for aa = 1:length( unique_est )
        sortFeatIDs( AlignedIDs(aa) ) = unique_est(aa);
    end

    % If we have too many unique features ( more than # true states)
    %   then we need to fill in "zero" entries so that unaligned est states
    %    appear at the end of the aligned matrix (with high feat IDs )
    Ks = setdiff( 1:size(F,2), unique_est );
    if ~isempty( Ks )
        kk=1;
        for aa = 1:size(F,2)
            if sortFeatIDs(aa) == 0
                sortFeatIDs( aa ) = Ks(kk);
                kk = kk + 1;
            end
        end
    end

    alignedF = F( :, sortFeatIDs );
    alignedFfrac = Ffrac( :, sortFeatIDs );
end

end


text:
var DefaultLineWrapper,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

module.exports = DefaultLineWrapper = (function(superClass) {
  extend(DefaultLineWrapper, superClass);

  function DefaultLineWrapper() {
    return DefaultLineWrapper.__super__.constructor.apply(this, arguments);
  }

  DefaultLineWrapper.prototype._render = function() {};

  return DefaultLineWrapper;

})(require('./_LineWrapper'));


text:
@interface AuthenticationManager ()

@property (nonatomic, copy) AuthenticationSuccessBlock authenticationSuccessBlock;

- (UIAlertView *)signInAlertView;

@end

@implementation AuthenticationManager

- (void)showSignInAlertViewWithCompletion:(AuthenticationSuccessBlock)completion
{
    self.authenticationSuccessBlock = completion;

    [[self signInAlertView] show];
}

#pragma mark - Private

- (UIAlertView *)signInAlertView
{
    UIAlertView *signInAlert = [[UIAlertView alloc] initWithTitle:@"Reddit Account"
                                                          message:@"Please enter your account credentials."
                                                         delegate:self
                                                cancelButtonTitle:@"Cancel"
                                                otherButtonTitles:@"Sign In", nil];
    signInAlert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;

    return signInAlert;
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        NSString *username = [[alertView textFieldAtIndex:0] text];
        NSString *password = [[alertView textFieldAtIndex:1] text];

        if ([username length] == 0 || [password length] == 0)
        {
            return;
        }

        __weak __typeof(self)weakSelf = self;
        [[RKClient sharedClient] signInWithUsername:username password:password completion:^(NSError *error) {
            if (error)
            {
                UIAlertView *errorAlertView = [weakSelf signInAlertView];
                errorAlertView.message = error.localizedFailureReason;

                [errorAlertView show];
            }
            else
            {
                if (self.authenticationSuccessBlock)
                {
                    dispatch_async(dispatch_get_main_queue(), self.authenticationSuccessBlock);
                }
            }
        }];
    }
}

@end


text:
Orbital is a point and click MMORPG Unity game.

the fifth is a plataform multiplayer game.


text:
LEX_FILES=ppdz/MJLexer.lex
OUT_FILES=ppdz/Yylex.java ppdz/*.class ppdz/Yylex.java~ ppdz/sym.java ppdz/parser.java
TEST_FILE=ppdz/MJTest.java
CUP_FILE=ppdz/mjparser.cup

CPATH=.:..:ppdz/:java-cup-11a.jar:symboltable-1.1.0.jar:mj-runtime.jar
JAVA=java
JAVAC=javac

all: test

JFlex: ppdz/MJLexer.lex
	$(JAVA) -jar JFlex.jar ppdz/MJLexer.lex

sym: JFlex parser
	$(JAVAC) -g ppdz/sym.java

Yylex: parser JFlex ppdz/Yylex.java
	$(JAVAC) -cp $(CPATH) -g ppdz/Yylex.java

test: JFlex sym Yylex
	$(JAVAC) -cp $(CPATH) -g $(TEST_FILE)

parser:
	$(JAVA) -jar java-cup-11a.jar -destdir ppdz $(CUP_FILE)
	$(JAVAC) -cp $(CPATH) -g ppdz/parser.java

run_parser: ppdz/MJTest.java
	@$(JAVA) -cp $(CPATH) ppdz/MJTest test/program.mj

run_test: program.obj
	$(JAVA) -cp mj-runtime.jar rs.etf.pp1.mj.runtime.Run program.obj ${ARGS}

disasm: program.obj
	$(JAVA) -cp mj-runtime.jar rs.etf.pp1.mj.runtime.disasm program.obj

clean:
	rm -rf $(OUT_FILES)

help:
	@echo "make JFlex (Lex file -> Yylex.java, generate lexic analyzer)"
	@echo "make sym   (Generate symbol table class)"
	@echo "make test  (Compile test class)"
	@echo "make all   (JFlex sym test)"
	@echo "make clean (clean all files, leave only src files)"


text:
<?xml version="1.0" encoding="utf-8"?>
<project>
	<meta title="RPGFL Test" package="rpgfl.test" version="1.0.0" company="tienery" />

	<app main="Main" file="rpgfl_test" path="bin" />

	<window background="#FFFFFF" fps="60" />
	<window width="800" height="480" unless="mobile" />
	<window orientation="landscape" vsync="false" antialiasing="0" if="cpp" />

	<source path="./" />
	<haxelib name="openfl" />
    <haxelib name="hscript" />
	<haxelib name="actuate" />
    <haxelib name="rpgfl" />

	<icon path="../assets/openfl.svg" />
	<assets path="../assets/img" rename="img" />
    <assets path="../assets/info" rename="info" />
    <assets path="../assets/maps" rename="maps" />

	<!-- optimize output
	<haxeflag name="-dce full" /> -->

</project>


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CellRef.cs" company="PropertyTools">
//   Copyright (c) 2014 PropertyTools contributors
// </copyright>
// <summary>
//   Represents a cell reference.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace PropertyTools.Wpf
{
    using System;
    using System.ComponentModel;
    using System.Globalization;

    /// <summary>
    /// Represents a cell reference.
    /// </summary>
    [TypeConverter(typeof(CellRefConverter))]
    public struct CellRef : IEquatable<CellRef>
    {
        /// <summary>
        /// The column.
        /// </summary>
        private readonly int column;

        /// <summary>
        /// The row.
        /// </summary>
        private readonly int row;

        /// <summary>
        /// Initializes a new instance of the <see cref="CellRef" /> struct.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <param name="column">The column.</param>
        public CellRef(int row, int column)
        {
            this.row = row;
            this.column = column;
        }

        /// <summary>
        /// Gets the column.
        /// </summary>
        public int Column => this.column;

        /// <summary>
        /// Gets the row.
        /// </summary>
        public int Row => this.row;

        /// <summary>
        /// Converts a column number to a column name.
        /// </summary>
        /// <param name="column">The column.</param>
        /// <returns>
        /// The to column name.
        /// </returns>
        public static string ToColumnName(int column)
        {
            string result = string.Empty;
            while (column >= 26)
            {
                int i = column / 26;
                result += ((char)('A' + i - 1)).ToString(CultureInfo.InvariantCulture);
                column = column - (i * 26);
            }

            result += ((char)('A' + column)).ToString(CultureInfo.InvariantCulture);
            return result;
        }

        /// <summary>
        /// Converts a row number to a row name.
        /// </summary>
        /// <param name="row">The row.</param>
        /// <returns>
        /// The to row name.
        /// </returns>
        public static string ToRowName(int row)
        {
            return (row + 1).ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
        /// </returns>
        public override int GetHashCode()
        {
            long hash = this.column;
            hash = (hash << 16) + this.row;
            return (int)hash;
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
        /// </summary>
        /// <param name="obj">Another object to compare to.</param>
        /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
        public override bool Equals(object obj)
        {
            return obj is CellRef && this.Equals((CellRef)obj);
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
        public bool Equals(CellRef other)
        {
            return this.column == other.column && this.row == other.row;
        }

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return string.Format("{0}{1}", ToColumnName(this.Column), this.Row + 1);
        }
    }
}


text:
@implementation Correspondence

+ (instancetype)insertInManagedObjectContext:(NSManagedObjectContext *)moc_ {
    NSParameterAssert(moc_);
    return [NSEntityDescription insertNewObjectForEntityForName:@"Correspondence" inManagedObjectContext:moc_];
}

+ (NSString*)entityName {
    return @"Correspondence";
}

+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_ {
    NSParameterAssert(moc_);
    return [NSEntityDescription entityForName:@"Correspondence" inManagedObjectContext:moc_];
}

@end


text:
var numOfChildWindows = 5;
var childWindows = [];
for (var i = 0; i < numOfChildWindows; i++) {
    var windowName = 'Lock-test-child' + i;
    childWindows.push(window.open('Lock-test-child.html', windowName));
}

jasmine.DEFAULT_TIMEOUT_INTERVAL = 500000;
describe("Lock.", function () {
    beforeEach(function (done) {
        done();
    });
    it('Lock.capture(). Captured lock should be held only by one window until window is closed or lock is released', function (done) {
        var testFn = function () {
            var numOfCapturedLocks = 0;
            var capturedLock = null;
            childWindows.forEach(function(childWindow) {
                if (childWindow.lock) {
                    expect(childWindow.lock.isCaptured()).toEqual(childWindow.captureCallbackExecuted);
                    if (childWindow.lock.isCaptured()) {
                        capturedLock = childWindow.lock;
                        numOfCapturedLocks++;
                    }
                }
            });
            if (numOfCapturedLocks === 0) {
                setTimeout(testFn, 500);
                return;
            }
            capturedLock.release();
            setTimeout(function () {
                var numOfCapturedLocks = 0;
                var numOfReleasedLocks = 0;
                var capturedLock = null;
                childWindows.forEach(function (childWindow) {
                    expect(childWindow.lock.isCaptured() || childWindow.lock.isReleased()).toEqual(childWindow.captureCallbackExecuted);
                    if (childWindow.lock.isCaptured()) {
                        capturedLock = childWindow.lock;
                        numOfCapturedLocks++;
                    }
                    if (childWindow.lock.isReleased()) {
                        numOfReleasedLocks++;
                    }
                });
                expect(numOfCapturedLocks).toEqual(1);
                expect(numOfReleasedLocks).toEqual(1);
                SJ.iwc.Lock.capture('lockid', function () {
                    expect(childWindows.length).toEqual(0);
                    done();
                });
                setTimeout(function () {
                    childWindows.forEach(function (childWindow) {
                        childWindow.close();
                    });
                    childWindows.length = 0;
                }, 1000);
            }, 500);
        };
        testFn();
    });
});

SJ.windowOn('unload', function () {
    childWindows.forEach(function (childWindow) {
        childWindow.close();
    });
});


text:
namespace Adaptive.Aeron.Security
{
    /// <summary>
    /// Representation of a session during the authentication process from the perspective of an <seealso cref="IAuthenticator"/>.
    /// </summary>
    /// <seealso cref="IAuthenticator"/>
    public interface ISessionProxy
    {
        /// <summary>
        /// The identity of the potential session assigned by the system.
        /// </summary>
        /// <returns> identity for the potential session. </returns>
        long SessionId();

        /// <summary>
        /// Inform the system that the session requires a challenge by sending the provided encoded challenge.
        /// </summary>
        /// <param name="encodedChallenge"> to be sent to the client. </param>
        /// <returns> true if challenge was accepted to be sent at present time or false if it will be retried later. </returns>
        bool Challenge(byte[] encodedChallenge);

        /// <summary>
        /// Inform the system that the session has met authentication requirements.
        /// </summary>
        /// <param name="encodedPrincipal"> that has passed authentication. </param>
        /// <returns> true if authentication was accepted at present time or false if it will be retried later. </returns>
        bool Authenticate(byte[] encodedPrincipal);

        /// <summary>
        /// Inform the system that the session should be rejected.
        /// </summary>
        void Reject();
    }
}


text:
module FayeTockenable
  extend ActiveSupport::Concern
  included do
    field :faye_token, type: String, default: nil
  end

  def reset_faye_token!
    reset_faye_token
    self if save(validate: false)
  end

  def reset_faye_token
    self.faye_token = SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')
  end
end


text:
import { expect } from 'chai';
import { ForceOrgDisplay } from '../../../src/commands';
import { nls } from '../../../src/messages';

// tslint:disable:no-unused-expression
describe('Force Source Status', () => {
  it('Should build the source command no flag', async () => {
    const forceOrgDisplay = new ForceOrgDisplay();
    const displayCommand = forceOrgDisplay.build({});
    expect(displayCommand.toCommand()).to.equal('sfdx force:org:display');
    expect(displayCommand.description).to.equal(
      nls.localize('force_org_display_default_text')
    );
  });
  it('Should build the source command with targetusername flag', async () => {
    const forceOrgDisplay = new ForceOrgDisplay('--targetusername');
    const displayCommand = forceOrgDisplay.build({ username: 'test' });
    expect(displayCommand.toCommand()).to.equal(
      'sfdx force:org:display --targetusername test'
    );
    expect(displayCommand.description).to.equal(
      nls.localize('force_org_display_username_text')
    );
  });
});


text:
This is a simple 'declarative' deployment system for servers and home
directories.  In conjuction with GNU Guix and (perhaps) GWL and the
common workflow langauge (CWL) essentially a replacement for Puppet,
Chef, Cfengine, Cfruby, GNU stow, etc.  See the doc/design.org
document for more.

The tooling comes with the `sheepdog`: a minimalist monitor and notification system.
The purpose of `sheepdog' is to monitor problems in hardware and software on a larger setup.
Events, such as a succeeding or failing backup, get pushed onto a message queue for later digestion.

Important notice: much of the work on deploy has been superceded by Guix and Guix home!

=> https://guix.gnu.org/manual/devel/en/html_node/Home-Configuration.html

What remains is our faithful `sheepdog' to generate monitoring events and tools to process them.

Pjotr Prins (c) 2015-2022

## TODO

=> https://issues.genenetwork.org/search?query=sheepdog&type=all

# Sheepdog

Sheepdog is a tool for monitoring services. The idea is simple: use a
wrapper script to capture output of, for example, a backup run. On
error push a message out into a queue. The basic premises are:

- Only notify on FAIL (by default)
- Separation of concerns
- Make debugging of scripts easy

By default we use redis, but syslog and others may also be used.
The advantage of redis is that it is not bound to the same host, can cross firewalls using an ssh reverse tunnel (see below), and is easy to query.

    ./bin/sheepdog_run.rb -v -c 'echo "HELLO WORLD"'

To push a failing event

    ./bin/sheepdog_run.rb -v -c 'false'

To get the status, query with

    ./bin/sheepdog_list.rb
    2021-01-10 00:33:41 -0600 (penguin2) SUCCESS 0 <33m40s> TRIM
    2021-01-10 01:00:01 -0600 (penguin2) FAIL 1 <00m00s> CHK_BORG_GN2
    2021-01-10 01:00:01 -0600 (penguin2) SUCCESS 0 <00m00s> CHK_BORG_IPFS
    2021-01-10 01:00:01 -0600 (penguin2) SUCCESS 0 <00m00s> CHK_BORG_TUX01
    2021-01-10 01:00:01 -0600 (penguin2) SUCCESS 0 <00m00s> CHK_TUX01_MARIADB

And parse JSON with the great `jq` tool you can find [here](https://stedolan.github.io/jq/):

    ./bin/sheepdog_list.rb --json|jq

Outputs a nicely colored and formatted:

```js
{
    "time": "2021-01-09 16:00:34 +0000",
    "elapsed": 0,
    "host": "lario",
    "command": "find . -iname \"*\" -mtime -100 -print|grep binx",
    "tag": "HELLO",
    "stdout": "",
    "stderr": "",
    "status": 1,
    "err": "FAIL"
}
```

Note that the message queue contains fields for the time stamp, the executed command and stdout/stderr. These are important for trouble shooting down the line.

Check jq out. It has a lot of powerful filters. To get the
last status of services do

    ./bin/sheepdog_list.rb --status|jq

Note that if redis fails to respond the commands will still run, but
(obviously) no event is recorded in redis.

We host a reference implementation here. Sheepdog has a number
of tricks:

## jq for filtered output

Reduce the number of fields:

    sheepdog_list.rb --status|jq '.[]| { time: .time, tag: .tag, status: .status }'

To see only the failing tags (-c outputs a record on a single line):

    sheepdog_list.rb --status|jq -c '.[]| select(.status=="FAIL") | { time: .time, tag: .tag, status: .status }'

```js
{"time":"2021-01-10 09:42:46 +0100","tag":"FETCH_P2","status":"FAIL"}
{"time":"2021-01-11 02:00:02 -0600","tag":"CHK_BORG_GN2","status":"FAIL"}
```

## Backups

An example for making a backup with the excellent borg tool, reporting
to a redis server running on a host named report.lan

```sh
#!/bin/bash

export stamp=$(date +%A-%Y%m%d-%H:%M:%S)
sheepdog_run.rb -c "borg create /export/backup/borg-etc::P2_etc-$stamp /etc" --tag 'P2-ETC' --log --always --host reporthost
```

and after running many backups it was time to create `sheepdog_borg'
which looks like

```sh
sheepdog_borg.rb -b /export/backup/borg-etc /etc
```

`sheepdog_borg` checks file permissions and will only run with a
passphrase set in $HOME/.borg-pass.  See the script for more info.
`sheepdog_borg` can be run as root. For security reasons, do not do
set that up as a CRON job (unless sheepdog and scripts are installed
by Guix into the immutable store).

## Find if a directory changed

When doing backups we want to know (1) whether a command ran,
(2) whether it failed and (3) assert something happened.

For the (3) Unix has

    find dir/ -iname "*" -mtime -2 -print

to see if anything changed in the last days. Sheepdog can do

    sheepdog_run.rb -v -c 'find . -iname "*" -mtime -2 -print|grep bin'

where `grep` generates a return value.

## Monitor a web service

This can easily be done with curl and grep:

    sheepdog_run.rb -c 'curl https://thebird.nl/|grep Pjotr'

## Monitor the monitor

Ok, you have a notification for your backup job. How do you know when
the server just stopped working? There are three things to add: a ping
or curl job to the machine (see above), and monitoring job output,
e.g. with above 'find if a directory changed'. In addition you can
monitor for failing redis PINGs by adding a daily ping to redis with

    sheepdog_ping.rb --host reporthost

and adding an 'expect' job to notify you if such a PING is not received
in time. Obviously one could run a ping every minute when reporting
is critical.

# Redis

Because we use redis we can use the following commands:

## Remove messages

```
redis-cli
KEYS sheepdog_*
DEL sheepdog_run
```

## Using passwords

When a server is configured with a password it can be passed on the
command line with `--password` or set in a file
`~/.config/sheepdog/sheepdog.conf`:

```js
{
  "redis": {
    "host"  : "localhost",
    "port" : 6379,
    "password": "123456"
  }
}
```

Multiple hosts are supported in principle, but behaviour is (yet)
undefined. When you specify a host on the command line it will send a
message to that host using the password. Here, hostname will be the default
message queue and that can be overridden with the `--host` switch.

## Locking

We have a lock command which will check a lock file using the tag name.

sheepdog_rsync command has an option for using borg locks.

# Extra info

## Developing a new notification service

To create a new notification service it is easiest to go through
the following steps:

1. Create notification with `-v` and '`--always` flags
2. Run notification every minute (in CRON)
3. Use sheepdog_list to monitor the queue
4. Add `-v --full` and `--filter` options to view stdout/stderr
5. After making sure it works relax (1) and (2)

The notifications contain stdout and stderr output which should be
informative.

## E-mail failures

We can tell sheepdog to sent E-mails on failure. There are two scenarios:

1. E-mail directly - for critical services
2. E-mail daily digest - e.g., for backups

Receiving E-mails is very annoying, so when the sheepdog barks it
should be worth resolving.

To E-mail on failure simply use the `--email` switch:

```sh
sheepdog_rsync.rb --tag RSYNC_P2 genenetwork.org:/export/backup/tux01/* /export/backup/tux01/ --always --email admin@genenetwork.org -v --log --args '--delete'
```

## Typical CRON

This is what CRON jobs look like. To prevent injection, make sure the
scripts in a root CRON are only accessible by root!

```cron
GEM_PATH=/home/wrk/opt/deploy/lib/ruby/vendor_ruby
PATH=/home/wrk/iwrk/deploy/deploy/bin:/home/wrk/opt/deploy/bin:/bin:/usr/bin

# Once a week
0 0 * * 0 sheepdog_run.rb -c '/sbin/fstrim -a' --tag TRIM_P2 --host reporthost --log --always >> ~/cron.log 2>&1

22 4 * * 3 sheepdog_run.rb -c '/usr/bin/certbot renew --quiet' --tag CERTBOT_P2 --host reporthost >> ~/cron.log 2>&1

# Every day
0 0 * * * sheepdog_ping.rb --host reporthost

# Every 6 hours
0 0,6,12,18 * * * /export/backup/scripts/backup.sh  >> ~/cron.log 2>&1
```

Note that the redirection only for stuff not captured by sheepdog. It
is rare to look into those outputs. If you leave it out CRON may try
to send an E-mail on any output.

## REDIS reverse tunnel

Sometimes a redis queue is not directly reachable because it is inside a firewall. If the sheepdog machine can be reachead from the redis machine we can set up a reverse tunnel with ssh. That requires a password-less key and therefore we should give that user limited rights. On the machine running sheepdog create a user that has no shell access:

```
useradd redis-tun -m -s /bin/true
```

In /etc/ssh/sshd.conf set up

```
Match User redis-tun
  PermitOpen 127.0.0.1:6379
  X11Forwarding no
  AllowAgentForwarding no
  ForceCommand /bin/false
```

Now make sure the ssh key is on the redis host and

```
/usr/bin/ssh -i key -f -N -R 6377:localhost:6379 redis-tun@sheepdoghost
```

Next you should be able to connect with

```
redis-cli -p 6377
```

And update sheepdog.conf accordingly

A CRON entry may look like

```
3 * * * * /usr/bin/ssh -i key -f -N -R 6377:localhost:6379 redis-tun@sheepdoghost >> tunnel.log &2>1
```

# Check for connections

Sheepdog has an expect function to check for servers connecting. For example,
running the following on the queue

    sheepdog_expect.rb --filter penguin2 --elapse 3h

will add a FAIL event if penguin2 has not connected in the last three
hours, i.e. no messages where received in the queue.

# Install

To install dependencies:

    guix package -i ruby ruby-redis redis jq ruby-colorize borg -p ~/opt/deploy

Setup the environment

    . ~/opt/deploy/etc/profile

(notice the leading dot) and run. Look inside profile to see the required
environment variables. The following may just do in CRON:

    GEM_PATH=$HOME/opt/deploy/lib/ruby/vendor_ruby

A (failing) CRON job may look like

    0 * * * * echo $HOME >> ~/sheepdog.log
    0 * * * * GEM_PATH=$HOME/opt/deploy/lib/ruby/vendor_ruby ~/iuser/deploy/deploy/bin/sheepdog_run.rb -c 'nono "HELLO WORLD"' --tag HELLO >> ~/sheepdog.log &2>1

GEM_PATH can also be set at the top of the crontab, but note that does no
variable expansion of $HOME. Something like this may work

    GEM_PATH=/home/user/opt/deploy/lib/ruby/vendor_ruby
    PATH=/home/user/iuser/deploy/deploy/bin:/home/user/opt/deploy/bin:/bin:/usr/bin

    0 * * * * sheepdog_run.rb -c 'echo "HELLO WORLD"' --tag HELLO -v >> ~/sheepdog.log

Do test with the -v switch and '>> log' to make sure your script works.
Thereafter

    GEM_PATH=/home/user/opt/deploy/lib/ruby/vendor_ruby
    PATH=/home/user/iuser/deploy/deploy/bin:/home/user/opt/deploy/bin:/bin:/usr/bin

    0 * * * * sheepdog_run.rb -c 'echo "HELLO WORLD"' --tag HELLO -v --log

should do the job.

# License

This software is published under the MIT license.


text:
namespace RestImageResize
{
    /// <summary>
    /// Enumerates the supported image transformation types.
    /// </summary>
    public enum ImageTransform
    {
        /// <summary>
        /// The scale to fit transformation.
        /// </summary>
        Fit = 0,

        /// <summary>
        /// The scale to fill transformation.
        /// </summary>
        Fill = 1,

        /// <summary>
        /// The scale down to fit transformation.
        /// </summary>
        DownFit = 2,

        /// <summary>
        /// The scale down to fill transformation.
        /// </summary>
        DownFill = 3,

        /// <summary>
        /// The central crop transformation.
        /// </summary>
        Crop = 4,

        /// <summary>
        /// The stretch transformation.
        /// </summary>
        Stretch = 5,

        /// <summary>
        ///
        /// </summary>
        ResizeMin = 6,

        /// <summary>
        ///
        /// </summary>
        DownResizeMin = 7,

        /// <summary>
        /// The resize crop transformation
        /// </summary>
        ResizeCrop = 8,
        /// <summary>
        ///
        /// </summary>
        DownResizeCrop = 9
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
            http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <class>com.cancosoft.assets.handset.domain.CheckRegister</class>
    </persistence-unit>
</persistence>


text:
require 'java_buildpack/component/base_component'
require 'java_buildpack/container'
require 'java_buildpack/util/dash_case'
require 'java_buildpack/util/java_main_utils'

module JavaBuildpack
  module Container

    # Encapsulates the detect, compile, and release functionality for applications running a simple Java +main()+
    # method. This isn't a _container_ in the traditional sense, but contains the functionality to manage the lifecycle
    # of Java +main()+ applications.
    class JavaMain < JavaBuildpack::Component::BaseComponent

      # (see JavaBuildpack::Component::BaseComponent#detect)
      def detect
        main_class ? JavaMain.to_s.dash_case : nil
      end

      # (see JavaBuildpack::Component::BaseComponent#compile)
      def compile
      end

      # (see JavaBuildpack::Component::BaseComponent#release)
      def release
        @droplet.additional_libraries.insert 0, @application.root
        manifest_class_path.each { |path| @droplet.additional_libraries << path }

        release_text
      end

      private

      ARGUMENTS_PROPERTY = 'arguments'.freeze

      CLASS_PATH_PROPERTY = 'Class-Path'.freeze

      private_constant :ARGUMENTS_PROPERTY, :CLASS_PATH_PROPERTY

      def release_text
        [
          port,
          "#{@droplet.java_home.root}/bin/java",
          @droplet.additional_libraries.as_classpath,
          @droplet.java_opts.join(' '),
          main_class,
          arguments
        ].flatten.compact.join(' ')
      end

      def arguments
        @configuration[ARGUMENTS_PROPERTY]
      end

      def main_class
        JavaBuildpack::Util::JavaMainUtils.main_class(@application, @configuration)
      end

      def manifest_class_path
        values = JavaBuildpack::Util::JavaMainUtils.manifest(@application)[CLASS_PATH_PROPERTY]
        values.nil? ? [] : values.split(' ').map { |value| @droplet.root + value }
      end

      def port
        main_class =~ /^org\.springframework\.boot\.loader\.(?:[JW]ar|Properties)Launcher$/ ? 'SERVER_PORT=$PORT' : nil
      end

    end

  end
end


text:
<?php

declare(strict_types=1);

namespace Drupal\ckeditor5_plugin_elements_subset\Plugin\CKEditor5Plugin;

use Drupal\ckeditor5\Plugin\CKEditor5PluginConfigurableTrait;
use Drupal\ckeditor5\Plugin\CKEditor5PluginDefault;
use Drupal\ckeditor5\Plugin\CKEditor5PluginElementsSubsetInterface;
use Drupal\Core\Form\FormStateInterface;

class SneakySuperset extends CKEditor5PluginDefault implements CKEditor5PluginElementsSubsetInterface {

  use CKEditor5PluginConfigurableTrait;

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'configured_subset' => [],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getElementsSubset(): array {
    return $this->configuration['configured_subset'];
  }

}


text:
const currentLocale = $('input[name=locale]').val();

const biometricTranslations = {
  'en': {
    'expired': '
Your Biometric session has expired.

Refresh the page for a new QR code or cancel the operation to return to the Strong Authentication overview.
',
    'complete': 'Je Biometric account is gereed voor gebruik. Je gaat automatisch terug naar het Sterke Authenticatie overzicht'
  },
  'nl': {
    'expired': '
Je Biometric sessie is verlopen.

Ververs de pagina voor een nieuwe QR code of annuleer het authenticeren om terug te gaan naar het Sterke Authenticatie overzicht.
',
    'complete': '
Your Biometric account is ready to use. You wil be automatically be redirected to the Strong Authentication overview
'
  }
};

const accrued_time = $('input[name=accrued_time]').val();

$('#countdown').pietimer({
    seconds: 9.9 * 60,
    color: '#4DB3CF',
    height: 60,
    width: 60,
    accrued_time: accrued_time
  },
  function () {
  });

$('#countdown').pietimer('start');

$.ajaxSetup({
  headers: {'X-POLLING': 'true'}
});

function pollStatus() {
  $.get('/poll', function (data) {
    switch (data.status) {
      case 'pending':
        window.setTimeout(pollStatus, 1000);
        break;
      case 'complete':
        $('#status').html(biometricTranslations[currentLocale][data.status]);
        window.setTimeout(function () {
          $( "#form" ).submit();
        }, 1000)
        break;
      case 'expired' :
        ['#countdown', '#timeleft', '#qrcode'].forEach(function(cssSelector){
          $(cssSelector).hide();
        });
        $('#status').html(biometricTranslations[currentLocale][data.status]);
        break;
    }
  })
}

window.setTimeout(pollStatus, 1000);


text:
<?php

require_once 'MySql.php';
require_once 'PgSql.php';

?>


text:
Link to the presentation: [Docker intro in < 5min][1].

This is my five minute intro into Docker that I presented internally as a really super-fast ramp up on what Docker is compared to more standard VM environment and how Docker can be leveraged. Heavily depends on discussion with the team and hands-on examples in the slides.

By no means is this a complete "learn how to Docker" type of presentation but a quick dive into the deep end, start doing before even understanding what you're doing. Learn by doing and learn by example are the keywords here.

It quickly mixes the bag up and makes you start using Docker asap, have fun guys :smile:

[1]: http://mikaturunen.github.io/5minuteintrotodocker/


text:
var primitives = true;

function ggbOnInit() {

  var element = document.getElementsByClassName("toolbar_button")[0];
  element.setAttribute("isselected", "false");
  ggbApplet.debug("ggbOnInit");
  ggbApplet.registerAddListener("newObjectListener");
  function Command(cmd){ggbApplet.debug(cmd); ggbApplet.evalCommand(cmd);}
  function abspos(x,y){
  return "Corner[4] + ("+x+"*(x(Corner[3])-x(Corner[4])),"+y+"*(x(Corner[2])-x(Corner[1])))"
  }
  Command('progress = 0');
  Command('Progresstext = Text["Progress: "progress"%",'+abspos("0.011","-0.032915")+']');
  Command('countnumber = 0');
  Command ('count0 = Text["Moves: "countnumber"",'+abspos("0.85","-0.032915")+']');
	Command('W = (-10,-10)');
	ggbApplet.setVisible("W",false);
	Command('welldone = Text["Well done!", W]');
	ggbApplet.setVisible("welldone",false);
	}

  function Command(cmd){ggbApplet.debug(cmd); ggbApplet.evalCommand(cmd);}
    function abspos(x,y){
  return "Corner[4] + ("+x+"*(x(Corner[3])-x(Corner[4])),"+y+"*(x(Corner[2])-x(Corner[1])))"
  }
  	var count = 'Text["Count = 0",'+abspos("0.85","-0.032915")+']'
function newObjectListener(obj) {
if (ggbApplet.getObjectType(obj) === "boolean" || ggbApplet.getObjectType(obj) === "text" || ggbApplet.getObjectType(obj) === "numeric"|| obj == "W")
{return;
}

    if (ggbApplet.getObjectType(obj) == "segment" || ggbApplet.getObjectType(obj) == "circle" || ggbApplet.getObjectType(obj) == "ray" || ggbApplet.getObjectType(obj) == "line") {
ggbApplet.setColor(obj,255,204,102);
}

  function Command(cmd){ggbApplet.debug(cmd); ggbApplet.evalCommand(cmd);}

    function abspos(x,y){
  return "Corner[4] + ("+x+"*(x(Corner[3])-x(Corner[4])),"+y+"*(x(Corner[2])-x(Corner[1])))"
  }

var cmdString = ggbApplet.getCommandString(obj);
console.log(cmdString);
console.log(ggbApplet.getObjectType(obj));
console.log(obj);

if (ggbApplet.getObjectType(obj) == "point" && cmdString == "")
{
	console.log(ggbApplet.getXcoord(obj));
	var x = ggbApplet.getXcoord(obj) + 0.01;
	console.log(x);
	var y = ggbApplet.getYcoord(obj) - 0.01;
	Command( obj +"= ("+x+","+y+")");
}

if (cmdString.substring(0,3) == "Ray" || (cmdString.substring(0,2) == "Eq" && ggbApplet.getObjectType(obj)=="point") || cmdString.substring(0,3) == "Seg" ||cmdString.substring(0,3) == "Cir" || cmdString.substring(0,3) == "Mid" || cmdString.substring(0,13) == "AngleBisector" || cmdString.substring(0,4) == "Perp" || cmdString.substring(0,4) == "Line" || (cmdString.substring(0,5) == "Trans"&& ggbApplet.getObjectType(obj)=="point")){
	Command('countnumber = countnumber + 1');
if (!(cmdString.substring(0,3) == "Ray" || cmdString.substring(0,3) == "Seg" || cmdString.substring(0,3) == "Cir") && primitives) { primitives = false;}

function isLowerCase(myString) {
  return (myString == myString.toLowerCase());
}

var lastcomma = cmdString.indexOf(",");
if(cmdString.substring(0,3) == "Cir" && (isLowerCase(cmdString.substring(lastcomma+2,lastcomma+3)) || cmdString.substring(lastcomma+2,lastcomma+4) =="Se" || cmdString.substring(lastcomma+2,lastcomma+4) =="Ra"))
{
primitives = false;}
}

if (cmdString.substring(0,13) == "AngleBisector"){
var obj1 = cmdString.substring(14,15);
if (ggbApplet.getObjectType(obj1) === "point"){
var obj2 = cmdString.substring(17,18);
var obj3 = cmdString.substring(20,21);
var a = ggbApplet.getXcoord(obj1);
var b = ggbApplet.getYcoord(obj1);
var m = ggbApplet.getXcoord(obj2);
var n = ggbApplet.getYcoord(obj2);
var x = ggbApplet.getXcoord(obj3);
var y = ggbApplet.getYcoord(obj3);

function round(value) {
    return(Math.round(value * 100000) / 100000);
}
if ( round((n-b)*(x-m)) === round((y-n)*(m-a))){
Command('Delete['+obj+']');
Command('Text["You can\'t use the bisecting tool if the angle is 180 degrees !",'+abspos("0.02","-0.632915")+']');
}
}
}
function getCoord(obj){
	if (ggbApplet.getObjectType(obj) === "point" ) {
	var x = ggbApplet.getXcoord(obj);
	var y = ggbApplet.getYcoord(obj);
		return "("+x+","+y+")"}
	else if (ggbApplet.getObjectType(obj)==="segment" || ggbApplet.getObjectType(obj)==="ray" ){
	Command("xx = x(Point["+obj+",0.5])");
	Command("yy = y(Point["+obj+",0.5])");
	var x = ggbApplet.getValue("xx");
	var y = ggbApplet.getValue("yy");
	return "("+x+","+y+")";
	}
	else if (ggbApplet.getObjectType(obj)==="circle"){
	var x = ggbApplet.getXcoord(cmdString.substring(7,8));
	var y = ggbApplet.getYcoord(cmdString.substring(7,8));
	return "("+x+","+y+")";
	}
}

  // this functions can check all general objects
  function checkobject(target,x,y) {
      Command("finished = (" + obj + "== " + target + ")");
      finished = ggbApplet.getValueString("finished");
      if (finished.indexOf("true") > -1) {
	  Command('f_'+target+'= Text["", (0,0)]');
	  Command("W = "+getCoord(target)+"+("+x+","+y+")");
		ggbApplet.setVisible("welldone",true);
      }
  }
  // this functions check line segments
  function checksegment(target,x,y) {
    if (ggbApplet.getObjectType(obj) == "segment") {
  	  var beginpointobject = "Point["+obj+",0]"
	  var endpointobject = "Point["+obj+",1]"
	  var beginpointtarget = "Point["+target+",0]"
	  var endpointtarget = "Point["+target+",1]"
      //here it checks if endpoints of line segment are equal
      if (obj != "finished") {
        Command("finished =((("+beginpointobject+"=="+beginpointtarget+")||("+beginpointobject+"=="+endpointtarget+"))&&(("+endpointobject+"=="+beginpointtarget+")||("+endpointobject+"=="+endpointtarget+")))");
        finished = ggbApplet.getValueString("finished");
      if (finished.indexOf("true") > -1) {
	  Command('f_'+target+'= Text["", (0,0)]');
	  if (typeof x !== 'undefined'){
  	  Command("W = "+getCoord(target)+"+("+x+","+y+")")};
		ggbApplet.setVisible("welldone",true);
      }
     			     }
   							 }
 					}
   // this functions can check if line segment has right direction

 function checkdirection(target,x,y) {
    if (ggbApplet.getObjectType(obj) == "segment" || ggbApplet.getObjectType(obj) == "ray" || ggbApplet.getObjectType(obj) == "line") {

	  Command("finished = (("+obj+"(1)=="+target+"(1))&&("+obj+"(-1)=="+target+"(-1)))");
      finished = ggbApplet.getValueString("finished");
      if (finished.indexOf("true") > -1) {
	  Command('f_'+target+'= Text["", (0,0)]');
	  	  if (typeof x !== 'undefined'){
  	  Command("W = "+getCoord(target)+"+("+x+","+y+")")};
		ggbApplet.setVisible("welldone",true);
      }

	}
  }
  // this functions check if the new point is on the targetline
  function checkpointontarget(target,x,y) {
    if (ggbApplet.getObjectType(obj) == "point") {
      Command("finished = ("+target+"(x("+obj+"))==y("+obj+"))");
      finished = ggbApplet.getValueString("finished");
      if (finished.indexOf("true") > -1) {
	  Command('f_p'+target+'= Text["", (0,0)]');
	  	  if (typeof x !== 'undefined'){
  	  Command("W = "+getCoord(obj)+"+("+x+","+y+")")};
		ggbApplet.setVisible("welldone",true);
 }

  }
  }

function drawn(object){
	return ggbApplet.getVisible('f_'+object) ;
}
var setVisible = ggbApplet.setVisible;

function LevelCompleted(condition,mincount){
 if(condition){
 	Command('progress = 100');
	Command('Complete = Text["Level completed !",  '+abspos("0.15","-0.13")+']');
    var count = ggbApplet.getValue("countnumber");
	if (primitives && (count === minlevel{{page.number}}p)){
	Command('score2 = Text["Perfect ! You have done this challenge in a minimum number of primitive moves!", '+abspos("0.35","-0.602915")+']');}
	if (!primitives)
	{ if(count === minlevel{{page.number}}){
	Command('score2 = Text["Perfect ! You have done this challenge in a minimum number of moves!", '+abspos("0.35","-0.602915")+']');}}
   //document.getElementById("level").style.display="inline-block";
	  $( "#hidden" ).slideDown(1000);
   $( "#hiddencomments" ).toggle();

if (primitives){
if (!(localStorage.Level{{page.number}}p < count)) {localStorage.Level{{page.number}}p = count;}}
else{
if(!(localStorage.Level{{page.number}}<count)){localStorage.Level{{page.number}} = count;}}

	}
}


text:
import { GraphQLNonNull } from 'graphql';
import TagInput from '../types/TagInputType';
import TagType from '../types/TagType';
import Tag from '../models/Tag';

const deleteTag = {
  type: new GraphQLNonNull(TagType),
  args: {
    tag: {
      type: TagInput,
      description: 'Delete tag',
    },
  },
  resolve: async (data, { tag }, { viewer, loaders }) => {
    const newTag = await Tag.delete(viewer, tag, loaders);
    return newTag;
  },
};

export default deleteTag;


text:
class Iso_Lookup
  require 'json'
  require 'json/ext'
  require 'rubygems'
  require 'httparty'

  def logger
    RAILS_DEFAULT_LOGGER
  end

  def generateit
    # see http://json.rubyforge.org/
    logger.info [ JSON.parser, JSON.generator ]
    #json = JSON.generate ({"pi"=>3.141})
    fruits = {:apple => "mansana", :orange=>"naranja"}
    geometry = {"pi"=>3.141}
    shopping = [fruits, geometry]
    json = JSON.generate(shopping)
    #([apple => "mansana", orange => "naranja"], {"pi"=>3.141})
    logger.info json
    return json
  end

  def parseit
    # see http://json.rubyforge.org/
    logger.info [ JSON.parser, JSON.generator ]
    #json = JSON.generate ({"pi"=>3.141})
    instring = '[{"apple":"mansana","orange":"naranja"},{"pi":3.141}]'
    json = JSON.parse(instring)
    #([apple => "mansana", orange => "naranja"], {"pi"=>3.141})
    logger.info "**parsed json is" + json.to_s
    return json
  end

  def getTorrents(query, type)
    begin
      content = ISOHunter.find_by_name_in_isohunter(query)
      if ((content['items'].nil?) || (content['total_results'] < 1))
        logger.info "No suitable torrent file was found."
        return nil
      end
      logger.info "Description: " + content["description"]

      torrents = Array.new
      i = 0

      jcontent = content['items']['list']

      logger.info "Found " + content['items']['list'].size.to_s + "  matching."
      jcontent.each do |each|
        logger.info "*" * 80

        torrent = Hash.new
        # link points to the detail page on ISOHunter
        # url points to the actual .torrent file

        torrent['torrent'] = each['enclosure_url']
        torrent['category'] = each['category']
        torrent['link'] = each['link']
        torrent['size'] = each['size']
        torrent['pubdate'] = each['pubDate']

        logger.info "Torrent URL: " + torrent['torrent']
        logger.info "Detailed page: "  + torrent['link']
        logger.info "Size: " + torrent['size']
        logger.info "Category: " + torrent['category']
        logger.info 'pubDate: ' + torrent['pubdate']

        if (torrent['category'] == type)

          torrents[i] = torrent
          i = i + 1
          logger.info "****added #{i}th row ****"
        else
          logger.info '***skipping***'
        end
      end
      if torrents.size > 0
        puts "***returning #{torrents.size} torrents***"
        return torrents
      else
        return nil
      end
    rescue Error => err
      logger.info "An Error occurred in the isolookup.rb file: " + err.message
      return nil
    rescue Exception => ex
      logger.info "An Exception occurred in the isolookup.rb file: " + ex.message
      return nil

    end

  end

end

class ISOHunter
  include HTTParty
  base_uri 'isohunt.com/js/json.php'
  default_params :output => 'json'
  format :json

  def self.find_by_name_in_isohunter(search_term)
    #get('/js/json.php?ihq=ubuntu&start=21&rows=20&sort=seeds', :query => {:other => other})
    maxrows = MAX_ISO_SEARCH_NUMBER ? MAX_ISO_SEARCH_NUMBER: 10
    get('/js/json.php', :query => {:ihq => search_term, :start => '1', :rows => maxrows, :sort => 'relevance'})
  end
end


text:
module Api
  module UpdateProgressConstants
    U_START = 1
    U_ARG_START = 2
    U_ARG_FIN = 3
    U_REQ_START = 4
    U_REQ_IOERROR = 5
    U_REQ_FIN = 6
    U_RESP_START = 7
    U_RESP_FIN = 8
    U_FINISH = 9
  end
  module InvocationProgressListener
    include UpdateProgressConstants
    def onUpdateStart(time, isForced); end
    def onArgumentsStart(); end
    def onArgumentsFinish(makeRequest); end
    def onRequestStart(time); end
    def onRequestIOError(io_exception); end
    def onRequestFinish(time); end
    def onResponseStart(); end
    def onResponseFinish();end
    def onUpdateFinish(makeRequest, time);end
  end
end


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'dialog_tui'

require 'minitest/autorun'


text:
var recycleBin = require('../../../../../lib/rules/util').values.recycleBin;

module.exports = function(req, res) {
  res.json({
    ec: 0,
    list: recycleBin.list()
  });
};


text:
// Package s3 provides a storagedriver.StorageDriver implementation to
// store blobs in Amazon S3 cloud storage.
//
// This package leverages the official aws client library for interfacing with
// S3.
//
// Because S3 is a key, value store the Stat call does not support last modification
// time for directories (directories are an abstraction for key, value stores)
//
// Keep in mind that S3 guarantees only read-after-write consistency for new
// objects, but no read-after-update or list-after-write consistency.
package s3

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
	"github.com/aws/aws-sdk-go/aws/ec2metadata"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"

	"github.com/docker/distribution/context"
	"github.com/docker/distribution/registry/client/transport"
	storagedriver "github.com/docker/distribution/registry/storage/driver"
	"github.com/docker/distribution/registry/storage/driver/base"
	"github.com/docker/distribution/registry/storage/driver/factory"
)

const driverName = "s3aws"

// minChunkSize defines the minimum multipart upload chunk size
// S3 API requires multipart upload chunks to be at least 5MB
const minChunkSize = 5 << 20

const defaultChunkSize = 2 * minChunkSize

// listMax is the largest amount of objects you can request from S3 in a list call
const listMax = 1000

// validRegions maps known s3 region identifiers to region descriptors
var validRegions = map[string]struct{}{}

//DriverParameters A struct that encapsulates all of the driver parameters after all values have been set
type DriverParameters struct {
	AccessKey      string
	SecretKey      string
	Bucket         string
	Region         string
	RegionEndpoint string
	Encrypt        bool
	KeyID          string
	Secure         bool
	ChunkSize      int64
	RootDirectory  string
	StorageClass   string
	UserAgent      string
}

func init() {
	for _, region := range []string{
		"us-east-1",
		"us-west-1",
		"us-west-2",
		"eu-west-1",
		"eu-central-1",
		"ap-southeast-1",
		"ap-southeast-2",
		"ap-northeast-1",
		"ap-northeast-2",
		"sa-east-1",
	} {
		validRegions[region] = struct{}{}
	}

	// Register this as the default s3 driver in addition to s3aws
	factory.Register("s3", &s3DriverFactory{})
	factory.Register(driverName, &s3DriverFactory{})
}

// s3DriverFactory implements the factory.StorageDriverFactory interface
type s3DriverFactory struct{}

func (factory *s3DriverFactory) Create(parameters map[string]interface{}) (storagedriver.StorageDriver, error) {
	return FromParameters(parameters)
}

type driver struct {
	S3            *s3.S3
	Bucket        string
	ChunkSize     int64
	Encrypt       bool
	KeyID         string
	RootDirectory string
	StorageClass  string
}

type baseEmbed struct {
	base.Base
}

// Driver is a storagedriver.StorageDriver implementation backed by Amazon S3
// Objects are stored at absolute keys in the provided bucket.
type Driver struct {
	baseEmbed
}

// FromParameters constructs a new Driver with a given parameters map
// Required parameters:
// - accesskey
// - secretkey
// - region
// - bucket
// - encrypt
func FromParameters(parameters map[string]interface{}) (*Driver, error) {
	// Providing no values for these is valid in case the user is authenticating
	// with an IAM on an ec2 instance (in which case the instance credentials will
	// be summoned when GetAuth is called)
	accessKey := parameters["accesskey"]
	if accessKey == nil {
		accessKey = ""
	}
	secretKey := parameters["secretkey"]
	if secretKey == nil {
		secretKey = ""
	}

	regionEndpoint := parameters["regionendpoint"]
	if regionEndpoint == nil {
		regionEndpoint = ""
	}

	regionName, ok := parameters["region"]
	if regionName == nil || fmt.Sprint(regionName) == "" {
		return nil, fmt.Errorf("No region parameter provided")
	}
	region := fmt.Sprint(regionName)
	// Don't check the region value if a custom endpoint is provided.
	if regionEndpoint == "" {
		if _, ok = validRegions[region]; !ok {
			return nil, fmt.Errorf("Invalid region provided: %v", region)
		}
	}

	bucket := parameters["bucket"]
	if bucket == nil || fmt.Sprint(bucket) == "" {
		return nil, fmt.Errorf("No bucket parameter provided")
	}

	encryptBool := false
	encrypt := parameters["encrypt"]
	switch encrypt := encrypt.(type) {
	case string:
		b, err := strconv.ParseBool(encrypt)
		if err != nil {
			return nil, fmt.Errorf("The encrypt parameter should be a boolean")
		}
		encryptBool = b
	case bool:
		encryptBool = encrypt
	case nil:
		// do nothing
	default:
		return nil, fmt.Errorf("The encrypt parameter should be a boolean")
	}

	secureBool := true
	secure := parameters["secure"]
	switch secure := secure.(type) {
	case string:
		b, err := strconv.ParseBool(secure)
		if err != nil {
			return nil, fmt.Errorf("The secure parameter should be a boolean")
		}
		secureBool = b
	case bool:
		secureBool = secure
	case nil:
		// do nothing
	default:
		return nil, fmt.Errorf("The secure parameter should be a boolean")
	}

	keyID := parameters["keyid"]
	if keyID == nil {
		keyID = ""
	}

	chunkSize := int64(defaultChunkSize)
	chunkSizeParam := parameters["chunksize"]
	switch v := chunkSizeParam.(type) {
	case string:
		vv, err := strconv.ParseInt(v, 0, 64)
		if err != nil {
			return nil, fmt.Errorf("chunksize parameter must be an integer, %v invalid", chunkSizeParam)
		}
		chunkSize = vv
	case int64:
		chunkSize = v
	case int, uint, int32, uint32, uint64:
		chunkSize = reflect.ValueOf(v).Convert(reflect.TypeOf(chunkSize)).Int()
	case nil:
		// do nothing
	default:
		return nil, fmt.Errorf("invalid value for chunksize: %#v", chunkSizeParam)
	}

	if chunkSize < minChunkSize {
		return nil, fmt.Errorf("The chunksize %#v parameter should be a number that is larger than or equal to %d", chunkSize, minChunkSize)
	}

	rootDirectory := parameters["rootdirectory"]
	if rootDirectory == nil {
		rootDirectory = ""
	}

	storageClass := s3.StorageClassStandard
	storageClassParam := parameters["storageclass"]
	if storageClassParam != nil {
		storageClassString, ok := storageClassParam.(string)
		if !ok {
			return nil, fmt.Errorf("The storageclass parameter must be one of %v, %v invalid", []string{s3.StorageClassStandard, s3.StorageClassReducedRedundancy}, storageClassParam)
		}
		// All valid storage class parameters are UPPERCASE, so be a bit more flexible here
		storageClassString = strings.ToUpper(storageClassString)
		if storageClassString != s3.StorageClassStandard && storageClassString != s3.StorageClassReducedRedundancy {
			return nil, fmt.Errorf("The storageclass parameter must be one of %v, %v invalid", []string{s3.StorageClassStandard, s3.StorageClassReducedRedundancy}, storageClassParam)
		}
		storageClass = storageClassString
	}

	userAgent := parameters["useragent"]
	if userAgent == nil {
		userAgent = ""
	}

	params := DriverParameters{
		fmt.Sprint(accessKey),
		fmt.Sprint(secretKey),
		fmt.Sprint(bucket),
		region,
		fmt.Sprint(regionEndpoint),
		encryptBool,
		fmt.Sprint(keyID),
		secureBool,
		chunkSize,
		fmt.Sprint(rootDirectory),
		storageClass,
		fmt.Sprint(userAgent),
	}

	return New(params)
}

// New constructs a new Driver with the given AWS credentials, region, encryption flag, and
// bucketName
func New(params DriverParameters) (*Driver, error) {
	awsConfig := aws.NewConfig()
	var creds *credentials.Credentials
	if params.RegionEndpoint == "" {
		creds = credentials.NewChainCredentials([]credentials.Provider{
			&credentials.StaticProvider{
				Value: credentials.Value{
					AccessKeyID:     params.AccessKey,
					SecretAccessKey: params.SecretKey,
				},
			},
			&credentials.EnvProvider{},
			&credentials.SharedCredentialsProvider{},
			&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
		})

	} else {
		creds = credentials.NewChainCredentials([]credentials.Provider{
			&credentials.StaticProvider{
				Value: credentials.Value{
					AccessKeyID:     params.AccessKey,
					SecretAccessKey: params.SecretKey,
				},
			},
			&credentials.EnvProvider{},
		})
		awsConfig.WithS3ForcePathStyle(true)
		awsConfig.WithEndpoint(params.RegionEndpoint)
	}

	awsConfig.WithCredentials(creds)
	awsConfig.WithRegion(params.Region)
	awsConfig.WithDisableSSL(!params.Secure)

	if params.UserAgent != "" {
		awsConfig.WithHTTPClient(&http.Client{
			Transport: transport.NewTransport(http.DefaultTransport, transport.NewHeaderRequestModifier(http.Header{http.CanonicalHeaderKey("User-Agent"): []string{params.UserAgent}})),
		})
	}

	s3obj := s3.New(session.New(awsConfig))

	// TODO Currently multipart uploads have no timestamps, so this would be unwise
	// if you initiated a new s3driver while another one is running on the same bucket.
	// multis, _, err := bucket.ListMulti("", "")
	// if err != nil {
	// 	return nil, err
	// }

	// for _, multi := range multis {
	// 	err := multi.Abort()
	// 	//TODO appropriate to do this error checking?
	// 	if err != nil {
	// 		return nil, err
	// 	}
	// }

	d := &driver{
		S3:            s3obj,
		Bucket:        params.Bucket,
		ChunkSize:     params.ChunkSize,
		Encrypt:       params.Encrypt,
		KeyID:         params.KeyID,
		RootDirectory: params.RootDirectory,
		StorageClass:  params.StorageClass,
	}

	return &Driver{
		baseEmbed: baseEmbed{
			Base: base.Base{
				StorageDriver: d,
			},
		},
	}, nil
}

// Implement the storagedriver.StorageDriver interface

func (d *driver) Name() string {
	return driverName
}

// GetContent retrieves the content stored at "path" as a []byte.
func (d *driver) GetContent(ctx context.Context, path string) ([]byte, error) {
	reader, err := d.Reader(ctx, path, 0)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(reader)
}

// PutContent stores the []byte content at a location designated by "path".
func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error {
	_, err := d.S3.PutObject(&s3.PutObjectInput{
		Bucket:               aws.String(d.Bucket),
		Key:                  aws.String(d.s3Path(path)),
		ContentType:          d.getContentType(),
		ACL:                  d.getACL(),
		ServerSideEncryption: d.getEncryptionMode(),
		SSEKMSKeyId:          d.getSSEKMSKeyID(),
		StorageClass:         d.getStorageClass(),
		Body:                 bytes.NewReader(contents),
	})
	return parseError(path, err)
}

// Reader retrieves an io.ReadCloser for the content stored at "path" with a
// given byte offset.
func (d *driver) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) {
	resp, err := d.S3.GetObject(&s3.GetObjectInput{
		Bucket: aws.String(d.Bucket),
		Key:    aws.String(d.s3Path(path)),
		Range:  aws.String("bytes=" + strconv.FormatInt(offset, 10) + "-"),
	})

	if err != nil {
		if s3Err, ok := err.(awserr.Error); ok && s3Err.Code() == "InvalidRange" {
			return ioutil.NopCloser(bytes.NewReader(nil)), nil
		}

		return nil, parseError(path, err)
	}
	return resp.Body, nil
}

// Writer returns a FileWriter which will store the content written to it
// at the location designated by "path" after the call to Commit.
func (d *driver) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) {
	key := d.s3Path(path)
	if !append {
		// TODO (brianbland): cancel other uploads at this path
		resp, err := d.S3.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
			Bucket:               aws.String(d.Bucket),
			Key:                  aws.String(key),
			ContentType:          d.getContentType(),
			ACL:                  d.getACL(),
			ServerSideEncryption: d.getEncryptionMode(),
			SSEKMSKeyId:          d.getSSEKMSKeyID(),
			StorageClass:         d.getStorageClass(),
		})
		if err != nil {
			return nil, err
		}
		return d.newWriter(key, *resp.UploadId, nil), nil
	}
	resp, err := d.S3.ListMultipartUploads(&s3.ListMultipartUploadsInput{
		Bucket: aws.String(d.Bucket),
		Prefix: aws.String(key),
	})
	if err != nil {
		return nil, parseError(path, err)
	}

	for _, multi := range resp.Uploads {
		if key != *multi.Key {
			continue
		}
		resp, err := d.S3.ListParts(&s3.ListPartsInput{
			Bucket:   aws.String(d.Bucket),
			Key:      aws.String(key),
			UploadId: multi.UploadId,
		})
		if err != nil {
			return nil, parseError(path, err)
		}
		var multiSize int64
		for _, part := range resp.Parts {
			multiSize += *part.Size
		}
		return d.newWriter(key, *multi.UploadId, resp.Parts), nil
	}
	return nil, storagedriver.PathNotFoundError{Path: path}
}

// Stat retrieves the FileInfo for the given path, including the current size
// in bytes and the creation time.
func (d *driver) Stat(ctx context.Context, path string) (storagedriver.FileInfo, error) {
	resp, err := d.S3.ListObjects(&s3.ListObjectsInput{
		Bucket:  aws.String(d.Bucket),
		Prefix:  aws.String(d.s3Path(path)),
		MaxKeys: aws.Int64(1),
	})
	if err != nil {
		return nil, err
	}

	fi := storagedriver.FileInfoFields{
		Path: path,
	}

	if len(resp.Contents) == 1 {
		if *resp.Contents[0].Key != d.s3Path(path) {
			fi.IsDir = true
		} else {
			fi.IsDir = false
			fi.Size = *resp.Contents[0].Size
			fi.ModTime = *resp.Contents[0].LastModified
		}
	} else if len(resp.CommonPrefixes) == 1 {
		fi.IsDir = true
	} else {
		return nil, storagedriver.PathNotFoundError{Path: path}
	}

	return storagedriver.FileInfoInternal{FileInfoFields: fi}, nil
}

// List returns a list of the objects that are direct descendants of the given path.
func (d *driver) List(ctx context.Context, opath string) ([]string, error) {
	path := opath
	if path != "/" && path[len(path)-1] != '/' {
		path = path + "/"
	}

	// This is to cover for the cases when the rootDirectory of the driver is either "" or "/".
	// In those cases, there is no root prefix to replace and we must actually add a "/" to all
	// results in order to keep them as valid paths as recognized by storagedriver.PathRegexp
	prefix := ""
	if d.s3Path("") == "" {
		prefix = "/"
	}

	resp, err := d.S3.ListObjects(&s3.ListObjectsInput{
		Bucket:    aws.String(d.Bucket),
		Prefix:    aws.String(d.s3Path(path)),
		Delimiter: aws.String("/"),
		MaxKeys:   aws.Int64(listMax),
	})
	if err != nil {
		return nil, parseError(opath, err)
	}

	files := []string{}
	directories := []string{}

	for {
		for _, key := range resp.Contents {
			files = append(files, strings.Replace(*key.Key, d.s3Path(""), prefix, 1))
		}

		for _, commonPrefix := range resp.CommonPrefixes {
			commonPrefix := *commonPrefix.Prefix
			directories = append(directories, strings.Replace(commonPrefix[0:len(commonPrefix)-1], d.s3Path(""), prefix, 1))
		}

		if *resp.IsTruncated {
			resp, err = d.S3.ListObjects(&s3.ListObjectsInput{
				Bucket:    aws.String(d.Bucket),
				Prefix:    aws.String(d.s3Path(path)),
				Delimiter: aws.String("/"),
				MaxKeys:   aws.Int64(listMax),
				Marker:    resp.NextMarker,
			})
			if err != nil {
				return nil, err
			}
		} else {
			break
		}
	}

	if opath != "/" {
		if len(files) == 0 && len(directories) == 0 {
			// Treat empty response as missing directory, since we don't actually
			// have directories in s3.
			return nil, storagedriver.PathNotFoundError{Path: opath}
		}
	}

	return append(files, directories...), nil
}

// Move moves an object stored at sourcePath to destPath, removing the original
// object.
func (d *driver) Move(ctx context.Context, sourcePath string, destPath string) error {
	/* This is terrible, but aws doesn't have an actual move. */
	_, err := d.S3.CopyObject(&s3.CopyObjectInput{
		Bucket:               aws.String(d.Bucket),
		Key:                  aws.String(d.s3Path(destPath)),
		ContentType:          d.getContentType(),
		ACL:                  d.getACL(),
		ServerSideEncryption: d.getEncryptionMode(),
		SSEKMSKeyId:          d.getSSEKMSKeyID(),
		StorageClass:         d.getStorageClass(),
		CopySource:           aws.String(d.Bucket + "/" + d.s3Path(sourcePath)),
	})
	if err != nil {
		return parseError(sourcePath, err)
	}

	return d.Delete(ctx, sourcePath)
}

// Delete recursively deletes all objects stored at "path" and its subpaths.
func (d *driver) Delete(ctx context.Context, path string) error {
	resp, err := d.S3.ListObjects(&s3.ListObjectsInput{
		Bucket: aws.String(d.Bucket),
		Prefix: aws.String(d.s3Path(path)),
	})
	if err != nil || len(resp.Contents) == 0 {
		return storagedriver.PathNotFoundError{Path: path}
	}

	s3Objects := make([]*s3.ObjectIdentifier, 0, listMax)

	for len(resp.Contents) > 0 {
		for _, key := range resp.Contents {
			s3Objects = append(s3Objects, &s3.ObjectIdentifier{
				Key: key.Key,
			})
		}

		_, err := d.S3.DeleteObjects(&s3.DeleteObjectsInput{
			Bucket: aws.String(d.Bucket),
			Delete: &s3.Delete{
				Objects: s3Objects,
				Quiet:   aws.Bool(false),
			},
		})
		if err != nil {
			return nil
		}

		resp, err = d.S3.ListObjects(&s3.ListObjectsInput{
			Bucket: aws.String(d.Bucket),
			Prefix: aws.String(d.s3Path(path)),
		})
		if err != nil {
			return err
		}
	}

	return nil
}

// URLFor returns a URL which may be used to retrieve the content stored at the given path.
// May return an UnsupportedMethodErr in certain StorageDriver implementations.
func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
	methodString := "GET"
	method, ok := options["method"]
	if ok {
		methodString, ok = method.(string)
		if !ok || (methodString != "GET" && methodString != "HEAD") {
			return "", storagedriver.ErrUnsupportedMethod{}
		}
	}

	expiresIn := 20 * time.Minute
	expires, ok := options["expiry"]
	if ok {
		et, ok := expires.(time.Time)
		if ok {
			expiresIn = et.Sub(time.Now())
		}
	}

	var req *request.Request

	switch methodString {
	case "GET":
		req, _ = d.S3.GetObjectRequest(&s3.GetObjectInput{
			Bucket: aws.String(d.Bucket),
			Key:    aws.String(d.s3Path(path)),
		})
	case "HEAD":
		req, _ = d.S3.HeadObjectRequest(&s3.HeadObjectInput{
			Bucket: aws.String(d.Bucket),
			Key:    aws.String(d.s3Path(path)),
		})
	default:
		panic("unreachable")
	}

	return req.Presign(expiresIn)
}

func (d *driver) s3Path(path string) string {
	return strings.TrimLeft(strings.TrimRight(d.RootDirectory, "/")+path, "/")
}

// S3BucketKey returns the s3 bucket key for the given storage driver path.
func (d *Driver) S3BucketKey(path string) string {
	return d.StorageDriver.(*driver).s3Path(path)
}

func parseError(path string, err error) error {
	if s3Err, ok := err.(awserr.Error); ok && s3Err.Code() == "NoSuchKey" {
		return storagedriver.PathNotFoundError{Path: path}
	}

	return err
}

func (d *driver) getEncryptionMode() *string {
	if !d.Encrypt {
		return nil
	}
	if d.KeyID == "" {
		return aws.String("AES256")
	}
	return aws.String("aws:kms")
}

func (d *driver) getSSEKMSKeyID() *string {
	if d.KeyID != "" {
		return aws.String(d.KeyID)
	}
	return nil
}

func (d *driver) getContentType() *string {
	return aws.String("application/octet-stream")
}

func (d *driver) getACL() *string {
	return aws.String("private")
}

func (d *driver) getStorageClass() *string {
	return aws.String(d.StorageClass)
}

// writer attempts to upload parts to S3 in a buffered fashion where the last
// part is at least as large as the chunksize, so the multipart upload could be
// cleanly resumed in the future. This is violated if Close is called after less
// than a full chunk is written.
type writer struct {
	driver      *driver
	key         string
	uploadID    string
	parts       []*s3.Part
	size        int64
	readyPart   []byte
	pendingPart []byte
	closed      bool
	committed   bool
	cancelled   bool
}

func (d *driver) newWriter(key, uploadID string, parts []*s3.Part) storagedriver.FileWriter {
	var size int64
	for _, part := range parts {
		size += *part.Size
	}
	return &writer{
		driver:   d,
		key:      key,
		uploadID: uploadID,
		parts:    parts,
		size:     size,
	}
}

func (w *writer) Write(p []byte) (int, error) {
	if w.closed {
		return 0, fmt.Errorf("already closed")
	} else if w.committed {
		return 0, fmt.Errorf("already committed")
	} else if w.cancelled {
		return 0, fmt.Errorf("already cancelled")
	}

	// If the last written part is smaller than minChunkSize, we need to make a
	// new multipart upload :sadface:
	if len(w.parts) > 0 && int(*w.parts[len(w.parts)-1].Size) < minChunkSize {
		var completedParts []*s3.CompletedPart
		for _, part := range w.parts {
			completedParts = append(completedParts, &s3.CompletedPart{
				ETag:       part.ETag,
				PartNumber: part.PartNumber,
			})
		}
		_, err := w.driver.S3.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
			Bucket:   aws.String(w.driver.Bucket),
			Key:      aws.String(w.key),
			UploadId: aws.String(w.uploadID),
			MultipartUpload: &s3.CompletedMultipartUpload{
				Parts: completedParts,
			},
		})
		if err != nil {
			w.driver.S3.AbortMultipartUpload(&s3.AbortMultipartUploadInput{
				Bucket:   aws.String(w.driver.Bucket),
				Key:      aws.String(w.key),
				UploadId: aws.String(w.uploadID),
			})
			return 0, err
		}

		resp, err := w.driver.S3.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
			Bucket:               aws.String(w.driver.Bucket),
			Key:                  aws.String(w.key),
			ContentType:          w.driver.getContentType(),
			ACL:                  w.driver.getACL(),
			ServerSideEncryption: w.driver.getEncryptionMode(),
			StorageClass:         w.driver.getStorageClass(),
		})
		if err != nil {
			return 0, err
		}
		w.uploadID = *resp.UploadId

		// If the entire written file is smaller than minChunkSize, we need to make
		// a new part from scratch :double sad face:
		if w.size < minChunkSize {
			resp, err := w.driver.S3.GetObject(&s3.GetObjectInput{
				Bucket: aws.String(w.driver.Bucket),
				Key:    aws.String(w.key),
			})
			defer resp.Body.Close()
			if err != nil {
				return 0, err
			}
			w.parts = nil
			w.readyPart, err = ioutil.ReadAll(resp.Body)
			if err != nil {
				return 0, err
			}
		} else {
			// Otherwise we can use the old file as the new first part
			copyPartResp, err := w.driver.S3.UploadPartCopy(&s3.UploadPartCopyInput{
				Bucket:     aws.String(w.driver.Bucket),
				CopySource: aws.String(w.driver.Bucket + "/" + w.key),
				Key:        aws.String(w.key),
				PartNumber: aws.Int64(1),
				UploadId:   resp.UploadId,
			})
			if err != nil {
				return 0, err
			}
			w.parts = []*s3.Part{
				{
					ETag:       copyPartResp.CopyPartResult.ETag,
					PartNumber: aws.Int64(1),
					Size:       aws.Int64(w.size),
				},
			}
		}
	}

	var n int

	for len(p) > 0 {
		// If no parts are ready to write, fill up the first part
		if neededBytes := int(w.driver.ChunkSize) - len(w.readyPart); neededBytes > 0 {
			if len(p) >= neededBytes {
				w.readyPart = append(w.readyPart, p[:neededBytes]...)
				n += neededBytes
				p = p[neededBytes:]
			} else {
				w.readyPart = append(w.readyPart, p...)
				n += len(p)
				p = nil
			}
		}

		if neededBytes := int(w.driver.ChunkSize) - len(w.pendingPart); neededBytes > 0 {
			if len(p) >= neededBytes {
				w.pendingPart = append(w.pendingPart, p[:neededBytes]...)
				n += neededBytes
				p = p[neededBytes:]
				err := w.flushPart()
				if err != nil {
					w.size += int64(n)
					return n, err
				}
			} else {
				w.pendingPart = append(w.pendingPart, p...)
				n += len(p)
				p = nil
			}
		}
	}
	w.size += int64(n)
	return n, nil
}

func (w *writer) Size() int64 {
	return w.size
}

func (w *writer) Close() error {
	if w.closed {
		return fmt.Errorf("already closed")
	}
	w.closed = true
	return w.flushPart()
}

func (w *writer) Cancel() error {
	if w.closed {
		return fmt.Errorf("already closed")
	} else if w.committed {
		return fmt.Errorf("already committed")
	}
	w.cancelled = true
	_, err := w.driver.S3.AbortMultipartUpload(&s3.AbortMultipartUploadInput{
		Bucket:   aws.String(w.driver.Bucket),
		Key:      aws.String(w.key),
		UploadId: aws.String(w.uploadID),
	})
	return err
}

func (w *writer) Commit() error {
	if w.closed {
		return fmt.Errorf("already closed")
	} else if w.committed {
		return fmt.Errorf("already committed")
	} else if w.cancelled {
		return fmt.Errorf("already cancelled")
	}
	err := w.flushPart()
	if err != nil {
		return err
	}
	w.committed = true
	var completedParts []*s3.CompletedPart
	for _, part := range w.parts {
		completedParts = append(completedParts, &s3.CompletedPart{
			ETag:       part.ETag,
			PartNumber: part.PartNumber,
		})
	}
	_, err = w.driver.S3.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
		Bucket:   aws.String(w.driver.Bucket),
		Key:      aws.String(w.key),
		UploadId: aws.String(w.uploadID),
		MultipartUpload: &s3.CompletedMultipartUpload{
			Parts: completedParts,
		},
	})
	if err != nil {
		w.driver.S3.AbortMultipartUpload(&s3.AbortMultipartUploadInput{
			Bucket:   aws.String(w.driver.Bucket),
			Key:      aws.String(w.key),
			UploadId: aws.String(w.uploadID),
		})
		return err
	}
	return nil
}

// flushPart flushes buffers to write a part to S3.
// Only called by Write (with both buffers full) and Close/Commit (always)
func (w *writer) flushPart() error {
	if len(w.readyPart) == 0 && len(w.pendingPart) == 0 {
		// nothing to write
		return nil
	}
	if len(w.pendingPart) < int(w.driver.ChunkSize) {
		// closing with a small pending part
		// combine ready and pending to avoid writing a small part
		w.readyPart = append(w.readyPart, w.pendingPart...)
		w.pendingPart = nil
	}

	partNumber := aws.Int64(int64(len(w.parts) + 1))
	resp, err := w.driver.S3.UploadPart(&s3.UploadPartInput{
		Bucket:     aws.String(w.driver.Bucket),
		Key:        aws.String(w.key),
		PartNumber: partNumber,
		UploadId:   aws.String(w.uploadID),
		Body:       bytes.NewReader(w.readyPart),
	})
	if err != nil {
		return err
	}
	w.parts = append(w.parts, &s3.Part{
		ETag:       resp.ETag,
		PartNumber: partNumber,
		Size:       aws.Int64(int64(len(w.readyPart))),
	})
	w.readyPart = w.pendingPart
	w.pendingPart = nil
	return nil
}


text:
package com.opengamma.analytics.financial.model.interestrate.definition;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.Validate;
import org.threeten.bp.ZonedDateTime;

import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.volatility.curve.VolatilityCurve;
import com.opengamma.util.ArgumentChecker;

/**
 *
 */
public class HullWhiteTwoFactorDataBundle extends StandardDiscountBondModelDataBundle {
  private final double _reversionSpeed1;
  private final double _reversionSpeed2;
  private final double _meanReversionLevel;
  private final YieldAndDiscountCurve _forwardRateCurve;
  private final VolatilityCurve _volatilityCurve2;
  private final double _correlation;

  public HullWhiteTwoFactorDataBundle(final YieldAndDiscountCurve shortRateCurve, final VolatilityCurve volatilityCurve1, final VolatilityCurve volatilityCurve2, final ZonedDateTime date,
      final double reversionSpeed1, final double reversionSpeed2, final double meanReversionLevel, final YieldAndDiscountCurve forwardRateCurve, final double correlation) {
    super(shortRateCurve, volatilityCurve1, date);
    Validate.notNull(volatilityCurve2, "second volatility curve");
    Validate.notNull(forwardRateCurve, "forward rate curve");
    if (!ArgumentChecker.isInRangeInclusive(-1, 1, correlation)) {
      throw new IllegalArgumentException("Correlation must be >= -1 and <= 1");
    }
    _reversionSpeed1 = reversionSpeed1;
    _reversionSpeed2 = reversionSpeed2;
    _meanReversionLevel = meanReversionLevel;
    _forwardRateCurve = forwardRateCurve;
    _volatilityCurve2 = volatilityCurve2;
    _correlation = correlation;
  }

  public double getFirstSpeed() {
    return _reversionSpeed1;
  }

  public double getSecondSpeed() {
    return _reversionSpeed2;
  }

  public double getMeanReversionLevel() {
    return _meanReversionLevel;
  }

  public double getForwardRate(final double t) {
    return _forwardRateCurve.getInterestRate(t);
  }

  public YieldAndDiscountCurve getForwardRateCurve() {
    return _forwardRateCurve;
  }

  public double getSecondVolatility(final double t) {
    return _volatilityCurve2.getVolatility(t);
  }

  public double getCorrelation() {
    return _correlation;
  }

  public VolatilityCurve getSecondVolatilityCurve() {
    return _volatilityCurve2;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    long temp;
    temp = Double.doubleToLongBits(_correlation);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    result = prime * result + ((_forwardRateCurve == null) ? 0 : _forwardRateCurve.hashCode());
    temp = Double.doubleToLongBits(_meanReversionLevel);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    temp = Double.doubleToLongBits(_reversionSpeed1);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    temp = Double.doubleToLongBits(_reversionSpeed2);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    result = prime * result + ((_volatilityCurve2 == null) ? 0 : _volatilityCurve2.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (!super.equals(obj)) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final HullWhiteTwoFactorDataBundle other = (HullWhiteTwoFactorDataBundle) obj;
    if (Double.doubleToLongBits(_correlation) != Double.doubleToLongBits(other._correlation)) {
      return false;
    }
    if (!ObjectUtils.equals(_forwardRateCurve, other._forwardRateCurve)) {
      return false;
    }
    if (Double.doubleToLongBits(_meanReversionLevel) != Double.doubleToLongBits(other._meanReversionLevel)) {
      return false;
    }
    if (Double.doubleToLongBits(_reversionSpeed1) != Double.doubleToLongBits(other._reversionSpeed1)) {
      return false;
    }
    if (Double.doubleToLongBits(_reversionSpeed2) != Double.doubleToLongBits(other._reversionSpeed2)) {
      return false;
    }
    return ObjectUtils.equals(_volatilityCurve2, other._volatilityCurve2);
  }
}


text:
<?
	# $Id: unrefreshed.php,v 1.1.2.3 2003-02-26 16:17:06 dan Exp $
	#
	# Copyright (c) 1998-2001 DVL Software Limited

   require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php');
   require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php');
   require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php');
	require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php');
   require_once($_SERVER['DOCUMENT_ROOT'] . '/../classes/ports-unrefreshed.php');

#$Debug=1;

   freshports_Start('Unrefreshed ports',
               'freshports - new ports, applications',
               'FreeBSD, index, applications, ports');

#phpinfo();

function freshports_IfNull($Value1, $Value2='&nbsp') {
	if (IsSet($Value1)) {
		$result = $Value1;
	} else {
		$result = $Value2;
	}

	return $result;

}

function freshports_DisplayUnrefreshedPorts($dbh) {
	GLOBAL $User;
	$Ports = new PortsUnrefreshed($dbh);

	$NumRows = $Ports->FetchAll();

	if ($NumRows > 0) {
		if ($User->type == SUPER_USER) {
?>
<FORM ACTION="<? echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<?php
		}
?>

Port ID
Port Name
Category
Category ID
Commit Log ID
<?php
		if ($User->type == SUPER_USER) {
?>
Monitor
Ignore
Mark as Refreshed
Reason
Date Ignored
<?php
		}

		for ($i = 0; $i < $NumRows; $i++) {
			$Ports->FetchNth($i);
			echo "
\n";

			$ID = $Ports->commit_log_id . '_' . $Ports->port_id;

?>

<INPUT NAME="port_id[]"        TYPE="hidden" value="<?php echo $Ports->port_id;       ?>">
<INPUT NAME="commit_log_id[]"  TYPE="hidden" value="<?php echo $Ports->commit_log_id; ?>"><?php
			echo $Ports->port_id . '	' . "\n";
			echo 'category_name . '/' . $Ports->port_name . '/">' . $Ports->port_name  . '	' . "\n";
			echo ''                  . $Ports->category_id   . '	';
			echo 'category_name . '/">' . $Ports->category_name  . '	' . "\n";
			echo ''    . $Ports->commit_log_id . ' '. freshports_Commit_Link($Ports->message_id) . ' ' . freshports_Email_Link($Ports->message_id) . '	' . "\n";
			if ($User->type == SUPER_USER) {
?>
<INPUT NAME="action[<?php echo $ID;?>]" TYPE="RADIO" VALUE="Monitor"<?php if (!IsSet($Ports->date_ignored)) echo " CHECKED"; ?>>
<INPUT NAME="action[<?php echo $ID;?>]" TYPE="RADIO" VALUE="Ignore" <?php if ( IsSet($Ports->date_ignored)) echo " CHECKED"; ?>>
<INPUT NAME="action[<?php echo $ID;?>]" TYPE="RADIO" VALUE="Reset">
<INPUT NAME="reason[<?php echo $ID;?>]" TYPE="text" SIZE="18" VALUE="<?php echo $Ports->reason; ?>">
<INPUT NAME="date[<?php   echo $ID;?>]" TYPE="hidden"  VALUE="<?php echo $Ports->date_ignored; ?>"><?php echo freshports_IfNull($Ports->date_ignored); ?>

<?php
			}
		}
?>

<?php
		if ($User->type == SUPER_USER) {
?>

<INPUT TYPE="submit" VALUE="Update">

</FORM>
<?php
		}
	} else {
		echo '
All ports are refreshed
';
	}
}

if (IsSet($_POST['port_id']) && $User->type == SUPER_USER ) {
	#
	# OK, time to update things!
	#
   require_once($_SERVER['DOCUMENT_ROOT'] . '/../classes/commit_log_ports.php');
   require_once($_SERVER['DOCUMENT_ROOT'] . '/../classes/commit_log_ports_ignore.php');

  	pg_exec ($db, 'BEGIN');
  	$CommitOrRollback = 'COMMIT';

	$CommitLogPort       = new Commit_Log_Ports       ($db);
	$CommitLogPortIgnore = new Commit_Log_Ports_Ignore($db);

	while (list($key, $port_id) = each($_POST['port_id'])) {
		$commit_log_id = $_POST['commit_log_id'][$key];

		$ID = $commit_log_id . '_' . $port_id;

		$action        = $_POST['action'][$ID];
		$reason        = $_POST['reason'][$ID];
		$date          = $_POST['date'][$ID];

/*
		echo "\$key='$key' :: \$port_id=$port_id";
		echo " :: commit_log_id='$commit_log_id'";

		echo " :: \$ID='$ID'";
		echo " :: action='"        . $action . "'";
		echo " :: reason='"        . $reason . "'";
		echo " :: date  ='"        . $date   . "'";
		echo "
\n";
*/

		$CommitLogPort->CommitLogIDSet      ($commit_log_id);
		$CommitLogPort->PortIDSet           ($port_id);

		$CommitLogPortIgnore->CommitLogIDSet($commit_log_id);
		$CommitLogPortIgnore->PortIDSet     ($port_id);

		switch ($action) {
			case 'Monitor':
				# remove the entry from commit_log_port_ignore if one exists
				if (IsSet($date) && chr($date) != 0) {
					$numrows = $CommitLogPortIgnore->delete();
				}
				break;

			case 'Ignore':
				if (!IsSet($reason) || chr($reason) == 0) {
					$reason = 'none given';
				}
				$CommitLogPortIgnore->ReasonSet($reason);
				$numrows = $CommitLogPortIgnore->insert();

				break;

			case 'Reset':
				$numrows = $CommitLogPort->NeedsRefreshClear();
				break;

			default:
				die("unknown action found: '$action'");
		}

		if ($numrows != 1) {
			$CommitOrRollback = 'ROLLBACK';
		}
	}
	pg_exec ($db, $CommitOrRollback);
}

?>
<TABLE WIDTH="<? echo $TableWidth; ?>" BORDER="0" ALIGN="center">

	<? echo freshports_PageBannerText("Unrefreshed ports"); ?>

This is a list of ports in our database which need to be refreshed.
Ports in our datbase which need refreshing do not match what's in the ports tree.  The most common reason
for this situation is a port error.

<?php freshports_DisplayUnrefreshedPorts($db); ?>

	<?
	freshports_SideBar();
	?>

<?
freshports_ShowFooter();
?>


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: Qt Linguist Manual: TS File Format</title>
  <link rel="prev" href="linguist-programmers.html" />
  <link rel="contents" href="linguist-manual.html" />
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

[Previous: Qt Linguist Manual: Programmers]
[Contents]

Qt Linguist Manual: TS File Format

The <tt>.ts</tt> file format used by Qt Linguist is described by the DTD presented below, which we include for your convenience. Be aware that the format may change in future Qt releases.

 <!--
  !
  ! Some notes to the DTD:
  !
  ! The location element is set as optional since it was introduced first in Qt 4.2.
  !
   -->
 <!--
  ! Macro used in order to escape byte entities not allowed in an xml document
  ! for instance, only #x9, #xA and #xD are allowed characters below #x20.
  -->
 <!ENTITY % evilstring '(#PCDATA | byte)*' >
 <!ELEMENT byte EMPTY>
 <!ATTLIST byte
           value CDATA #REQUIRED>
 <!ELEMENT TS (defaultcodec?, context+) >
 <!ATTLIST TS
           version CDATA #IMPLIED
           language CDATA #IMPLIED>
 <!ELEMENT defaultcodec (#PCDATA) >
 <!ELEMENT context (name, comment?, message+) >
 <!ATTLIST context
           encoding CDATA #IMPLIED>
 <!ELEMENT name %evilstring; >
 <!ELEMENT comment %evilstring; >
 <!ELEMENT message (location?, source, comment?, translation) >
 <!ATTLIST message
           encoding CDATA #IMPLIED
           numerus (yes|no) "no">
 <!ELEMENT location EMPTY>
 <!ATTLIST location
           filename CDATA #REQUIRED
           line CDATA #REQUIRED>
 <!ELEMENT source %evilstring;>
 <!--
  ! The following should really say one evilstring macro or several numerusform elements,
  ! but the DTD can't express this.
   -->
 <!ELEMENT translation (#PCDATA|byte|numerusform)* >
 <!ATTLIST translation
           type (unfinished|obsolete) #IMPLIED
           encoding CDATA #IMPLIED>
 <!ELEMENT numerusform %evilstring; >

[Previous: Qt Linguist Manual: Programmers]
[Contents]

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
require 'active_record'
require 'logger'

ActiveRecord::Base.establish_connection
ActiveRecord::Base.logger = Logger.new(Pathname.new(File.expand_path('../debug.log', __FILE__)))
ActiveRecord::Migration.verbose = false

ActiveRecord::Schema.define do
  create_table :users, :force => true do |t|
    t.column :name, :string
    t.column :username, :string
    t.column :password, :string
    t.column :activated, :boolean
    t.column :suspended_at, :datetime
    t.column :logins, :integer, :default => 0
    t.column :created_at, :datetime
    t.column :updated_at, :datetime
  end
end


text:
namespace {

// The minimum width of the inline disposition tab contents.
const int kMinInlineDispositionWidth = 300;

// The minimum height of the inline disposition tab contents.
const int kMinInlineDispositionHeight = 300;

}  // namespace

// static
gfx::Size WebIntentPicker::GetDefaultInlineDispositionSize(
    content::WebContents* web_contents) {
  // TODO(gbillock): This size calculation needs more thought.
  gfx::Size tab_size = web_contents->GetView()->GetContainerSize();
  int width = std::max(tab_size.width()/2, kMinInlineDispositionWidth);
  int height = std::max(tab_size.height()/2, kMinInlineDispositionHeight);

  return gfx::Size(width, height);
}

// static
int WebIntentPicker::GetNthStarImageIdFromCWSRating(double rating, int index) {
  // The fractional part of the rating is converted to stars as:
  //   [0, 0.33) -> round down
  //   [0.33, 0.66] -> half star
  //   (0.66, 1) -> round up
  const double kHalfStarMin = 0.33;
  const double kHalfStarMax = 0.66;

  // Add 1 + kHalfStarMax to make values with fraction > 0.66 round up.
  int full_stars = std::floor(rating + 1 - kHalfStarMax);

  if (index < full_stars)
    return IDR_CWS_STAR_FULL;

  // We don't need to test against the upper bound (kHalfStarMax); when the
  // fractional part is greater than kHalfStarMax, full_stars will be rounded
  // up, which means rating - full_stars is negative.
  bool half_star = rating - full_stars >= kHalfStarMin;

  return index == full_stars && half_star ?
      IDR_CWS_STAR_HALF :
      IDR_CWS_STAR_EMPTY;
}