text:
//
//  SKConversionProgressController.m
//  Skim
//
//  Created by Adam Maxwell on 12/6/06.

#import "SKConversionProgressController.h"
#import "NSString_SKExtensions.h"
#import "NSURL_SKExtensions.h"
#import "NSFileManager_SKExtensions.h"
#import "NSInvocation_SKExtensions.h"
#import "SKDocumentController.h"
#import "NSGraphics_SKExtensions.h"
#import "NSDocument_SKExtensions.h"
#import "NSError_SKExtensions.h"

#define PROVIDER_KEY    @"provider"
#define CONSUMER_KEY    @"consumer"
#define INPUTURL_KEY    @"inputURL"
#define PDFDATA_KEY     @"pdfData"
#define TOOLPATH_KEY    @"toolPath"

#define SKDviConversionCommandKey @"SKDviConversionCommand"
#define SKXdvConversionCommandKey @"SKXdvConversionCommand"

#define MIN_BUTTON_WIDTH 90.0

enum {
    SKConversionSucceeded = 0,
    SKConversionFailed = 1
};

@interface SKConversionProgressController (Private)
+ (NSString *)dviToolPath;
+ (NSString *)xdvToolPath;
- (NSData *)newPDFDataWithPostScriptData:(NSData *)psData error:(NSError **)outError;
- (NSData *)newPDFDataWithDVIAtURL:(NSURL *)dviURL toolPath:(NSString *)toolPath fileType:(NSString *)aFileType error:(NSError **)outError;
- (void)conversionCompleted;
- (void)conversionStarted;
- (void)converterWasStopped;
- (void)setButtonTitle:(NSString *)title action:(SEL)action;
@end

#pragma mark Callbacks

static void PSConverterBeginDocumentCallback(void *info)
{
    id delegate = (id)info;
    if ([delegate respondsToSelector:@selector(conversionStarted)])
        [delegate performSelectorOnMainThread:@selector(conversionStarted) withObject:nil waitUntilDone:NO];
}

static void PSConverterEndDocumentCallback(void *info, bool success)
{
    id delegate = (id)info;
    if ([delegate respondsToSelector:@selector(conversionCompleted)])
        [delegate performSelectorOnMainThread:@selector(conversionCompleted) withObject:nil waitUntilDone:NO];
}

CGPSConverterCallbacks SKPSConverterCallbacks = {
    0,
    PSConverterBeginDocumentCallback,
    PSConverterEndDocumentCallback,
    NULL, // haven't seen this called in my testing
    NULL,
    NULL,
    NULL, // messages are usually not useful
    NULL
};

#pragma mark -

@implementation SKConversionProgressController

@synthesize cancelButton, progressBar, textField;

+ (NSData *)newPDFDataWithPostScriptData:(NSData *)psData error:(NSError **)outError {
    return [[[[self alloc] init] autorelease] newPDFDataWithPostScriptData:psData error:outError];
}

+ (NSData *)newPDFDataWithDVIAtURL:(NSURL *)dviURL error:(NSError **)outError {
    NSString *dviToolPath = [self dviToolPath];
    if (dviToolPath)
        return [[[[self alloc] init] autorelease] newPDFDataWithDVIAtURL:dviURL toolPath:dviToolPath fileType:SKDVIDocumentType error:outError];
    else
        NSBeep();
    return nil;
}

+ (NSData *)newPDFDataWithXDVAtURL:(NSURL *)xdvURL error:(NSError **)outError {
    NSString *xdvToolPath = [self xdvToolPath];
    if (xdvToolPath)
        return [[[[self alloc] init] autorelease] newPDFDataWithDVIAtURL:xdvURL toolPath:xdvToolPath fileType:SKXDVDocumentType error:outError];
    else
        NSBeep();
    return nil;
}

- (void)dealloc {
    SKCFDESTROY(converter);
    SKDESTROY(outputFileURL);
    SKDESTROY(outputData);
    SKDESTROY(task);
    SKDESTROY(cancelButton);
    SKDESTROY(progressBar);
    SKDESTROY(textField);
    [super dealloc];
}

- (void)awakeFromNib {
    [[self window] setCollectionBehavior:NSWindowCollectionBehaviorMoveToActiveSpace];
    [progressBar setUsesThreadedAnimation:YES];
    [self setButtonTitle:NSLocalizedString(@"Cancel", @"Button title") action:@selector(cancel:)];
    [[self window] setTitle:[NSString stringWithFormat:NSLocalizedString(@"Converting %@", @"PS conversion progress message"), [[NSDocumentController sharedDocumentController] displayNameForType:fileType]]];
}

- (NSString *)windowNibName { return @"ConversionProgressWindow"; }

- (IBAction)close:(id)sender { [NSApp stopModalWithCode:SKConversionFailed]; }

- (IBAction)cancel:(id)sender {
    if (cancelled == YES) {
        [self converterWasStopped];
    } else {
        cancelled = YES;
        if (converter)
            CGPSConverterAbort(converter);
        else if ([task isRunning])
            [task terminate];
    }
}

- (void)converterWasStopped {
    NSBeep();
    [textField setStringValue:NSLocalizedString(@"Converter already stopped.", @"PS conversion progress message")];
    [self setButtonTitle:NSLocalizedString(@"Close", @"Button title") action:@selector(close:)];
}

- (void)conversionCompleted {
    [textField setStringValue:NSLocalizedString(@"File successfully converted!", @"PS conversion progress message")];
    [progressBar stopAnimation:nil];
    [self setButtonTitle:NSLocalizedString(@"Close", @"Button title") action:@selector(close:)];
}

- (void)conversionStarted {
    [progressBar startAnimation:nil];
    [textField setStringValue:[[[self window] title] stringByAppendingEllipsis]];
}

- (void)setButtonTitle:(NSString *)title action:(SEL)action {
    [cancelButton setTitle:title];
    [cancelButton setAction:action];
    SKAutoSizeButtons([NSArray arrayWithObjects:cancelButton, nil], YES);
}

#pragma mark PostScript

- (void)stopModalWithResult:(NSNumber *)result {
    [NSApp stopModalWithCode:[result boolValue] ? SKConversionSucceeded : SKConversionFailed];
}

- (void)convertPostScriptData:(NSData *)psData {
    // pass self as info
    converter = CGPSConverterCreate((void *)self, &SKPSConverterCallbacks, NULL);
    NSAssert(converter != NULL, @"unable to create PS converter");

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        CFMutableDataRef pdfData = CFDataCreateMutable(CFGetAllocator((CFDataRef)psData), 0);
        CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)psData);
        CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData(pdfData);

        Boolean success = CGPSConverterConvert(converter, provider, consumer, NULL);

        if (success)
            outputData = [(NSData *)pdfData copy];

        CGDataProviderRelease(provider);
        CGDataConsumerRelease(consumer);
        CFRelease(pdfData);

        // we don't use GCD for the callback, because on Mountain Lion the messages is never received, even though that works on Snow Leopard
        [self performSelectorOnMainThread:@selector(stopModalWithResult:) withObject:[NSNumber numberWithBool:success] waitUntilDone:NO];
    });

}

- (NSData *)newPDFDataWithPostScriptData:(NSData *)psData error:(NSError **)outError {
    NSAssert(NULL == converter, @"attempted to reenter SKConversionProgressController, but this is not supported");

    fileType = SKPostScriptDocumentType;
    cancelled = NO;

    NSModalSession session = [NSApp beginModalSessionForWindow:[self window]];
    NSInteger rv = NSRunContinuesResponse;

    [self convertPostScriptData:psData];

    while (rv == NSRunContinuesResponse)
        rv = [NSApp runModalSession:session];
    [NSApp endModalSession:session];

    if (rv != SKConversionSucceeded && outError) {
        if (cancelled)
            *outError = [NSError userCancelledErrorWithUnderlyingError:nil];
        else
            *outError = [NSError readFileErrorWithLocalizedDescription:NSLocalizedString(@"Unable to load file", @"Error description")];
    }

    [self close];

    return [outputData retain];
}

#pragma mark DVI and XDV

+ (NSString *)newToolPath:(NSString *)commandPath supportedTools:(NSArray *)supportedTools {
    NSString *commandName = [commandPath lastPathComponent];
    NSArray *paths = [NSArray arrayWithObjects:@"/Library/TeX/texbin", @"/usr/texbin", @"/sw/bin", @"/opt/local/bin", @"/usr/local/bin", nil];
    NSInteger i = 0, iMax = [paths count];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSEnumerator *toolEnum = [supportedTools objectEnumerator];

    NSAssert1(commandName == nil || [supportedTools containsObject:commandName], @"converter %@ is not supported", commandName);
    if (commandName == nil || [supportedTools containsObject:commandName] == NO)
        commandName = [toolEnum nextObject];
    do {
        i = 0;
        while ([fm isExecutableFileAtPath:commandPath] == NO) {
            if (i >= iMax) {
                commandPath = nil;
                break;
            }
            commandPath = [[paths objectAtIndex:i++] stringByAppendingPathComponent:commandName];
        }
    } while (commandPath == nil && (commandName = [toolEnum nextObject]));

    return [commandPath retain];
}

+ (NSString *)dviToolPath {
    static NSString *dviToolPath = nil;
    if (dviToolPath == nil) {
        NSString *commandPath = [[NSUserDefaults standardUserDefaults] stringForKey:SKDviConversionCommandKey];
        NSArray *supportedTools = [NSArray arrayWithObjects:@"dvipdfmx", @"dvipdfm", @"dvipdf", @"dvips", nil];
        dviToolPath = [self newToolPath:commandPath supportedTools:supportedTools];
    }
    return dviToolPath;
}

+ (NSString *)xdvToolPath {
    static NSString *xdvToolPath = nil;
    if (xdvToolPath == nil) {
        NSString *commandPath = [[NSUserDefaults standardUserDefaults] stringForKey:SKXdvConversionCommandKey];
        NSArray *supportedTools = [NSArray arrayWithObjects:@"xdvipdfmx", @"xdv2pdf", nil];
        xdvToolPath = [self newToolPath:commandPath supportedTools:supportedTools];
    }
    return xdvToolPath;
}

- (void)taskFinished:(NSNotification *)notification {
    NSData *outData = nil;
    BOOL success = [[notification object] terminationStatus] == 0 &&
                   [outputFileURL checkResourceIsReachableAndReturnError:NULL] &&
                   cancelled == NO;

    SKDESTROY(task);

    if (success)
        outData = [NSData dataWithContentsOfURL:outputFileURL];

    if (success && [[outputFileURL pathExtension] isCaseInsensitiveEqual:@"ps"]) {
        [self convertPostScriptData:outData];
    } else {
        if (success)
            outputData = [outData retain];
        [self conversionCompleted];
        [NSApp stopModalWithCode:success ? SKConversionSucceeded : SKConversionFailed];
    }
}

- (NSData *)newPDFDataWithDVIAtURL:(NSURL *)dviURL toolPath:(NSString *)toolPath fileType:(NSString *)aFileType error:(NSError **)outError {
    NSAssert(NULL == converter, @"attempted to reenter SKConversionProgressController, but this is not supported");

    fileType = aFileType;
    cancelled = NO;

    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *commandName = [toolPath lastPathComponent];
    NSURL *tmpDirURL = [fm URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:dviURL create:YES error:NULL];
    BOOL outputPS = [commandName isEqualToString:@"dvips"];
    NSURL *outFileURL = [tmpDirURL URLByAppendingPathComponent:[dviURL lastPathComponentReplacingPathExtension:outputPS ? @"ps" : @"pdf"]];
    NSArray *arguments = [commandName isEqualToString:@"dvipdf"] ? [NSArray arrayWithObjects:[dviURL path], [outFileURL path], nil] : [NSArray arrayWithObjects:@"-o", [outFileURL path], [dviURL path], nil];

    task = [[NSTask alloc] init];
    [task setLaunchPath:toolPath];
    [task setArguments:arguments];
    [task setCurrentDirectoryPath:[[dviURL URLByDeletingLastPathComponent] path]];
    [task setStandardOutput:[NSFileHandle fileHandleWithNullDevice]];
    [task setStandardError:[NSFileHandle fileHandleWithNullDevice]];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskFinished:) name:NSTaskDidTerminateNotification object:task];

    outputFileURL = [outFileURL retain];

    NSModalSession session = [NSApp beginModalSessionForWindow:[self window]];
    NSInteger rv = NSRunContinuesResponse;

    @try {
        [task launch];
        [self conversionStarted];
    }
    @catch(id exception) {
        SKDESTROY(task);
        [NSApp stopModalWithCode:SKConversionFailed];
    }

    while (rv == NSRunContinuesResponse)
        rv = [NSApp runModalSession:session];
    [NSApp endModalSession:session];

    [fm removeItemAtURL:tmpDirURL error:NULL];

    if (rv != SKConversionSucceeded && outError) {
        if (cancelled)
            *outError = [NSError userCancelledErrorWithUnderlyingError:nil];
        else
            *outError = [NSError readFileErrorWithLocalizedDescription:NSLocalizedString(@"Unable to load file", @"Error description")];
    }

    [self close];

    return [outputData retain];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="io.grpc.transport.ReadableBuffersArrayTest" tests="8" skipped="0" failures="0" errors="0" timestamp="2015-03-23T00:36:34" hostname="ip-172-31-3-252" time="0.041">
  <properties/>
  <testcase name="bufferShouldExposeArray" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.001"/>
  <testcase name="partialReadToArrayShouldSucceed" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.0"/>
  <testcase name="bufferShouldReadAllBytes" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.007"/>
  <testcase name="partialReadToByteBufferShouldSucceed" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.001"/>
  <testcase name="readToByteBufferShouldSucceed" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.004"/>
  <testcase name="readToStreamShouldSucceed" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.003"/>
  <testcase name="readToArrayShouldSucceed" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.004"/>
  <testcase name="partialReadToStreamShouldSucceed" classname="io.grpc.transport.ReadableBuffersArrayTest" time="0.001"/>
  <system-out><![CDATA[]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>

redpajama_set_name: RedPajamaGithub


text:
module TicTacToeRu
  class Game
    attr_accessor :current_player, :other_player

    def initialize(*players)
      @current_player, @other_player = players.shuffle
      @board = TicTacToeRu::Board.new
    end

    def play
      puts 'Игра началась'
      @board.grid_draw
      loop do
        puts "Игрок #{@current_player.name} делает ход:"
        @board.symbol = @current_player.symbol
        begin
          puts 'Выберите ячейку:'
          value = gets.chomp.to_i
          raise 'Вы ввели не числовое значение или такой ячейки не существует, попробуйте еще раз!' if value == 0 || value > 9
          raise "Эта ячейка уже занята, выберете другую!" unless @board.check_free_cell(value)
        rescue Exception => e
          puts e
          puts "\n"
          retry
        end
        @board.next_move(value)
        @board.grid_draw
        break puts 'Ничья! :)' if draw
        break puts "Игрок #{@current_player.name} победил" if winner
        switch_player
      end
    end

    private

    def winner
      @board.win_positions?
    end

    def draw
      @board.no_free_ceels?
    end

    def switch_player
      @current_player, @other_player = @other_player, @current_player
    end
  end
end


text:
Manage Entity Occurrence

Entity id:

Entity kind:

        Delete

            Are you sure to delete the occurrence?
             This will have an impact on the possible relations

                Cancel
                Yes, i'm sure
                Yes, also remove the entity and other occurrences

Move occurrence limits:

    ×

        Cancel
        Save


text:
using Poco::RegularExpression;
using Poco::RegularExpressionException;

RegularExpressionTest::RegularExpressionTest(const std::string& name): CppUnit::TestCase(name)
{
}

RegularExpressionTest::~RegularExpressionTest()
{
}

void RegularExpressionTest::testIndex()
{
	RegularExpression re("[0-9]+");
	RegularExpression::Match match;
	assert (re.match("", 0, match) == 0);
	assert (re.match("123", 3, match) == 0);
}

void RegularExpressionTest::testMatch1()
{
	RegularExpression re("[0-9]+");
	assert (re.match("123"));
	assert (!re.match("123cd"));
	assert (!re.match("abcde"));
	assert (re.match("ab123", 2));
}

void RegularExpressionTest::testMatch2()
{
	RegularExpression re("[0-9]+");
	RegularExpression::Match match;
	assert (re.match("123", 0, match) == 1);
	assert (match.offset == 0);
	assert (match.length == 3);

	assert (re.match("abc123def", 0, match) == 1);
	assert (match.offset == 3);
	assert (match.length == 3);

	assert (re.match("abcdef", 0, match) == 0);
	assert (match.offset == std::string::npos);
	assert (match.length == 0);

	assert (re.match("abc123def", 3, match) == 1);
	assert (match.offset == 3);
	assert (match.length == 3);
}

void RegularExpressionTest::testMatch3()
{
	RegularExpression re("[0-9]+");
	RegularExpression::MatchVec match;
	assert (re.match("123", 0, match) == 1);
	assert (match.size() == 1);
	assert (match[0].offset == 0);
	assert (match[0].length == 3);

	assert (re.match("abc123def", 0, match) == 1);
	assert (match.size() == 1);
	assert (match[0].offset == 3);
	assert (match[0].length == 3);

	assert (re.match("abcdef", 0, match) == 0);
	assert (match.size() == 0);

	assert (re.match("abc123def", 3, match) == 1);
	assert (match.size() == 1);
	assert (match[0].offset == 3);
	assert (match[0].length == 3);
}

void RegularExpressionTest::testMatch4()
{
	RegularExpression re("([0-9]+) ([0-9]+)");
	RegularExpression::MatchVec matches;
	assert (re.match("123 456", 0, matches) == 3);
	assert (matches.size() == 3);
	assert (matches[0].offset == 0);
	assert (matches[0].length == 7);
	assert (matches[1].offset == 0);
	assert (matches[1].length == 3);
	assert (matches[2].offset == 4);
	assert (matches[2].length == 3);

	assert (re.match("abc123 456def", 0, matches) == 3);
	assert (matches.size() == 3);
	assert (matches[0].offset == 3);
	assert (matches[0].length == 7);
	assert (matches[1].offset == 3);
	assert (matches[1].length == 3);
	assert (matches[2].offset == 7);
	assert (matches[2].length == 3);
}

void RegularExpressionTest::testMatch5()
{
	std::string digits = "0123";
	assert (RegularExpression::match(digits, "[0-9]+"));
	std::string alphas = "abcd";
	assert (!RegularExpression::match(alphas, "[0-9]+"));
}

void RegularExpressionTest::testMatch6()
{
	RegularExpression expr("^([a-z]*)?$");
	assert (expr.match("", 0, 0));
	assert (expr.match("abcde", 0, 0));
	assert (!expr.match("123", 0, 0));
}

void RegularExpressionTest::testExtract()
{
	RegularExpression re("[0-9]+");
	std::string str;
	assert (re.extract("123", str) == 1);
	assert (str == "123");

	assert (re.extract("abc123def", 0, str) == 1);
	assert (str == "123");

	assert (re.extract("abcdef", 0, str) == 0);
	assert (str == "");

	assert (re.extract("abc123def", 3, str) == 1);
	assert (str == "123");
}

void RegularExpressionTest::testSplit1()
{
	RegularExpression re("[0-9]+");
	std::vector<std::string> strings;
	assert (re.split("123", 0, strings) == 1);
	assert (strings.size() == 1);
	assert (strings[0] == "123");

	assert (re.split("abc123def", 0, strings) == 1);
	assert (strings.size() == 1);
	assert (strings[0] == "123");

	assert (re.split("abcdef", 0, strings) == 0);
	assert (strings.empty());

	assert (re.split("abc123def", 3, strings) == 1);
	assert (strings.size() == 1);
	assert (strings[0] == "123");
}

void RegularExpressionTest::testSplit2()
{
	RegularExpression re("([0-9]+) ([0-9]+)");
	std::vector<std::string> strings;
	assert (re.split("123 456", 0, strings) == 3);
	assert (strings.size() == 3);
	assert (strings[0] == "123 456");
	assert (strings[1] == "123");
	assert (strings[2] == "456");

	assert (re.split("abc123 456def", 0, strings) == 3);
	assert (strings.size() == 3);
	assert (strings[0] == "123 456");
	assert (strings[1] == "123");
	assert (strings[2] == "456");
}

void RegularExpressionTest::testSubst1()
{
	RegularExpression re("[0-9]+");
	std::string s = "123";
	assert (re.subst(s, "ABC") == 1);
	assert (s == "ABC");
	assert (re.subst(s, "123") == 0);

	s = "123";
	assert (re.subst(s, "AB$0CD") == 1);
	assert (s == "AB123CD");

	s = "123";
	assert (re.subst(s, "AB$1CD") == 1);
	assert (s == "ABCD");

	s = "123";
	assert (re.subst(s, "AB$2CD") == 1);
	assert (s == "ABCD");

	s = "123";
	assert (re.subst(s, "AB$$CD") == 1);
	assert (s == "AB$$CD");

	s = "123";
	assert (re.subst(s, "AB$0CD", RegularExpression::RE_NO_VARS) == 1);
	assert (s == "AB$0CD");
}

void RegularExpressionTest::testSubst2()
{
	RegularExpression re("([0-9]+) ([0-9]+)");
	std::string s = "123 456";
	assert (re.subst(s, "$2-$1") == 1);
	assert (s == "456-123");
}

void RegularExpressionTest::testSubst3()
{
	RegularExpression re("[0-9]+");
	std::string s = "123 456 789";
	assert (re.subst(s, "n", RegularExpression::RE_GLOBAL) == 3);
	assert (s == "n n n");
}

void RegularExpressionTest::testSubst4()
{
	RegularExpression re("[0-9]+");
	std::string s = "ABC 123 456 789 DEF";
	assert (re.subst(s, "n", RegularExpression::RE_GLOBAL) == 3);
	assert (s == "ABC n n n DEF");
}

void RegularExpressionTest::testError()
{
	try
	{
		RegularExpression re("(0-9]");
		failmsg("bad regexp - must throw exception");
	}
	catch (RegularExpressionException&)
	{
	}
}

void RegularExpressionTest::setUp()
{
}

void RegularExpressionTest::tearDown()
{
}

CppUnit::Test* RegularExpressionTest::suite()
{
	CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RegularExpressionTest");

	CppUnit_addTest(pSuite, RegularExpressionTest, testIndex);
	CppUnit_addTest(pSuite, RegularExpressionTest, testMatch1);
	CppUnit_addTest(pSuite, RegularExpressionTest, testMatch2);
	CppUnit_addTest(pSuite, RegularExpressionTest, testMatch3);
	CppUnit_addTest(pSuite, RegularExpressionTest, testMatch4);
	CppUnit_addTest(pSuite, RegularExpressionTest, testMatch5);
	CppUnit_addTest(pSuite, RegularExpressionTest, testMatch6);
	CppUnit_addTest(pSuite, RegularExpressionTest, testExtract);
	CppUnit_addTest(pSuite, RegularExpressionTest, testSplit1);
	CppUnit_addTest(pSuite, RegularExpressionTest, testSplit2);
	CppUnit_addTest(pSuite, RegularExpressionTest, testSubst1);
	CppUnit_addTest(pSuite, RegularExpressionTest, testSubst2);
	CppUnit_addTest(pSuite, RegularExpressionTest, testSubst3);
	CppUnit_addTest(pSuite, RegularExpressionTest, testSubst4);
	CppUnit_addTest(pSuite, RegularExpressionTest, testError);

	return pSuite;
}


text:
#region License

#endregion License

using System.Diagnostics;
using System.Runtime.CompilerServices;
using Debug = UnityEngine.Debug;

namespace eDriven.Core.Util
{
    /// <summary>
    /// A helper for making a log strings
    /// </summary>
    public class LogUtil
    {
        /// <summary>
        /// Prepends a number of characters to the input string
        /// Use space character for tabbing
        /// </summary>
        /// <param name="input"></param>
        /// <param name="count"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string Prepend(string input, int count, string c)
        {
            string output = string.Empty;

            for (int i = 0; i < count; i++)
            {
                output += c;
            }

            return output + input;
        }

        /// <summary>
        /// Gets current method name
        /// </summary>
        /// <returns></returns>
        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void PrintCurrentMethod()
        {
            StackTrace st = new StackTrace();
            StackFrame sf = st.GetFrame(1);

            Debug.Log(string.Format("{0}->{1}", sf.GetMethod().DeclaringType, sf.GetMethod().Name));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="Pitfalls of sharing a connection among threads" />
<meta name="abstract" content="Here is a review of the potential pitfalls of sharing a single Connection among multiple threads." />
<meta name="description" content="Here is a review of the potential pitfalls of sharing a single Connection among multiple threads." />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts65864.html" />
<meta scheme="URI" name="DC.Relation" content="rdevconcepts600.html" />
<meta scheme="URI" name="DC.Relation" content="cdevconcepts23499.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="cdevconcepts89498" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Pitfalls of sharing a connection among threads</title>

Pitfalls of sharing a connection among threads

Here is a review of the potential pitfalls of sharing a single Connection among
multiple threads.

Committing or rolling back a transaction closes all open ResultSet objects
and currently executing Statements, unless you are using held cursors.
If
one thread commits, it closes the Statements and ResultSets of
all other threads using the same connection.

Executing a Statement automatically closes any existing open ResultSet generated
by an earlier execution of that Statement.
If threads share Statements,
one thread could close another's ResultSet.

In many cases, it is easier to assign each thread to a distinct Connection.
If thread A does database work that is not transactionally related
to thread B, assign them to different Connections. For example,
if thread A is associated with a user input window that allows users
to delete hotels and thread B is associated with a user window that
allows users to view city information, assign those threads to different Connections.
That way, when thread A commits, it does not affect any ResultSets or Statements of
thread B.

Another strategy is to have one thread do queries and another thread do
updates. Queries hold shared locks until the transaction commits in SERIALIZABLE
isolation mode; use READ_COMMITTED instead.

Yet another strategy is to have only one thread do database access. Have
other threads get information from the database access thread.

Multiple threads are permitted to share a Connection, Statement,
or ResultSet. However, the application programmer must ensure that
one thread does not affect the behavior of the others.

Recommended Practices

Here are some tips for avoiding
unexpected behavior:

Avoid sharing Statements (and their <samp class="codeph">ResultSets</samp>)
among threads.

Each time a thread executes a Statement, it should process the
results before relinquishing the <samp class="codeph">Connection</samp>.

Each time a thread accesses the Connection, it should consistently
commit or not, depending on application protocol.

Have one thread be the "managing" database Connection thread that
should handle the higher-level tasks, such as establishing the <samp class="codeph">Connection</samp>,
committing, rolling back, changing <samp class="codeph">Connection</samp> properties
such as auto-commit, closing the <samp class="codeph">Connection</samp>, shutting
down the database (in an embedded environment), and so on.

Close ResultSets and <samp class="codeph">Statements</samp> that are
no longer needed in order to release resources.

Parent topic: Working with multiple threads sharing a single connection

Related concepts

Multi-thread programming tips

Related reference

Example of threads sharing a statement


text:
package com.google.common.collect;

import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Nullable;

/**
 * An ordering that treats all references as equals, even nulls.
 *
 * @author Emily Soldal
 */
@GwtCompatible(serializable = true)
final class AllEqualOrdering extends Ordering<Object> implements Serializable {
  static final AllEqualOrdering INSTANCE = new AllEqualOrdering();

  @Override
  public int compare(@Nullable Object left, @Nullable Object right) {
    return 0;
  }

  @Override
  public <E> List<E> sortedCopy(Iterable<E> iterable) {
    return Lists.newArrayList(iterable);
  }

  @Override
  public <E> ImmutableList<E> immutableSortedCopy(Iterable<E> iterable) {
    return ImmutableList.copyOf(iterable);
  }

  @SuppressWarnings("unchecked")
  @Override
  public <S> Ordering<S> reverse() {
    return (Ordering<S>) this;
  }

  private Object readResolve() {
    return INSTANCE;
  }

  @Override
  public String toString() {
    return "Ordering.allEqual()";
  }

  private static final long serialVersionUID = 0;
}


text:
'use strict';

define(function (require) {
    require('angular').module('myApp.filters', []).
        filter('interpolate', require('filter/version_filter'));
        // Add additional filters
        // .filter('filter2', ...
});


text:
@import "../palette.css";

:export { searchBarColor: var(--primaryLinkColor); }

.searchResult {
  margin-top: 20px;
}

.loadingWrapper {
  margin-top: 40px;
}


text:
<?php

class SeatPermissionsSeeder extends Seeder
{

    public function run()
    {
        // Temporarily disable mass assignment restrictions
        Eloquent::unguard();

        DB::table('seat_permissions')->truncate();

        SeatPermissions::create(array('permission' => 'pos_manager'));
        SeatPermissions::create(array('permission' => 'wallet_manager'));
        SeatPermissions::create(array('permission' => 'recruiter'));
        SeatPermissions::create(array('permission' => 'asset_manager'));
        SeatPermissions::create(array('permission' => 'contract_manger'));
        SeatPermissions::create(array('permission' => 'market_manager'));
        SeatPermissions::create(array('permission' => 'key_manager'));
        SeatPermissions::create(array('permission' => 'queue_manager'));
    }
}


text:
#ifndef CUSTOMOPERATIONTYPE_H
#define CUSTOMOPERATIONTYPE_H

#include <mpi.h>
#include "DataTypeDefine.h"
#include <complex>

namespace _MYNAMESPACE_
{
    namespace MPI
    {
        typedef enum _MPIOPTYPE_EXTENSION_
        {
            COMPLEX_FLOAT_SUM = MPIOPTYPESIZE + 1,
            COMPLEX_DOUBLE_SUM
        } MPIOPTYPE_EXETENSION ;

        // Custom Operation Type(s)
        extern MPI_Op MPI_COMPLEX_FLOAT_SUM;
        extern MPI_Op MPI_COMPLEX_DOUBLE_SUM;

        _MPI_OP_TYPE_SETTER_( COMPLEX_FLOAT_SUM,  MPI_COMPLEX_FLOAT_SUM )
        _MPI_OP_TYPE_SETTER_( COMPLEX_DOUBLE_SUM, MPI_COMPLEX_DOUBLE_SUM )

        template <>
        inline MPI_Op MPIOpType< std::complex<float>, SUM >()
        {
            return MPIOPERATIONTYPE<COMPLEX_FLOAT_SUM>();
        }

        template <>
        inline MPI_Op MPIOpType< std::complex<double>, SUM >()
        {
            return MPIOPERATIONTYPE<COMPLEX_DOUBLE_SUM>();
        }

        void CustomOperationTypeRegister();
    }
}

#endif // CUSTOMOPERATIONTYPE_H


text:
from ledlib.portal import Resonator, Portal
from ledlib.helpers import debugprint

from ledlib import patterns
from ledlib import colordefs

from ledlib.colordefs import *

import threading
import logging
import time
# python3 calls it Queue
import queue

class LedPortal(Portal):

    valid_positions = [  "N", "NE", "E", "SE", "S", "SW","W", "NW" ]

    def __init__(self, jsonObj, log):
        # superclass
        Portal.__init__(self,id,log)

        log.debug(" LedPortal initializing !!! ")

        # this will init all the Portal's fields
        if jsonObj != None:
            self.setStatusJsonSimple(jsonObj, log)

        verbose=True

        # create the LedResonators, also make the resonators LedResonattors
        self.ledResonators = {}
        for fc in range(4):                             # 4 FAdecandy boards
            for side in range(2):                       # 2 sets of 4 channels each
                reso_number = fc * 2 + side     # 8 resos
                pos = self.valid_positions[reso_number]
                portal_res = self.resonators.get(pos, None)
                v = None
                if portal_res:
                    v = portal_res.getValues()
                self.ledResonators[pos] = LedResonator(pos, self, fc, side, log, v)
                # by making the objects the same, when we update a resonator,
                # we see it in both. Arguably there should be no LedResonators structure.
                self.resonators[pos] = self.ledResonators[pos]

    # actions come here from the led.py rest service
    # the action strings are defined somewhere. In a document. Which I lost.
    def action(self, action, action_parm):
        self.log.warning(" LedPortal receiving action %s : %s", action, action_parm)

        if action == 'portal_neutralized':
            # flash grey a lot, leave it grey
            for pos, reso in self.ledResonators.items():
                self.log.debug(" LED portal sends neutralized command to leds")
                reso.do_action( LedAction( "neutralized" ) )

        elif action == 'portal_captured':
            # flash the new portal flavor, redraw
            for pos, reso in self.ledResonators.items():
                reso.do_action( LedAction( "captured" ) )

        elif action == 'resonator_add':
            # flash the resonator a lot
            reso = self.ledResonators[action_parm]
            reso.do_action( LedAction("add") )

        elif action == 'resonator_upgrade':
            reso = self.ledResonators[action_parm]
            reso.do_action( LedAction("add") )

        elif action == 'resonator_remove':
            # flash the resonator a lot leave it grey
            reso = self.ledResonators[action_parm]
            reso.do_action( LedAction("remove") )

        elif action == 'mod_added':
            self.log.debug(" no led action for adding a mod")

        elif action == 'mod_destroyed':
            self.log.debug(" no led action for removing a mod")

        elif action == 'attack':
            # invert the current portal owner
            act = None
            if self.faction == 0:
                self.log.warning("received attack on unowned portal ignoring")
            elif self.faction == 1:
                act = LedAction("attack", 2)
            elif self.faction == 2:
                act = LedAction("attack", 1)
            if act:
                # route to the particular resonator
                reso = self.ledResonators[action_parm]
                reso.do_action( act )

        elif action == 'recharge':
            if self.faction != 0:
                reso = self.ledResonators[action_parm]
                reso.do_action( LedAction("defend", self.faction) )

        elif action == 'virus_ada':
            self.log.debug(" no action yet for virus ada, add one! )")

        elif action == 'virus_jarvis':
            self.log.debug(" no action yet for virus jarvis, add one! ")

        else:
            self.log.warning(" UNKNOWN ACTION STRING %s ",action )

# Pixelstring
# name
# base
# size
# direction ( for motion? )

class PixelString(object):
    def __init__(self, name, base, size, direction):
        self.name = name
        self.base = base
        self.size = size
        self.direction = direction
        # TODO: validate direction = 1 or -1
        self.pixels = [0] * self.size
        # why didn't I just use reversed() ?
        if direction == 1:
            for i in range (size):
                self.pixels[i] = base + i
        if direction == -1:
            for i in range (size):
                self.pixels[i] = base + size -1 -i

# Input paramters:
#   'fadecandy', which is an integer which is 0, 1, 2, 3
#   side, which is either 0 or 1 ( side of the fade candy )
#
# a base, which was the base of the fadecandy
# self.LOC - a PixelString of Left Outside
# self.CBOT
# self.LIC - left inner
# self.RIC - right inner center?
# self.RB
# self.
# list_of_lists_of_pixel_numbers - all the pixels in the petal

class PixelMap(object):

    def __init__(self, fadecandy, side):
        # TODO: validate side is 0 or 1
        self.base = (512 * fadecandy) + (256 * side)
        channels = [0, 64, 128, 192]        # TODO these should be in math
        # TODO: better way for overrides

        debugprint ((" definining PixelMap: fadecandy ", fadecandy, "side ", side))

        cbase = self.base  + channels[0]
        self.LOC = PixelString ( "LOC", cbase, 43, 1)
        self.__CBOT = PixelString ("CBOT", cbase + 43, 21, -1)

        cbase = self.base + channels[1]
        self.LIC = PixelString ("LIC", cbase, 36, 1)
        self.LB = PixelString ( "LB", cbase+36, 28, -1)

        cbase = self.base + channels[2]
        self.RIC = PixelString ("RIC", cbase, 36, 1)
        self.RB = PixelString ( "RB", cbase+36, 28, -1)

        cbase = self.base + channels[3]
        self.ROC = PixelString ( "ROC", cbase, 43, 1)
        self.__CTOP = PixelString ("CTOP", cbase + 43, 21, -1)

        # center is composed
        self.CENTER = PixelString("CENTER", 0, 42, 1)
        self.CENTER.pixels = self.__CBOT.pixels + self.__CTOP.pixels

        self.list_of_lists_of_pixel_numbers = [ \
            self.LOC.pixels, \
            self.LIC.pixels, \
            self.CENTER.pixels, \
            self.RIC.pixels, \
            self.ROC.pixels, \
            self.LB.pixels, \
            self.RB.pixels \
            ]

        # "lixel" was originally a typo but it's a great unique tag
        debugprint (" Here comes the list of pixel numbers" )
        debugprint ((self.list_of_lists_of_pixel_numbers))
        debugprint (("Center: ", self.CENTER.pixels))
        debugprint (("LOC: ", self.LOC.pixels))
        debugprint (" Wheee!!!")

class LedAction():
    def __init__(self,action,faction=0):
        self.action = action
        self.faction = faction
        pass
    def __str__(self):
        return "LedAction: action: {0} faction {1}".format(self.action,self.faction)

# AKA a petal
# has a queue and a thread that reads the queue

class LedResonatorThread( threading.Thread):
    # todo: set more things
    def __init__(self,  ledResonator):
        threading.Thread.__init__(self)
        self.ledResonator = ledResonator
        self.log = ledResonator.log

    # sets the leds to the init base state for the current colors
    def init_pattern(self):
        reso = self.ledResonator
        self.log.info(" init pattern: pos %s faction %d level %d ",reso.position, reso.portal.faction,reso.level)
        patterns.parallel_blend(reso.pixelmap.list_of_lists_of_pixel_numbers, \
                        colordefs.colortable_faction[reso.portal.faction], \
                        colordefs.colortable_level[reso.level], \
                        4.0, \
                        40, \
                        reso)
        # test with a little chase, don't really want chase now
        # self.basic_chase_pattern("ww--ww--ww")
        #patterns.chase(reso.pixelmap.list_of_lists_of_pixel_numbers, "ww--ww--ww", -1, reso)

    def flash_pattern(self, faction, secs ):
        reso = self.ledResonator

        if faction == 0:
            rgb = colortable["NEUTRAL"]
        elif faction == 1:
            rgb = colortable["ENL"]
        elif faction == 2:
            rgb = colortable["RES"]

        self.log.info(" FLASH pattern: factionn %d rgb %s", faction, str(rgb) )

        patterns.flash(reso.pixelmap.list_of_lists_of_pixel_numbers, rgb, 10, secs, reso)

    def basic_chase_pattern(self, maskstring):
        reso = self.ledResonator
        self.log.info(" New basic CHASE pattern %s started.", maskstring)
        patterns.chase(reso.pixelmap.list_of_lists_of_pixel_numbers, maskstring, -1)        # infinite chase

    # each resonator has this thread running
    def run(self):
        q = self.ledResonator.queue
        reso = self.ledResonator # this is myself, for a shortcut
        while True:
            action = q.get()

            self.log.debug( "LedResonator %s faction %d received action %s qsize %d  ",reso.position, \
                reso.portal.faction, str(action),q.qsize() )

            if action.action == "init":
                self.init_pattern()

            elif action.action == "neutralized":
                self.log.debug("Resonator receives Neutralize command")
                self.ledResonator.clear()
                self.init_pattern()

            elif action.action == "attack":
                # faction is the number-form here - it means the faction that is attacking
                self.flash_pattern(action.faction, 3.0)
                self.init_pattern()

            elif action.action == "defend":
                # faction is the number form - it is the faction that is defending
                self.flash_pattern(action.faction, 3.0)
                self.init_pattern()

            elif action.action == "remove":
                # now there is nothing
                self.flash_pattern( 0, 6.0 )
                self.init_pattern()

            elif action.action == "add":
                self.flash_pattern( reso.portal.faction, 6.0 )
                self.init_pattern()

            else:
                self.log.warning( "resonator received unknown command %s",action.action)

            q.task_done() # tells other guy you are complete

            # this is the background that happens if nothing else happens
            while q.qsize() == 0:
                self.log.debug( " start background petal %s ",reso.position )
                patterns.chase(reso.pixelmap.list_of_lists_of_pixel_numbers, "ww--ww--ww", -1, reso)

class LedResonator(Resonator):

    # usage:
    # FC is fadecandy 0,1,2,3 ; side is 0,1 (side of the FC)
    # resos.append(Ledresonator(reso_number, reso_name, fc, side, level, health, faction)

    def __init__( self, position, portal, fc, side, log, values ):

        # superclass init
        Resonator.__init__(self, position, portal, log, values)
        # this sets log, portal, values in the superclass

        self.pixelmap = PixelMap (fc, side)

        # create the queue between this and the execution thread
        self.queue = queue.Queue()

        # may have to fix up argument so self gets to run
        r_thread = self.thread = LedResonatorThread(self)
        r_thread.start()

    def do_action(self,action):
        self.queue.put(action)

    # return FALSE if there is nothing else to do
    # return TRUE if you have something better to do
    def hasinterrupt(self):
        if self.queue.empty() == True:
            # log.info(" resonator %s has nothing better to do",self.position)
            return False
        else:
            self.log.debug(" resonator %s : qsize %d has SOMETHING better to do",self.position,self.queue.qsize() )
            return True

    def __str__(self):
        return '"{0}": {{"level": {1}, "health": {2} }}'.format(self.position, self.level, self.health)


text:
# frozen_string_literal: true

require 'simplecov'
require 'rspec'
require 'webmock/rspec'
require 'maropost'
require 'pry'

gem_dir = Gem::Specification.find_by_name('maropost').gem_dir
Dir[File.join(gem_dir, 'spec/support/**/*.rb')].each { |f| require f }

RSpec.configure do |config|
  config.include Helpers::Fixtures
  config.include Helpers::Requests
  config.color = true
  config.tty = true
end

Maropost.configure do |config|
  config.auth_token = 'auth_token'
  config.api_url = 'https://maropost.example.com/api/123/'
end


text:
package dk.brics.tajs.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * Tests that generally take long time.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
        TestOptionToggling.class,
        TestFeatureToggling.class,
        RunBlendedAnalysis.class,
        TestJQueryUse.class,
        TestRevamp2016.class
})
public class RunSlow {

    public static void main(String[] args) {
        org.junit.runner.JUnitCore.main("dk.brics.tajs.test.RunSlow");
    }
}


text:
package jet.bpm.engine.commands;

import java.util.UUID;
import jet.bpm.engine.api.ExecutionException;
import jet.bpm.engine.AbstractEngine;
import jet.bpm.engine.DefaultExecution;

public class ProcessElementCommand implements ExecutionCommand {

    private final String processDefinitionId;
    private final String elementId;
    private final UUID groupId;
    private final boolean exclusive;

    public ProcessElementCommand(String processDefinitionId, String elementId) {
        this(processDefinitionId, elementId, null, false);
    }

    public ProcessElementCommand(String processDefinitionId, String elementId, UUID groupId, boolean exclusive) {
        this.processDefinitionId = processDefinitionId;
        this.elementId = elementId;
        this.groupId = groupId;
        this.exclusive = exclusive;
    }

    public String getProcessDefinitionId() {
        return processDefinitionId;
    }

    public String getElementId() {
        return elementId;
    }

    public UUID getGroupId() {
        return groupId;
    }

    /**
     * Indicates the exclusiveness of this flow. Used to mark exclusive branches
     * of parallel flows.
     */
    public boolean isExclusive() {
        return exclusive;
    }

    @Override
    public DefaultExecution exec(AbstractEngine engine, DefaultExecution execution) throws ExecutionException {
        engine.getElementHandler().handle(execution, this);

        // perform notification of element activation
        execution.onActivation(execution, processDefinitionId, elementId);
        engine.fireOnElementActivation(execution, processDefinitionId, elementId);

        return execution;
    }
}


text:
local bin = require "bin"
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
_ENV = stdnse.module("cassandra", stdnse.seeall)

--[[

  Cassandra Thrift protocol implementation.

  For more information about Cassandra, see:

  http://cassandra.apache.org/

]]--

-- Protocol magic strings
CASSANDRAREQ = "\x80\x01\x00\x01"
CASSANDRARESP = "\x80\x01\x00\x02"
CASSLOGINMAGIC = "\x00\x00\x00\x01\x0c\x00\x01\x0d\x00\x01\x0b\x0b\x00\x00\x00\x02"
LOGINSUCC = "\x00\x00\x00\x01\x00"
LOGINFAIL = "\x00\x00\x00\x01\x0b"
LOGINACC = "\x00\x00\x00\x01\x0c"

--Returns string in cassandra format for login
--@param username to put in format
--@param password to put in format
--@return str : string in cassandra format for login
function loginstr (username, password)
  return bin.pack("A>aAaaaaA",
    CASSANDRAREQ,
    "login",
    CASSLOGINMAGIC,
    "username",
    username,
    "password",
    password,
    "\x00\x00" -- add two null on the end
    )
end

--Invokes command over socket and returns the response
--@param socket to connect to
--@param command to invoke
--@param cnt is protocol count
--@return status : true if ok; false if bad
--@return result : value if status ok, error msg if bad
function cmdstr (command,cnt)
  return bin.pack("A>aIA",
    CASSANDRAREQ,
    command,
    cnt,
    "\x00" -- add null on the end
    )
end

--Invokes command over socket and returns the response
--@param socket to connect to
--@param command to invoke
--@param cnt is protocol count
--@return status : true if ok; false if bad
--@return result : value if status ok, error msg if bad
function sendcmd (socket, command, cnt)
  local cmdstr = cmdstr (command,cnt)
  local response

  local status, err = socket:send(bin.pack(">I",string.len(cmdstr)))
  if ( not(status) ) then
    return false, "error sending packet length"
  end

  status, err = socket:send(cmdstr)
  if ( not(status) ) then
    return false, "error sending packet payload"
  end

  status, response = socket:receive_bytes(4)
  if ( not(status) ) then
          return false, "error receiving length"
  end
  local  _,size = bin.unpack(">I",response,1)

  if (string.len(response) < size+4 ) then
    local resp2
    status, resp2 = socket:receive_bytes(size+4 - string.len(response))
    if ( not(status) ) then
            return false, "error receiving payload"
    end
    response = response .. resp2
  end

  -- magic response starts at 5th byte for 4 bytes, 4 byte for length + length of string command
  if (string.sub(response,5,8+4+string.len(command)) ~= bin.pack("A>a", CASSANDRARESP, command)) then
    return false, "protocol response error"
  end

  return true, response
end

--Return Cluster Name
--@param socket to connect to
--@param cnt is protocol count
--@return status : true if ok; false if bad
--@return result : value if status ok, error msg if bad
function describe_cluster_name (socket,cnt)
  local cname = "describe_cluster_name"
  local status,resp = sendcmd(socket,cname,cnt)

  if (not(status)) then
    stdnse.debug1("sendcmd"..resp)
    return false, "error in communication"
  end

  -- grab the size
  -- pktlen(4) + CASSANDRARESP(4) + lencmd(4) + lencmd(v) + params(7) + next byte position
  local position = 12+string.len(cname)+7+1
  local _,size = bin.unpack(">I",resp,position)

  -- read the string after the size
  local value = string.sub(resp,position+4,position+4+size-1)
  return true, value
end

--Return API version
--@param socket to connect to
--@param cnt is protocol count
--@return status : true if ok; false if bad
--@return result : value if status ok, error msg if bad
function describe_version (socket,cnt)
  local cname = "describe_version"
  local status,resp = sendcmd(socket,cname,cnt)

  if (not(status)) then
    stdnse.debug1("sendcmd"..resp)
    return false, "error in communication"
  end

  -- grab the size
  -- pktlen(4) + CASSANDRARESP(4) + lencmd(4) + lencmd(v) + params(7) + next byte position
  local position = 12+string.len(cname)+7+1
  local _,size = bin.unpack(">I",resp,position)

  -- read the string after the size
  local value = string.sub(resp,position+4,position+4+size-1)
  return true, value
end

--Login to Cassandra
--@param socket to connect to
--@param username to connect to
--@param password to connect to
--@return status : true if ok; false if bad
--@return result : table of status ok, error msg if bad
--@return if status ok : remaining data read from socket but not used
function login (socket,username,password)
  local loginstr = loginstr (username, password)
  local combo = username..":"..password

  local status, err = socket:send(bin.pack(">I",string.len(loginstr)))
  if ( not(status) ) then
          stdnse.debug3("cannot send len "..combo)
          return false, "Failed to connect to server"
  end

  status, err = socket:send(loginstr)
  if ( not(status) ) then
          stdnse.debug3("Sent packet for "..combo)
          return false, err
  end

  local response
  status, response = socket:receive_bytes(22)
  if ( not(status) ) then
          stdnse.debug3("Receive packet for "..combo)
          return false, err
  end
  local _, size = bin.unpack(">I", response, 1)

  local loginresp = string.sub(response,5,17)
  if (loginresp ~= bin.pack("A>a", CASSANDRARESP, "login")) then
    return false, "protocol error"
  end

  local magic = string.sub(response,18,22)
  stdnse.debug3("packet for "..combo)
  stdnse.debug3("packet hex: %s", stdnse.tohex(response) )
  stdnse.debug3("size packet hex: %s", stdnse.tohex(size) )
  stdnse.debug3("magic packet hex: %s", stdnse.tohex(magic) )

  if (magic == LOGINSUCC) then
    return true
  else
    return false, "Login failed."
  end
end

return _ENV;


text: installBiocDataPackage.sh "bioimagedbs-1.6.0"


text:
import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';

import { SharedService } from '../../../../services/shared.service';
import { ExchangeRateService } from '../../exchangeRate.service';
import 'rxjs/add/operator/take';
import { CurrencyService } from '../../../currency/currency.service';

@Component({
    selector: 'exchange-rate-form',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./exchangeRateForm.scss'],
    templateUrl: './exchangeRateForm.html',
})
export class ExchangeRateForm {
    exchangeRateDate: Date;
    JSON: any = JSON;

    public formGroup: FormGroup;
    exchangeRate: any = {};
    subscription: Subscription;
    exchangeRateType: any;
    currency: any = { id: '', code: '', name: '' }
    currencyList = [];

    constructor(protected service: ExchangeRateService,
        private route: ActivatedRoute,
        private router: Router,
        fb: FormBuilder,
        private sharedService: SharedService,
        private currencyService: CurrencyService) {
        this.formGroup = fb.group({
            id: '',
            exchangeRateDate: [this.exchangeRateDate, Validators.required],
            exchangeRate: ['', Validators.required],
            currency: [this.currency, Validators.required]
        });
    }

    getCurrencyList(): void {
        this.currencyService.getCombo().subscribe(currencyList => this.currencyList = currencyList);
    }

    ngOnInit(): void {
        this.getCurrencyList();
        this.route.params.subscribe(
            (params: Params) => {
                let id = params['id'];
                id = id == undefined ? '0' : id;
                if (id != '0') {
                    this.service.get(+id).take(1).subscribe(
                        (data) => {
                            this.loadForm(data);
                        }
                    )
                }
            }
        );
    }

    refresh(): void {
        this.getCurrencyList();
    }

    loadForm(data: any) {
        if (data != null) {
            this.exchangeRate = data;
            data.exchangeRateDate = new Date(data.exchangeRateDate);

        }
        this.formGroup.patchValue(this.exchangeRate, { onlySelf: true });
        this.exchangeRateType = this.exchangeRate.exchangeRateType;
    }

    public onSubmit(values: any, event: Event): void {
        event.preventDefault();
        console.log(values);
        this.service.save(values).subscribe(
            (data) => {
                this.sharedService.addMessage({ severity: 'info', summary: 'Success', detail: 'Operation Success' });
                this.resetForm();
                this.router.navigate(['/pages/exchangeRate/form/']);
            }
        );
    }

    public resetForm() {
        this.formGroup.reset();
    }
    /*================== CurrencyFilter ===================*/
    filteredCurrencyList: any[];

    filterCurrencyList(event) {
        let query = event.query.toLowerCase();
        this.filteredCurrencyList = [];
        for (let i = 0; i < this.currencyList.length; i++) {
            let currency = this.currencyList[i];
            if (currency.display.toLowerCase().indexOf(query) >= 0) {
                this.filteredCurrencyList.push(currency);

            }
        }
    }

    onCurrencySelect(event: any) {

    }
    /*================== Customer Type Filter ===================*/
}


text: export default "non-external";


text:
package com.palm.yh.common.util;

import org.springframework.stereotype.Component;

import io.vertx.core.json.JsonObject;

/**
 * 构造返回结果辅助类
 *
 * @author hxl
 */
@Component
public class ResponseMessageProduceUtil {
	/**
	 * 构造成功的返回结果
	 *
	 * @param data 返回的数据
	 * @return
	 * Object
	 */
	public Object getSuccessMessage(String data){
		return getSuccessMessage(null, data);
	}

	/**
	 * 构造成功的返回结果
	 *
	 * @param message 提醒信息
	 * @param data 返回的数据
	 * @return
	 * Object
	 */
	public Object getSuccessMessage(String message,String data){
		return getMessage("0", message, data);
	}

	public Object getMessage(String code,String message,String data){
		JsonObject jsonObject=new JsonObject();
		jsonObject.put("code", code);
		jsonObject.put("msg", message);
		jsonObject.put("data", data);
		return jsonObject;
	}

	/**
	 * 构造失败的返回结果
	 *
	 * @param message 错误的信息
	 * @return
	 * Object
	 */
	public Object getErrorMessage(String message){
		return getMessage("-1", message, null);
	}

}


text:
define(function(require, exports, module) {

    var marionette = require('marionette');
    var template = require('hbs!../templates/recipe-view');
    var Recipe = require('app/models/recipe').Recipe;

    var RecipeView = marionette.ItemView.extend({
        model: Recipe,
        template: template,

        ui: {

        },

        events: {
        },

        initialize: function(options) {
            this.model = options.model;
            this.session = options.session;
        }

    });

    exports.RecipeView = RecipeView;
})


text:
import { Circle } from './src/Circle.js';
import { Parallelogram } from './src/Parallelogram.js';
import { Rectangle } from './src/Rectangle.js';
import { Square } from './src/Square.js';
import { Triangle } from './src/Triangle.js';

var circles = document.getElementsByTagName('circle');
for (var i = 0; i < circles.length; i++) {
    window.onload = Circle.findCircleElement(circles[i]);
}

var parallelograms = document.getElementsByTagName('parallelogram');

for (var i = 0; i < parallelograms.length; i++){
	window.onload = Parallelogram.processSquare(parallelograms[i]);
}

var rectangles = document.getElementsByTagName('rectangle');

for (var i = 0; i < rectangles.length; i++){
	window.onload = Rectangle.processRectangle(rectangles[i]);
}

var squares = document.getElementsByTagName('square');

for (var i = 0; i < squares.length; i++){
	window.onload = Square.processSquare(squares[i]);
}

var triangleUps = document.getElementsByTagName('triangle-up');
for (var i = 0; i < triangleUps.length; i++){
    window.onload = Triangle.processingTriangle(triangleUps[i], 'up');
}

var triangleLefts = document.getElementsByTagName('triangle-left');
for (var i = 0; i < triangleLefts.length; i++){
    window.onload = Triangle.processingTriangle(triangleLefts[i], 'left');
}

var triangleRights = document.getElementsByTagName('triangle-right');
for (var i = 0; i < triangleRights.length; i++){
    window.onload = Triangle.processingTriangle(triangleRights[i], 'right');
}

var triangleDowns = document.getElementsByTagName('triangle-down');
for (var i = 0; i < triangleDowns.length; i++){
    window.onload = Triangle.processingTriangle(triangleDowns[i], 'down');
}

var triangleTopLeft = document.getElementsByTagName('triangle-top-left');
for (var i = 0; i < triangleTopLeft.length; i++){
    window.onload = Triangle.processingTriangle(triangleTopLeft[i], 'top-left');
}
var triangleTopRight = document.getElementsByTagName('triangle-top-right');
for (var i = 0; i < triangleTopRight.length; i++){
    window.onload = Triangle.processingTriangle(triangleTopRight[i], 'top-right');
}

var triangleBottomRight = document.getElementsByTagName('triangle-bottom-right');
for (var i = 0; i < triangleBottomRight.length; i++){
    window.onload = Triangle.processingTriangle(triangleBottomRight[i], 'bottom-right');
}

var triangleBottomLeft = document.getElementsByTagName('triangle-bottom-left');
for (var i = 0; i < triangleBottomLeft.length; i++){
    window.onload = Triangle.processingTriangle(triangleBottomLeft[i], 'bottom-left');
}

var triangles = document.getElementsByTagName('triangle');
for (var i = 0; i < triangles.length; i++){
	window.onload = Triangle.processingTriangle(triangles[i], null);
}


text:
using Microsoft.EntityFrameworkCore;
using Promact.Trappist.DomainModel.DbContext;
using Promact.Trappist.DomainModel.Models.TestConduct;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Promact.Trappist.DomainModel.Enum;
using Promact.Trappist.DomainModel.Models.Test;
using Promact.Trappist.DomainModel.ApplicationClasses.Reports;
using Promact.Trappist.DomainModel.Models.Question;
using System;
using Promact.Trappist.DomainModel.Models.Report;
using Promact.Trappist.Repository.TestConduct;
using Promact.Trappist.DomainModel.ApplicationClasses.Test;

namespace Promact.Trappist.Repository.Reports
{
    public class ReportRepository : IReportRepository
    {
        #region Private Members
        private readonly TrappistDbContext _dbContext;
        private readonly ITestConductRepository _testConductRepository;
        #endregion

        #region Constructor
        public ReportRepository(TrappistDbContext dbContext, ITestConductRepository testConductRepository)
        {
            _dbContext = dbContext;
            _testConductRepository = testConductRepository;
        }
        #endregion

        #region IReportRepository Methods
        #region Public Methods
        public async Task<TestAC> GetTestNameAsync(int id)
        {
            var result = await _dbContext.Test.AsNoTracking().Where(x => x.Id == id)
                .Select(selectOnly => new { selectOnly.TestName, selectOnly.Link, selectOnly.CorrectMarks, selectOnly.Duration, selectOnly.EndDate }).ToListAsync();
            var testACObject = new TestAC()
            {
                TestName = result.First().TestName,
                Link = result.First().Link,
                CorrectMarks = result.First().CorrectMarks,
                Duration = result.First().Duration,
                EndDate = result.First().EndDate
            };
            return testACObject;
        }

        public async Task<IEnumerable<TestAttendees>> GetAllTestAttendeesAsync(int id)
        {
            return await _dbContext.TestAttendees.AsNoTracking().Where(t => t.TestId == id).Include(x => x.Report).ToListAsync();
        }

        public async Task SetStarredCandidateAsync(int id)
        {
            var studentToBeStarred = await _dbContext.TestAttendees.FindAsync(id);
            studentToBeStarred.StarredCandidate = !studentToBeStarred.StarredCandidate;
            await _dbContext.SaveChangesAsync();
        }

        public async Task SetAllCandidateStarredAsync(bool status, int selectedTestStatus, string searchString)
        {
            List<TestAttendees> attendeeList;

            if (searchString == null)
                searchString = "";
            else
                searchString = searchString.ToLowerInvariant();

            if ((TestStatus)selectedTestStatus == TestStatus.AllCandidates)
                attendeeList = await _dbContext.TestAttendees.Where(x => x.FirstName.ToLower().Contains(searchString) || x.LastName.ToLower().Contains(searchString) || x.Email.Contains(searchString)).ToListAsync();

            else
                attendeeList = await _dbContext.TestAttendees.Include(x => x.Report).Where(x => x.Report.TestStatus == (TestStatus)selectedTestStatus
                && (x.FirstName.ToLower().Contains(searchString) || x.LastName.ToLower().Contains(searchString) || x.Email.Contains(searchString))).ToListAsync();

            attendeeList.ForEach(x => x.StarredCandidate = status);

            await _dbContext.SaveChangesAsync();
        }

        public async Task<bool> IsCandidateExistAsync(int attendeeId)
        {
            return await _dbContext.TestAttendees.AnyAsync(s => s.Id == attendeeId);
        }

        public async Task<TestAttendees> GetTestAttendeeDetailsByIdAsync(int testAttendeeId)
        {
            var testAttendee = await _dbContext.TestAttendees.Include(x => x.Test).Include(x => x.TestConduct).Include(x => x.TestLogs).Include(x => x.Report).FirstOrDefaultAsync(x => x.Id == testAttendeeId);
            return testAttendee;
        }

        public async Task<List<TestQuestion>> GetTestQuestions(int testId)
        {
            var listOfQuestionsInTest = await _dbContext.TestQuestion.Include(x => x.Question).Where(x => x.TestId == testId).ToListAsync();
            var testQuestionIds = listOfQuestionsInTest.Where(x => x.Question.QuestionType != QuestionType.Programming && x.TestId == testId).Select(x => x.Id).ToList();
            var questionObjectList = await _dbContext.TestQuestion.Include(x => x.Question).Include(x => x.Question.SingleMultipleAnswerQuestion).ThenInclude(x => x.SingleMultipleAnswerQuestionOption).Where(x => testQuestionIds.Contains(x.Id) && x.TestId == testId).ToListAsync();

            var testQuestionList = new List<TestQuestion>();

            foreach (var question in listOfQuestionsInTest)
            {
                if (question.Question.QuestionType == QuestionType.Programming)
                    testQuestionList.Add(question);
                else
                {
                    var questionObject = questionObjectList.Where(x => x.QuestionId == question.QuestionId).FirstOrDefault();
                    testQuestionList.Add(questionObject);
                }
            }
            return testQuestionList;
        }

        public async Task<List<TestAnswers>> GetTestAttendeeAnswers(int testAttendeeId)
        {
            var testAttendeeFullAnswerList = await _dbContext.TestAnswers.Where(x => x.TestConduct.TestAttendeeId == testAttendeeId).ToListAsync();
            return testAttendeeFullAnswerList;
        }

        public async Task<double> CalculatePercentileAsync(int testAttendeeId, int testId)
        {
            int sameMarks = 0;
            int count = 0;
            double studentPercentile;

            var attendee = await _dbContext.Report.Where(x => x.TestAttendeeId == testAttendeeId).FirstOrDefaultAsync();
            var marksList = await _dbContext.Report.Where(x => x.TestAttendee.TestId == testId).OrderBy(x => x.TotalMarksScored).ToListAsync();
            double noOfScores = marksList.Count();

            foreach (var marks in marksList)
            {
                if (attendee.TotalMarksScored == marks.TotalMarksScored)
                    sameMarks = sameMarks + 1;
                else if (marks.TotalMarksScored < attendee.TotalMarksScored)
                    count = count + 1;
            }

            var rank = count + (0.5 * sameMarks);
            double percentile = rank / noOfScores;
            studentPercentile = percentile * 100;
            return studentPercentile;
        }

        public async Task<List<ReportQuestionsCountAC>> GetAllAttendeeMarksDetailsAsync(int testId)
        {
            var testAttendeeAnswerList = new List<TestAnswers>();
            var testQuestionList = new List<TestQuestion>();
            var allAttendeeMarksDetailsList = new List<ReportQuestionsCountAC>();
            var easyQuestionAttempted = 0; var hardQuestionAttempted = 0; var mediumQuestionAttempted = 0;
            var countOptions = 0; var totalQuestionAttempted = 0; var sameMarks = 0;
            var count = 0;

            //all testattendees Of a test
            var allTestAttendeeList = await _dbContext.TestAttendees.Where(x => x.TestId == testId).Include(x => x.Report).Select(x => x.Id).ToListAsync();
            //all testAttendees marks list
            var marksList = await _dbContext.Report.Where(x => x.TestAttendee.TestId == testId).OrderBy(x => x.TotalMarksScored).Select(s => new { s.TestAttendeeId, s.TotalMarksScored }).ToListAsync();
            //no test questions of a test
            var totalNoOfTestQuestions = await _dbContext.TestQuestion.CountAsync(x => x.TestId == testId);
            //all questions attempted by all attendees
            var questionsAttemptedByAllAttendeeList = _dbContext.TestConduct.Where(x => x.TestAttendees.TestId == testId && x.QuestionStatus == QuestionStatus.answered || x.QuestionStatus == QuestionStatus.review)
                                                           .Select(selectOnly => new { selectOnly.Id, selectOnly.TestAttendeeId, selectOnly.QuestionId, selectOnly.Question.QuestionType, selectOnly.Question.DifficultyLevel });
            //all answers attempted by all attendees
            var answeredByAllAttendeeList = await _dbContext.TestAnswers.Where(x => x.TestConduct.TestAttendees.TestId == testId).Select(s => new { s.TestConductId, s.AnsweredOption }).ToListAsync();

            //all testcode solutions of a test
            var testCodeSolutionsList = _dbContext.TestCodeSolution.Where(x => x.TestAttendee.TestId == testId).Select(selectOnly => new { selectOnly.QuestionId, selectOnly.TestAttendeeId, selectOnly.Score });

            foreach (var testAttendee in allTestAttendeeList)
            {
                double studentPercentile = 0.0;
                var attemptedQuestions = questionsAttemptedByAllAttendeeList.Where(x => x.TestAttendeeId == testAttendee).ToList();
                attemptedQuestions.ForEach(x =>
                {
                    var checkAttempts = 0;
                    var difficultyLevel = x.DifficultyLevel;
                    if (x.QuestionType != QuestionType.Programming)
                    {
                        var givenOptionsByAttendee = answeredByAllAttendeeList.Where(y => y.TestConductId == x.Id).Select(y => y.AnsweredOption).FirstOrDefault();
                        if (givenOptionsByAttendee != null)
                        {
                            totalQuestionAttempted += 1;
                            checkAttempts = 1;
                        }
                    }
                    else
                    {
                        var givenSolutionByAttendee = testCodeSolutionsList.Where(y => y.QuestionId == x.QuestionId && y.TestAttendeeId == testAttendee).ToList();
                        if (givenSolutionByAttendee.Count() > 0)
                        {
                            totalQuestionAttempted += 1;
                            checkAttempts = 1;
                        }
                    }
                    if (checkAttempts == 1)
                    {
                        if (difficultyLevel == DifficultyLevel.Easy)
                            easyQuestionAttempted += 1;
                        else if (difficultyLevel == DifficultyLevel.Medium)
                            mediumQuestionAttempted += 1;
                        else
                            hardQuestionAttempted += 1;
                    }
                });
                //calculate percentile
                double noOfScores = marksList.Count();
                var attendee = marksList.FirstOrDefault(z => z.TestAttendeeId == testAttendee);
                foreach (var marks in marksList)
                {
                    if (attendee != null && attendee.TotalMarksScored == marks.TotalMarksScored)
                        sameMarks = sameMarks + 1;
                    else if (attendee != null && marks.TotalMarksScored < attendee.TotalMarksScored)
                        count = count + 1;
                }
                var rank = count + (0.5 * sameMarks);
                double percentile = rank / noOfScores;
                studentPercentile = percentile * 100;

                var reportQuestions = new ReportQuestionsCountAC()
                {
                    TestAttendeeId = testAttendee,
                    EasyQuestionAttempted = easyQuestionAttempted,
                    MediumQuestionAttempted = mediumQuestionAttempted,
                    HardQuestionAttempted = hardQuestionAttempted,
                    NoOfQuestionAttempted = totalQuestionAttempted,
                    Percentile = Math.Round(studentPercentile, 2),
                    totalTestQuestions = totalNoOfTestQuestions
                };
                allAttendeeMarksDetailsList.Add(reportQuestions);

                easyQuestionAttempted = mediumQuestionAttempted = hardQuestionAttempted = countOptions = totalQuestionAttempted = 0;
                studentPercentile = 0.0;
            };
            return allAttendeeMarksDetailsList;
        }

        public async Task<List<CodeSnippetTestCasesCalculationAC>> GetCodeSnippetDetailsAsync(int attendeeId, int questionId)
        {
            if (!await _dbContext.TestCodeSolution.Where(x => x.TestAttendeeId == attendeeId).AnyAsync(x => x.QuestionId == questionId))
                return null;
            var testCodeSolutionObject = await _dbContext.TestCodeSolution.Include(x => x.TestCaseResultCollection).OrderByDescending(x => x.CreatedDateTime).FirstOrDefaultAsync(x => x.TestAttendeeId == attendeeId && x.QuestionId == questionId);
            var codeSnippetTestCaseList = new List<CodeSnippetTestCasesCalculationAC>();
            var testCaseObjectList = testCodeSolutionObject.TestCaseResultCollection;

            bool testCasePassed;

            var codeSnippetQuestionTestCasesList = await _dbContext.CodeSnippetQuestionTestCases.Where(x => x.CodeSnippetQuestionId == questionId).ToListAsync();
            var i = 0;
            foreach (var testCase in testCaseObjectList)
            {
                var codeSnippetTestCase = codeSnippetQuestionTestCasesList.Where(x => x.Id == testCase.CodeSnippetQuestionTestCasesId).Single();
                testCasePassed = testCase.Output == codeSnippetTestCase.TestCaseOutput;
                var testCaseDetailsList = new CodeSnippetTestCasesCalculationAC()
                {
                    TestCaseName = codeSnippetTestCase.TestCaseTitle,
                    TestCaseInput = codeSnippetTestCase.TestCaseInput,
                    TestCaseMarks = codeSnippetTestCase.TestCaseMarks,
                    TestCaseType = codeSnippetTestCase.TestCaseType,
                    ExpectedOutput = codeSnippetTestCase.TestCaseOutput,
                    Processing = testCase.Processing,
                    Memory = testCase.Memory,
                    ActualOutput = testCase.Output,
                    IsTestCasePassing = testCasePassed
                };
                i++;
                codeSnippetTestCaseList.Add(testCaseDetailsList);
            }
            return codeSnippetTestCaseList;
        }

        public async Task<decimal> GetTotalMarksOfCodeSnippetQuestionAsync(int attendeeId, int questionId)
        {
            if (!await _dbContext.TestCodeSolution.Where(x => x.TestAttendeeId == attendeeId).AnyAsync(x => x.QuestionId == questionId))
            {
                return -1;
            }
            var maximumScoreObtainedByAttendeeInCodeSnippetQuestion = await _dbContext.TestCodeSolution.OrderByDescending(x => x.CreatedDateTime).Where(x => x.TestAttendeeId == attendeeId && x.QuestionId == questionId).Select(x => x.Score).FirstOrDefaultAsync();
            var testObjectCorrectMarks = await _dbContext.TestAttendees.Where(x => x.Id == attendeeId).Include(x => x.Test).Select(x => x.Test.CorrectMarks).FirstOrDefaultAsync();
            var totalMarksObtainedInCodeSnippetQuestion = (decimal)maximumScoreObtainedByAttendeeInCodeSnippetQuestion * testObjectCorrectMarks;
            totalMarksObtainedInCodeSnippetQuestion = Math.Round(totalMarksObtainedInCodeSnippetQuestion, 2);
            return totalMarksObtainedInCodeSnippetQuestion;
        }

        public async Task<TestCodeSolutionDetailsAC> GetTestCodeSolutionDetailsAsync(int attendeeId, int questionId)
        {
            if (!await _dbContext.TestCodeSolution.Where(x => x.TestAttendeeId == attendeeId).AnyAsync(x => x.QuestionId == questionId))
                return null;
            var testCodeSolutionObject = await _dbContext.TestCodeSolution.Include(x => x.TestCaseResultCollection).OrderByDescending(x => x.CreatedDateTime).FirstOrDefaultAsync(x => x.TestAttendeeId == attendeeId && x.QuestionId == questionId);
            var totalNumberOfSuccessfulAttempts = await _dbContext.TestCodeSolution.CountAsync(x => x.Score == 1 && x.TestAttendeeId == attendeeId && x.QuestionId == questionId);
            var totalNumberOfAttemptsMadeByAttendee = await _dbContext.TestCodeSolution.CountAsync(x => x.TestAttendeeId == attendeeId && x.QuestionId == questionId);

            var testCodeSolutionDetailsObject = new TestCodeSolutionDetailsAC()
            {
                Language = testCodeSolutionObject.Language,
                NumberOfSuccessfulAttempts = totalNumberOfSuccessfulAttempts,
                TotalNumberOfAttempts = totalNumberOfAttemptsMadeByAttendee,
                CodeSolution = testCodeSolutionObject.Solution
            };

            return testCodeSolutionDetailsObject;
        }

        public async Task<TestAttendees> SetTestStatusAsync(TestAttendees attendee, bool isTestEnd)
        {
            attendee.Report = await _dbContext.Report.FirstOrDefaultAsync(x => x.TestAttendeeId == attendee.Id);
            if (attendee.Report != null)
            {
                if (isTestEnd)
                {
                    attendee.Report.IsTestPausedUnWillingly = false;
                    if (attendee.Report.TestStatus == TestStatus.AllCandidates)
                        attendee.Report.TestStatus = TestStatus.CompletedTest;
                }
                else
                {
                    attendee.Report.IsTestPausedUnWillingly = false;
                    attendee.Report.IsAllowResume = true;
                    attendee.Report.TestStatus = TestStatus.AllCandidates;
                }
                _dbContext.Report.Update(attendee.Report);
                await _dbContext.SaveChangesAsync();
                return attendee;
            }
            else
                return null;
        }

        public async Task SetWindowCloseAsync(int attendeeId, bool isTestResume)
        {
            var reportObject = await _dbContext.Report.FirstOrDefaultAsync(x => x.TestAttendeeId == attendeeId);
            if (reportObject != null)
            {
                if (isTestResume)
                    reportObject.IsAllowResume = false;
                else
                    reportObject.IsTestPausedUnWillingly = true;
                _dbContext.Report.Update(reportObject);
                await _dbContext.SaveChangesAsync();
            }
        }

        public async Task<Report> GetWindowCloseAsync(int attendeeId)
        {
            var reportObject = await _dbContext.Report.FirstOrDefaultAsync(x => x.TestAttendeeId == attendeeId);
            return reportObject;
        }

        public async Task<int> GetAttemptedQuestionsByAttendeeAsync(int attendeeId)
        {
            var numberOfAnsweredButReviewedQuestions = 0;
            var count = 0;
            var listOfQuestionsAttemptedByTestAttendee = await _dbContext.TestConduct.Include(x => x.TestAnswers).Where(x => x.TestAttendeeId == attendeeId && x.QuestionStatus == QuestionStatus.answered).ToListAsync();
            var listOfQuestionsAttendedByTestAttendee = await _dbContext.TestConduct.Include(x => x.TestAnswers).Where(x => x.TestAttendeeId == attendeeId && x.QuestionStatus == QuestionStatus.review).ToListAsync();

            foreach (var conduct in listOfQuestionsAttendedByTestAttendee)
            {
                count = 0;
                if (conduct.QuestionStatus == QuestionStatus.unanswered || conduct.QuestionStatus == QuestionStatus.selected)
                {
                    continue;
                }

                if (conduct.QuestionStatus == QuestionStatus.review)
                {
                    foreach (var answer in conduct.TestAnswers)
                    {
                        if (conduct.Id == answer.TestConductId)
                            count = count + 1;
                        if ((answer.AnsweredOption != null && count == 1 || conduct.IsAnswered))
                        {
                            numberOfAnsweredButReviewedQuestions = numberOfAnsweredButReviewedQuestions + 1;
                        }
                    }
                }
            }

            var numberOfQuestionsAttempted = listOfQuestionsAttemptedByTestAttendee.Count() + numberOfAnsweredButReviewedQuestions;
            return numberOfQuestionsAttempted;
        }

        public async Task<List<TestAttendees>> GenerateReportForUnfinishedTestAsync(List<int> attendeeIdList)
        {
            foreach (var id in attendeeIdList)
            {
                await _testConductRepository.SetAttendeeTestStatusAsync(id, TestStatus.UnfinishedTest);
            }

            return await _dbContext.TestAttendees.Where(x => attendeeIdList.Any(id => id == x.Id)).Include(x => x.Report).ToListAsync();
        }

        public async Task<List<int>> GetAttendeeIdListAsync(int testId)
        {
            var testAttendeeIdList = await _dbContext.TestAttendees.Where(x => x.TestId == testId && x.Report != null).Select(x => x.Id).ToListAsync();
            return testAttendeeIdList;
        }
        #endregion
        #endregion
    }
}


text:
<?php

defined('_JEXEC') or die('RESTRICTED');
?>

<?php echo WFText::_('WF_INSTALLER_UNINSTALL_DESC'); ?>

        <li class="wf-tooltip active" title="<?php echo JText :: _('WF_INSTALLER_PLUGINS') . '::' . WFText::_('WF_INSTALLER_PLUGINS_DESC'); ?>"><?php echo JText :: _('WF_INSTALLER_PLUGINS'); ?>

        <li class="wf-tooltip" title="<?php echo JText :: _('WF_INSTALLER_EXTENSIONS') . '::' . WFText::_('WF_INSTALLER_EXTENSIONS_DESC'); ?>"><?php echo JText :: _('WF_INSTALLER_EXTENSIONS'); ?>

        <li class="wf-tooltip" title="<?php echo JText :: _('WF_INSTALLER_LANGUAGES') . '::' . WFText::_('WF_INSTALLER_LANGUAGES_DESC'); ?>"><?php echo JText :: _('WF_INSTALLER_LANGUAGES'); ?>

        <li class="wf-tooltip" title="<?php echo JText :: _('WF_INSTALLER_RELATED') . '::' . WFText::_('WF_INSTALLER_RELATED_DESC'); ?>"><?php echo JText :: _('WF_INSTALLER_RELATED'); ?>

            <?php if (count($this->plugins)) : ?>
                <?php echo $this->loadTemplate('plugins'); ?>
            <?php else : ?>
                <?php echo WFText::_('WF_INSTALLER_NO_PLUGINS'); ?>
            <?php endif; ?>

            <?php if (count($this->extensions)) : ?>
                <?php echo $this->loadTemplate('extensions'); ?>
            <?php else : ?>
                <?php echo WFText::_('WF_INSTALLER_EXTENSIONS'); ?>
            <?php endif; ?>

            <?php if (count($this->languages)) : ?>
                <?php echo $this->loadTemplate('languages'); ?>
            <?php else : ?>
                <?php echo WFText::_('WF_INSTALLER_NO_LANGUAGES'); ?>
            <?php endif; ?>

            <?php if (count($this->related)) : ?>
                <?php echo $this->loadTemplate('related'); ?>
            <?php else : ?>
                <?php echo WFText::_('WF_INSTALLER_NO_RELATED'); ?>
            <?php endif; ?>


text:
//
// Copyright (c) Microsoft Corporation.    All rights reserved.
//

namespace Microsoft.Llilum.BoardConfigurations
{
    using Microsoft.Zelig.Runtime;
    using Microsoft.Zelig.Configuration.Environment;

    [DisplayName("STM32F401")]
    public sealed class STM32F401SoC : ProcessorCategory
    {
        [DependsOn(typeof(STM32F401SoC))]
        [DisplayName("Internal 96KB Static RAM")]
        [Defaults("BaseAddress", 0x20000000U)]
        [Defaults("SizeInBytes", 96 * 1024)]
        [Defaults("WordSize", 32)]
        [Defaults("WaitStates", 0)]
        [EnumDefaults("Characteristics", MemoryAttributes.RAM |
                                          MemoryAttributes.RandomAccessMemory |
                                          MemoryAttributes.InternalMemory |
                                          MemoryAttributes.ConfiguredAtEntryPoint)]
        public sealed class InternalRAM96KB : RamMemoryCategory
        {
        }

        [DependsOn(typeof(STM32F401SoC))]
        [DisplayName("Internal 512KB FLASH")]
        [Defaults("BaseAddress", 0x08000000U)]
        [Defaults("SizeInBytes", 512 * 1024)]
        [Defaults("WordSize", 32)]
        [Defaults("WaitStates", 0)]
        [EnumDefaults("Characteristics", MemoryAttributes.FLASH |
                                          MemoryAttributes.RandomAccessMemory |
                                          MemoryAttributes.InternalMemory |
                                          MemoryAttributes.ConfiguredAtEntryPoint)]
        public sealed class InternalFlash512KB : FlashMemoryCategory
        {
        }
    }

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

    [DisplayName("Memory Map for STM32F401")]
    public sealed class STM32F401MemoryMap : MemoryMapCategory
    {

        [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory |
                                               MemoryAttributes.RandomAccessMemory |
                                               MemoryAttributes.ConfiguredAtEntryPoint)]
        [MemorySection(MemoryUsage.Stack |
                        MemoryUsage.Heap |
                        MemoryUsage.DataRW |
                        MemoryUsage.Code)]
        [AllowedOptions(typeof(STM32F401SoC.InternalRAM96KB))]
        [Defaults("BaseAddress", 0x20000000U)]
        public RamMemoryCategory InternalRamChip;

        [MergeEnumDefaults("Characteristics", MemoryAttributes.InternalMemory |
                                               MemoryAttributes.RandomAccessMemory |
                                               MemoryAttributes.ConfiguredAtEntryPoint |
                                               MemoryAttributes.LoadedAtEntrypoint)]
        [MemorySection(MemoryUsage.Bootstrap |
                        MemoryUsage.Code |
                        MemoryUsage.DataRO |
                        MemoryUsage.VectorsTable |
                        MemoryUsage.Relocation)]
        [AllowedOptions(typeof(STM32F401SoC.InternalFlash512KB))]
        [Defaults("BaseAddress", 0x08000000U)]
        public FlashMemoryCategory InternalFlashChip;
    }

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

    [DisplayName("STM32F401 MBED")]
    public sealed class STM32F401 : ProductCategory
    {
        [AllowedOptions(typeof(STM32F401SoC))]
        [Defaults("CoreClockFrequency", 84000000UL)]
        [Defaults("RealTimeClockFrequency", 1000000UL)]
        [Defaults("DefaultThreadPoolThreads", 2)]
        [Defaults("DefaultTimerPoolThreads", 2)]
        public STM32F401SoC Processor;

        //--//

        [AllowedOptions(typeof(STM32F401SoC.InternalRAM96KB))]
        [Defaults("BaseAddress", 0x20000000U)]
        public RamMemoryCategory InternalRam;

        [AllowedOptions(typeof(STM32F401SoC.InternalFlash512KB))]
        [Defaults("BaseAddress", 0x08000000U)]
        public FlashMemoryCategory InternalFlashChip;
    }

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

    [DisplayName("LLVM Compilation for STM32F401")]
    [Defaults("Platform", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7M_VFP))]
    [Defaults("CallingConvention", typeof(Microsoft.Zelig.Configuration.Environment.Abstractions.Architectures.LlvmForArmV7MCallingConvention))]
    [Defaults("Product", typeof(STM32F401))]
    [Defaults("MemoryMap", typeof(STM32F401MemoryMap))]
    public sealed class STM32F401MBEDCompilationSetup : CompilationSetupCategory
    {
    }

}