text:
// In harness baselines, null is different than undefined. See `generateActual` in `harness.ts`.
namespace RWC {
    function runWithIOLog(ioLog: Playback.IoLog, fn: (oldIO: Harness.IO) => void) {
        const oldIO = Harness.IO;

        const wrappedIO = Playback.wrapIO(oldIO);
        wrappedIO.startReplayFromData(ioLog);
        Harness.setHarnessIO(wrappedIO);

        try {
            fn(oldIO);
        }
        finally {
            wrappedIO.endReplay();
            Harness.setHarnessIO(oldIO);
        }
    }

    export function runRWCTest(jsonPath: string) {
        describe("Testing a rwc project: " + jsonPath, () => {
            let inputFiles: Harness.Compiler.TestFile[] = [];
            let otherFiles: Harness.Compiler.TestFile[] = [];
            let tsconfigFiles: Harness.Compiler.TestFile[] = [];
            let compilerResult: compiler.CompilationResult;
            let compilerOptions: ts.CompilerOptions;
            const baselineOpts: Harness.Baseline.BaselineOptions = {
                Subfolder: "rwc",
                Baselinefolder: "internal/baselines"
            };
            const baseName = ts.getBaseFileName(jsonPath);
            let currentDirectory: string;
            let useCustomLibraryFile: boolean;
            let caseSensitive: boolean;
            after(() => {
                // Mocha holds onto the closure environment of the describe callback even after the test is done.
                // Therefore we have to clean out large objects after the test is done.
                inputFiles = [];
                otherFiles = [];
                tsconfigFiles = [];
                compilerResult = undefined!;
                compilerOptions = undefined!;
                currentDirectory = undefined!;
                // useCustomLibraryFile is a flag specified in the json object to indicate whether to use built/local/lib.d.ts
                // or to use lib.d.ts inside the json object. If the flag is true, use the lib.d.ts inside json file
                // otherwise use the lib.d.ts from built/local
                useCustomLibraryFile = false;
                caseSensitive = false;
            });

            it("can compile", function (this: Mocha.Context) {
                this.timeout(800_000); // Allow long timeouts for RWC compilations
                let opts!: ts.ParsedCommandLine;

                const ioLog: Playback.IoLog = Playback.newStyleLogIntoOldStyleLog(JSON.parse(Harness.IO.readFile(`internal/cases/rwc/${jsonPath}/test.json`)!), Harness.IO, `internal/cases/rwc/${baseName}`);
                currentDirectory = ioLog.currentDirectory;
                useCustomLibraryFile = !!ioLog.useCustomLibraryFile;
                runWithIOLog(ioLog, () => {
                    opts = ts.parseCommandLine(ioLog.arguments, fileName => Harness.IO.readFile(fileName));
                    assert.equal(opts.errors.length, 0);

                    // To provide test coverage of output javascript file,
                    // we will set noEmitOnError flag to be false.
                    opts.options.noEmitOnError = false;
                });
                let fileNames = opts.fileNames;

                runWithIOLog(ioLog, () => {
                    const tsconfigFile = ts.forEach(ioLog.filesRead, f => vpath.isTsConfigFile(f.path) ? f : undefined);
                    if (tsconfigFile) {
                        const tsconfigFileContents = getHarnessCompilerInputUnit(tsconfigFile.path);
                        tsconfigFiles.push({ unitName: tsconfigFile.path, content: tsconfigFileContents.content });
                        const parsedTsconfigFileContents = ts.parseJsonText(tsconfigFile.path, tsconfigFileContents.content);
                        const configParseHost: ts.ParseConfigHost = {
                            useCaseSensitiveFileNames: Harness.IO.useCaseSensitiveFileNames(),
                            fileExists: Harness.IO.fileExists,
                            readDirectory: Harness.IO.readDirectory,
                            readFile: Harness.IO.readFile
                        };
                        const configParseResult = ts.parseJsonSourceFileConfigFileContent(parsedTsconfigFileContents, configParseHost, ts.getDirectoryPath(tsconfigFile.path));
                        fileNames = configParseResult.fileNames;
                        opts.options = ts.extend(opts.options, configParseResult.options);
                        ts.setConfigFileInOptions(opts.options, configParseResult.options.configFile);
                    }

                    // Deduplicate files so they are only printed once in baselines (they are deduplicated within the compiler already)
                    const uniqueNames = new ts.Map<string, true>();
                    for (const fileName of fileNames) {
                        // Must maintain order, build result list while checking map
                        const normalized = ts.normalizeSlashes(Harness.IO.resolvePath(fileName)!);
                        if (!uniqueNames.has(normalized)) {
                            uniqueNames.set(normalized, true);
                            // Load the file
                            inputFiles.push(getHarnessCompilerInputUnit(fileName));
                        }
                    }

                    // Add files to compilation
                    for (const fileRead of ioLog.filesRead) {
                        const unitName = ts.normalizeSlashes(Harness.IO.resolvePath(fileRead.path)!);
                        if (!uniqueNames.has(unitName) && !Harness.isDefaultLibraryFile(fileRead.path)) {
                            uniqueNames.set(unitName, true);
                            otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
                        }
                        else if (!opts.options.noLib && Harness.isDefaultLibraryFile(fileRead.path) && !uniqueNames.has(unitName) && useCustomLibraryFile) {
                            // If useCustomLibraryFile is true, we will use lib.d.ts from json object
                            // otherwise use the lib.d.ts from built/local
                            // Majority of RWC code will be using built/local/lib.d.ts instead of
                            // lib.d.ts inside json file. However, some RWC cases will still use
                            // their own version of lib.d.ts because they have customized lib.d.ts
                            uniqueNames.set(unitName, true);
                            inputFiles.push(getHarnessCompilerInputUnit(fileRead.path));
                        }
                    }
                });

                if (useCustomLibraryFile) {
                    // do not use lib since we already read it in above
                    opts.options.lib = undefined;
                    opts.options.noLib = true;
                }

                caseSensitive = ioLog.useCaseSensitiveFileNames || false;
                // Emit the results
                compilerResult = Harness.Compiler.compileFiles(
                    inputFiles,
                    otherFiles,
                    { useCaseSensitiveFileNames: "" + caseSensitive },
                    opts.options,
                    // Since each RWC json file specifies its current directory in its json file, we need
                    // to pass this information in explicitly instead of acquiring it from the process.
                    currentDirectory);
                compilerOptions = compilerResult.options;

                function getHarnessCompilerInputUnit(fileName: string): Harness.Compiler.TestFile {
                    const unitName = ts.normalizeSlashes(Harness.IO.resolvePath(fileName)!);
                    let content: string;
                    try {
                        content = Harness.IO.readFile(unitName)!;
                    }
                    catch (e) {
                        content = Harness.IO.readFile(fileName)!;
                    }
                    return { unitName, content };
                }
            });

            it("has the expected emitted code", function (this: Mocha.Context) {
                this.timeout(100_000); // Allow longer timeouts for RWC js verification
                Harness.Baseline.runMultifileBaseline(baseName, "", () => {
                    return Harness.Compiler.iterateOutputs(compilerResult.js.values());
                }, baselineOpts, [".js", ".jsx"]);
            });

            it("has the expected declaration file content", () => {
                Harness.Baseline.runMultifileBaseline(baseName, "", () => {
                    if (!compilerResult.dts.size) {
                        return null; // eslint-disable-line no-null/no-null
                    }

                    return Harness.Compiler.iterateOutputs(compilerResult.dts.values());
                }, baselineOpts, [".d.ts"]);
            });

            it("has the expected source maps", () => {
                Harness.Baseline.runMultifileBaseline(baseName, "", () => {
                    if (!compilerResult.maps.size) {
                        return null; // eslint-disable-line no-null/no-null
                    }

                    return Harness.Compiler.iterateOutputs(compilerResult.maps.values());
                }, baselineOpts, [".map"]);
            });

            it("has the expected errors", () => {
                Harness.Baseline.runMultifileBaseline(baseName, ".errors.txt", () => {
                    if (compilerResult.diagnostics.length === 0) {
                        return null; // eslint-disable-line no-null/no-null
                    }
                    // Do not include the library in the baselines to avoid noise
                    const baselineFiles = tsconfigFiles.concat(inputFiles, otherFiles).filter(f => !Harness.isDefaultLibraryFile(f.unitName));
                    const errors = compilerResult.diagnostics.filter(e => !e.file || !Harness.isDefaultLibraryFile(e.file.fileName));
                    return Harness.Compiler.iterateErrorBaseline(baselineFiles, errors, { caseSensitive, currentDirectory });
                }, baselineOpts);
            });

            // Ideally, a generated declaration file will have no errors. But we allow generated
            // declaration file errors as part of the baseline.
            it("has the expected errors in generated declaration files", () => {
                if (compilerOptions.declaration && !compilerResult.diagnostics.length) {
                    Harness.Baseline.runMultifileBaseline(baseName, ".dts.errors.txt", () => {
                        if (compilerResult.diagnostics.length === 0) {
                            return null; // eslint-disable-line no-null/no-null
                        }

                        const declContext = Harness.Compiler.prepareDeclarationCompilationContext(
                            inputFiles, otherFiles, compilerResult, /*harnessSettings*/ undefined!, compilerOptions, currentDirectory // TODO: GH#18217
                        );
                        // Reset compilerResult before calling into `compileDeclarationFiles` so the memory from the original compilation can be freed
                        const links = compilerResult.symlinks;
                        compilerResult = undefined!;
                        const declFileCompilationResult = Harness.Compiler.compileDeclarationFiles(declContext, links)!;

                        return Harness.Compiler.iterateErrorBaseline(tsconfigFiles.concat(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles), declFileCompilationResult.declResult.diagnostics, { caseSensitive, currentDirectory });
                    }, baselineOpts);
                }
            });
        });
    }

    export class RWCRunner extends Harness.RunnerBase {
        public enumerateTestFiles() {
            // see also: `enumerateTestFiles` in tests/webTestServer.ts
            return Harness.IO.getDirectories("internal/cases/rwc/");
        }

        public kind(): Harness.TestRunnerKind {
            return "rwc";
        }

        /** Setup the runner's tests so that they are ready to be executed by the harness
         *  The first test should be a describe/it block that sets up the harness's compiler instance appropriately
         */
        public initializeTests(): void {
            // Read in and evaluate the test list
            for (const test of this.tests && this.tests.length ? this.tests : this.getTestFiles()) {
                this.runTest(typeof test === "string" ? test : test.file);
            }
        }

        private runTest(jsonFileName: string) {
            runRWCTest(jsonFileName);
        }
    }
}


text:
using System;
using AutoMapper;
using Domain.Objetos;

namespace ApiRest.ViewModels
{
    internal class ViewModelToDomainMappingProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<ProdutoViewModel, Produto>();
            CreateMap<LoteViewModelRecebimento, Lote>();
            CreateMap<PontoDeVendaViewModel, PontoDeVenda>();
            CreateMap<EnderecoViewModel, Endereco>();
            CreateMap<PedidoViewModelRecebimento, Pedido>();
            CreateMap<ItemDoPedidoViewModelRecebimento, ItemDoPedido>();
            CreateMap<UsuarioViewModel, Usuario>();

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var builder = require('botbuilder');
var restify = require('restify');
const request = require('request');

var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
    console.log('%s listening to %s', server.name, server.url);
});

//create connector
//console connector
// var connector = new builder.ConsoleConnector().listen();
//chat connector
var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
}

);

//create the bot
var bot = new builder.UniversalBot(connector);

server.post('/api/messages', connector.listen());

//add in the dialog
// bot.dialog('/',function(session) {
//     // session.send('Hello, bot!')
//     var userMessage = session.message.text;
//     session.send('you said: ' + userMessage);

// });
// bot.dialog('/',[
//     function(session) {
//         builder.Prompts.text(session, 'Please enter your name');
//     },
//     function(session, result) {
//         session.send('Hello, ' + result.response);
//     }
// ]);

bot.dialog('/', [
    function (session) {
        session.beginDialog('/ensureProfile', session.userData.profile);
    },
    function (session, results) {

        request("http://api.themoviedb.org/3/search/movie?api_key=d2bd0f8ec7a732cd06702f331cc9f6b6&query=shrek", function (error, response, body) {
            console.log(process.env.MOVIE_DB_API_KEY);
            console.log(body);
            const result = JSON.parse(body);
            console.log(result.results[0].id);
   });
        request("https://api.themoviedb.org/3/movie/808/translations?api_key=d2bd0f8ec7a732cd06702f331cc9f6b6",function(error,response,body) {
            session.send(body);
            const translation = JSON.parse(body);
            var highestRow = translation.translations.length;
            session.send(highestRow.toString());
            session.send(translation.translations[highestRow-1].name);
});
        session.userData.movie = {id:808}
        //https://api.themoviedb.org/3/movie/{movie_id}?api_key=<<api_key>>&language=en-US
        request("https://api.themoviedb.org/3/movie/"+session.userData.movie.id +"?api_key="+"d2bd0f8ec7a732cd06702f331cc9f6b6"+"&language=en-US",function(error,response,body) {
            const details = JSON.parse(body);
            session.userData.movie.length = details.runtime.toString()
            session.send(details.runtime.toString());
});
         var intervalTimer = setInterval(function(){
                session.send('test');
                }, 1000);

        setTimeout(function(){
        session.send('time is up');
        clearInterval(intervalTimer)}, 5000);

        //   HttpResponse<String> response = Unirest.get("https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&language=en-US&api_key=%3C%3Capi_key%3E%3E").body("{}").asString();

        // session.userData.profile = results.response;
        // session.send('Hello %(name)s! I love %(company)s!',session.userData.profile);
    }
]);

bot.dialog('/ensureProfile', [
    function (session, args, next) {
        session.dialogData.profile = args || {};
        if (!session.dialogData.profile.name) {
            builder.Prompts.text(session, "what's your name?");
        } else {
            next();
        }
    },
    function (session, results, next) {
        if (results.response) {
            session.dialogData.profile.name = results.response;
        }
        if (!session.dialogData.profile.company) {
            builder.Prompts.text(session, "What company do you work for?");

        } else {
            next();
        }
    },
    function (session, results, next) {
        if (results.response) {
            session.dialogData.profile.company = results.response;
        }
        session.endDialogWithResult({ response: session.dialogData.profile });
    }
]);


text:
package mx.skyguardian.controltower.http.remoting;

public abstract class AbstractSession {
	private String eid = "";
	private Long tm = 0L;

	public String getEid() {
		return eid;
	}

	public void setEid(String eid) {
		this.eid = eid;
	}

	public Long getTm() {
		return tm;
	}

	public void setTm(Long tm) {
		this.tm = tm;
	}
}


text:
//
//  LYActiveManu.h
//  彩票
//
//  Created by 李胜营 on 16/4/25.
//  Copyright (c) 2016年 dasheng. All rights reserved.
//

#import <UIKit/UIKit.h>
@class LYActiveManu;

@protocol LYActiveManuDelegate <NSObject>

- (void)activedidClickCloseButtonWithManu:(LYActiveManu *)actiManu;

@end
@interface LYActiveManu : UIView
/* delegate */
@property (weak, nonatomic) id<LYActiveManuDelegate> delegate;
+ (instancetype)showActiveManuInPoint:(CGPoint)point;

- (void)hideActiveManuInpoint:(CGPoint)Point complention:(void(^)())complention;
@end


text:
<!DOCTYPE html>
<html>
	<head>
		<title>CS290 Exercise Tracker</title>
		<meta charset="utf-8"/>
	</head>
	<body>
		<h2>{{ds}} was a bad value for a date submitted. It should be a positive integer, not a string.</h2>
	</body>
<html>


text:
( // Module boilerplate to support browser globals, node.js and AMD.
  (typeof module !== "undefined" && function (m) { module.exports = m(); }) ||
  (typeof define === "function" && function (m) { define('underscoreIsDefined', m); }) ||
  (function (m) { window['underscoreIsDefined'] = m(); })
)(function () { return function(_) {

return function underscoreIsDefined(reference) {
  return !_.isUndefined(reference);
};

};});


text:
<?php
/**
 * Created by PhpStorm.
 * User: svtlichnijj
 * Date: 27.01.16
 * Time: 13:48
 */

namespace AppBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PostControllerTest extends WebTestCase
{
    public function testShowPost()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/post/hello-world');

        $this->assertGreaterThan(
            0,
            $crawler->filter('html:contains("Hello World")')->count()
        );
    }
}


text:
import { AlloyEvents, AlloyTriggers, CustomEvent, EventFormat, SystemEvents } from '@ephox/alloy';
import { Id } from '@ephox/katamari';

import { GetApiType, runWithApi } from '../../controls/Controls';

export interface OnMenuItemExecuteType<T> extends GetApiType<T> {
  readonly onAction: (itemApi: T) => void;
}

export const internalToolbarButtonExecute = Id.generate('toolbar.button.execute');

export interface InternalToolbarButtonExecuteEvent<T> extends CustomEvent {
  readonly buttonApi: T;
}

// Perform `action` when an item is clicked on, close menus, and stop event
const onToolbarButtonExecute = <T>(info: OnMenuItemExecuteType<T>): AlloyEvents.AlloyEventKeyAndHandler<EventFormat> =>
  AlloyEvents.runOnExecute((comp, _simulatedEvent) => {
    // If there is an action, run the action
    runWithApi(info, comp)((itemApi: T) => {
      AlloyTriggers.emitWith(comp, internalToolbarButtonExecute, {
        buttonApi: itemApi
      });
      info.onAction(itemApi);
    });
  });

const toolbarButtonEventOrder: Record<string, string[]> = {
  // TODO: use the constants provided by behaviours.
  [SystemEvents.execute()]: [ 'disabling', 'alloy.base.behaviour', 'toggling', 'toolbar-button-events' ]
};

export { onToolbarButtonExecute, toolbarButtonEventOrder, runWithApi };


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PholioVisualisation.Analysis;
using PholioVisualisation.PholioObjects;

namespace PholioVisualisation.AnalysisTest
{
    [TestClass]
    public class SpcForDsrComparerTest
    {
        private static SpcForDsrComparer New95_0()
        {
            return new SpcForDsrComparer {
                ConfidenceVariable = 0.025,
                PolarityId = PolarityIds.RagLowIsGood
            };
        }

        private static SpcForDsrComparer New99_8()
        {
            return new SpcForDsrComparer {
                ConfidenceVariable = 0.001,
                PolarityId = PolarityIds.RagLowIsGood
            };
        }

        [TestMethod]
        public void TestCompare()
        {
            // Values taken from IndicatorId 501, MRSA per 100,000 population, 2011
            CoreDataSet comparator = new CoreDataSet { Value = 2.132708657734625 };
            IndicatorMetadata metadata =
            new IndicatorMetadata { Unit = new Unit { Value = 100000 } };

            // 5PP - Cams PCT
            CoreDataSet data = new CoreDataSet
            {
                Value = 1.1358436559886544,
                LowerCI95 = 0.4566680649368694,
                UpperCI95 = 2.34027204390037,
                Denominator2 = 616282,
                YearRange = 1
            };
            Assert.AreEqual(Significance.Better, New95_0().Compare(data, comparator, metadata));
            Assert.AreEqual(Significance.Same, New99_8().Compare(data, comparator, metadata));

            // 5PT - Suffolk PCT
            data = new CoreDataSet
            {
                Value = 2.657913272289925,
                LowerCI95 = 1.5192270945178816,
                UpperCI95 = 4.3162846329446163,
                Denominator2 = 601976,
                YearRange = 1
            };
            Assert.AreEqual(Significance.Same, New95_0().Compare(data, comparator, metadata));
            Assert.AreEqual(Significance.Same, New99_8().Compare(data, comparator, metadata));

            // 5PG - Birmingham and East PCT
            data = new CoreDataSet
            {
                Value = 4.1515156695295845,
                LowerCI95 = 2.4184108857503652,
                UpperCI95 = 6.6469787446568454,
                Denominator2 = 409489,
                YearRange = 1
            };
            Assert.AreEqual(Significance.Worse, New95_0().Compare(data, comparator, metadata));
            Assert.AreEqual(Significance.Same, New99_8().Compare(data, comparator, metadata));
        }

    }
}


text:
FROM python:2.7-alpine
MAINTAINER Marco Cotrufo <marco.cotrufo@devncode.it>

COPY . /code
EXPOSE 8000

WORKDIR /code
RUN apk add --no-cache mariadb-dev alpine-sdk && \
    pip install -r requirements.txt

VOLUME ["/code/static", "/code/media", "/code/logs"]

ENTRYPOINT ["/usr/local/bin/gunicorn", "--config", "./gunicorn.conf", "euoserver.wsgi:application"]


text:
var Feedback = require('../models/feedback');
var sum = function (array) {
            res = 0;
            array.forEach(function (f) {
                res += f.value;
            });
            return res;
        };

module.exports = {
    addFeedback: function (req, resp) {
        var feedback = new Feedback();
        var tmp = req.body.feedback;
        feedback.id = tmp.user + "_" + tmp.quarter;
        feedback.user = tmp.user;
        feedback.quarter = tmp.quarter;
        feedback.final = tmp.final;
        feedback.criteria = tmp.criteria;

        Feedback.findOne({id: feedback.id}, function (err, res) {

            if (res) {
                res.criteria = feedback.criteria;
                res.save(function (err) {
                    if (err)
                        throw err;
                    resp.status(200).json({
                        success: true,
                        message: "Feddback updated"
                    });
                });
            } else {
                feedback.save(function (err) {
                    if (err) {
                        console.log(err);
                    }
                    resp.status(200).json({
                        success: true,
                        message: "feedback added"
                    });
                });
            }
        });
    },
    getFeedbacks: function (req, resp) {
        Feedback.find(function (err, res) {
            if (err) {
                console.log(err);
            }
            resp.json(res);
        });
    },
    getAssociateFeedbacks: function (req, resp) {
        var data = {user: req.params.uid};
        if ((req.params.quarter) && (req.params.uid))
            data = {user: req.params.uid,
                quarter: req.params.quarter};

        Feedback.find(data, function (err, res) {
            if (err) {
                console.log(err);
            }
            resp.json(res);
        });
    },
    getQuarterFeedbacks: function (req, resp) {
        var self = this;

        Feedback.find({quarter: req.params.quarter}, function (err, res) {
            if (err) {
                console.log(err);
            }
            var temp = [];
            if (req.params.sum) {
                res.forEach(function (f) {
                    temp.push({
                        id: f.user,
                        value: f.criteria[req.params.sum].value
                    });
                });
            } else {
                res.forEach(function (f) {
                    temp.push({
                        id: f.user,
                        value: sum(f.criteria)
                    });
                });
            }
            resp.json(temp);
        }
        );
    },
    exportFeedbacks: function (req, resp) {
        var labels = ["How would you rate the quality and timeliness of his/her tasks?", "How would you rate the level of his/her technical knowledge?",
            "How would you rate the level of his/her engagement in discussions,planning, problem solving?", "Is he/she interested in solving problems beyond the scope of his/her duties?",
            "If there was something you didn't like in the previous performance review, did he/she improve that area?", "Is there something you want him/her to improve?", "Other + / - "];

        Feedback.find({quarter: req.params.quarter}, function (err, res) {
            var exported = "QUARTER: " + req.params.quarter + "\n";

            res.forEach(function (f) {
                exported += f.user +" "+sum(f.criteria) +" \n ========================= \n";
               // console.log(exported);
                f.criteria.forEach(function (fb, i) {
                    exported += labels[i] + ": " + fb.value + "\n comment: " + fb.comment + "\n\n";
                });

            });

            resp.append('Content-Disposition', 'attachment; filename='+req.params.quarter+'.txt').append('Content-type', 'text/csv');
            resp.status(200).send(exported);
        });

    }
};


text:
'use strict';

angular.module('mifortTimesheet.timesheet', ['ngRoute', 'constants'])

    .config(['$routeProvider', 'appVersion', function ($routeProvider, appVersion) {
        $routeProvider.when('/timesheet', {
            templateUrl: 'timesheet/timesheetView.html?rel=' + appVersion,
            controller: 'timesheetController'
        });

        $routeProvider.when('/timesheet/:userId', {
            templateUrl: 'timesheet/timesheetView.html?rel=' + appVersion,
            controller: 'timesheetController'
        });
    }])

    .controller('timesheetController', ['$scope', 'timesheetService', 'calendarService', 'preferences', 'loginService', '$routeParams', '$timeout', 'Notification', "$q", "projectSummaryService", "$filter", '$location', '$http', '$rootScope',
        function ($scope, timesheetService, calendarService, preferences, loginService, $routeParams, $timeout, Notification, $q, projectSummaryService, $filter, $location, $http, $rootScope) {
            var user;

            $scope.projects = [];
            $scope.currentPeriodIndex = 0;
            $scope.timesheetKeys = timesheetService.getTimesheetKeys();
            $scope.logs = [];
            $scope.filteredLogs = [];
            $scope.customUserId = $routeParams.userId;
            $scope.grid = {options: {reportFilters: []}};
            $scope.activeRequest = false;
            $scope.pendingChanges = false;
            $scope.timer = null;
            $scope.lastSaveTimeout = null;
            $scope.lastSavedLogs = [];
            $scope.readonly = false;

            var userRole = preferences.get('user').role.toLowerCase();

            loginService.getUser($scope.customUserId).success(function (loggedUser) {
                if (loggedUser) {
                    $scope.loading = true;

                    var uniqueProjectAssignments = [],
                        loadedProjects = 0;

                    $scope.customUserName = loggedUser.displayName;
                    user = loggedUser;

                    if (!$scope.customUserId) {
                        preferences.set('user', loggedUser);

                        //get accounts
                        $http.get('api/v1/user/accounts/' + user.email).success(function(accounts) {
                            $rootScope.accounts = accounts.filter(function (acc) {
                                return acc.companyId != user.companyId && acc.external;
                            });
                        });
                    }

                    if (user.assignments && user.assignments.length) {
                        user.assignments.forEach(function (assignment) {
                            uniqueProjectAssignments.push(assignment.projectId);
                        });
                        uniqueProjectAssignments = _.uniq(uniqueProjectAssignments);
                    }

                    //get timesheets
                    if (!uniqueProjectAssignments.length) {
                        $scope.noAssignments = true;
                        $scope.loading = false;
                    }

                    uniqueProjectAssignments.forEach(function (assignment, index) {
                        timesheetService.getProject(assignment).success(function (project) {
                            if (project && project.active) {
                                project.assignments = _.where(user.assignments, {projectId: project._id});

                                $scope.projects.splice(index, 0, project);
                            }

                            loadedProjects++;
                        }).then(function () {
                            //when all projects are loaded
                            $scope.projects = $scope.getSortedProjects();

                            var filterProjects = $scope.projects.map(function (project) {
                                return {_id: project._id, name: project.name};
                            });
                            $scope.grid.options.reportFilters = [{field: "projects", value: filterProjects}];

                            if (loadedProjects == uniqueProjectAssignments.length) {
                                $scope.init();
                            }
                        });
                    });
                }
            });

            $scope.addLogs = function (index) {
                $scope.logs.push({index: index, data: $scope.groupDatePeriodsProjects(index)});
            };
            $scope.currentPeriodLogsLoaded = function () {
                $scope.$root.$emit('projectsAndLogsLoaded', {
                    projects: $scope.projects,
                    logs: $scope.logs,
                    index: $scope.currentPeriodIndex
                });
            };
            function blockTable() {
                var blockday = $scope.getFilteredDates();
                var counter = false;
                var reject = false;
                var approve = false;
                for(var key in blockday) {
                    if(blockday[key].readyForApprove === true){
                        counter = true;
                    }else if(blockday[key].readyForApprove === false){
                        reject = true;
                    }
                    if(blockday[key].Approve === true){
                        approve = true;
                    }
                }
                if (counter === true) {
                    $scope.readonly = true;
                    $scope.rejectColor = false;
                    $scope.approveColor = false;
                } else {
                    $scope.readonly = false;
                    $scope.approveColor = false;
                    $scope.rejectColor = true;
                }
                if(reject === true){
                    $scope.readonly = false;
                    $scope.approveColor = false;
                    $scope.rejectColor = true;
                } else {
                    $scope.approveColor = false;
                    $scope.rejectColor = false;
                }
                if(approve === true){
                    $scope.readonly = true;
                    $scope.approveColor = true;
                    $scope.rejectColor = false;
                }
            }
            $scope.init = function () {
                if(localStorage["redirectDate"] && !moment(localStorage["redirectDate"], '"MM/DD/YYYY"', true).isValid()) {
                    delete localStorage["redirectDate"];
                }
                var promises = [];
                $scope.projects.forEach(function (project) {
                    var today = moment();
                    if(localStorage["redirectDate"]){
                        var redirectDate = JSON.parse(localStorage["redirectDate"]);
                        project.periods.forEach(function (v, i, arr) {
                            if(v.start === redirectDate){
                                localStorage['currentPeriodIndex']=i;
                            }
                        })
                    }
                    //scroll into cuttent week
                    project.periods.forEach(function (period, periodIndex) {
                        var momentStart = moment(new Date(period.start)),
                            momentEnd = moment(new Date(period.end));
                        if (today.isBetween(momentStart, momentEnd) || today.isSame(momentStart, 'day') || today.isSame(momentEnd, 'day')) {
                            $scope.currentPeriodIndex = +preferences.get('currentPeriodIndex') || periodIndex || 0;
                        }
                    });
                    promises.push(initPeriod(project, $scope.currentPeriodIndex));
                });

                $q.all(promises).then(function () {
                    $scope.addLogs($scope.currentPeriodIndex);
                    initWatchers("logs");
                    $scope.currentPeriodLogsLoaded();

                    $scope.filteredLogs = $scope.getFilteredDates();

                    blockTable();

                    $scope.watchFilterChanges();

                    $scope.projects.forEach(function (project) {
                        applyProjectDefaultValues(project, $scope.currentPeriodIndex);
                    });
                    $scope.loading = false;
                });
            };

            $scope.introSteps = timesheetService.introSteps;

            function initPeriod(project, periodIndex) {
                var startDate = project.periods[periodIndex].start,
                    endDate = project.periods[periodIndex].end;

                project.periods[periodIndex].timesheet = [];
                project.periods[periodIndex].userTimesheets = [];

                return timesheetService.getTimesheet(user._id, project._id, startDate, endDate).success(function (dataTimesheet) {
                    project.periods[periodIndex].userTimesheets.push.apply(project.periods[periodIndex].userTimesheets, dataTimesheet.timesheet);
                }).then(function () {

                    generateDaysTemplates(project, periodIndex);
                    applyUserTimesheets(project, periodIndex);
                });
            }

            function applyUserTimesheets(project, periodIndex) {
                var period = project.periods[periodIndex];

                project.periods[periodIndex].userTimesheets.forEach(function (day, index) {
                    var timesheetDayIndex = _.findIndex(period.timesheet, {date: moment(new Date(day.date)).format("MM/DD/YYYY")}),
                        sameDateDays,
                        lastDayWithSameDate;

                    if (timesheetDayIndex != -1) {
                        sameDateDays = _.where(period.timesheet, {date: moment(new Date(day.date)).format("MM/DD/YYYY")});
                        lastDayWithSameDate = _.findIndex(period.timesheet, {_id: sameDateDays[sameDateDays.length - 1]._id});

                        //reset client saved data
                        delete day.color;
                        delete day.placeholder;
                        day.timePlaceholder = sameDateDays[0].timePlaceholder;

                        //if current iterated log is not the first for this date to push
                        if (project.periods[periodIndex].timesheet[timesheetDayIndex] && project.periods[periodIndex].timesheet[timesheetDayIndex].date == day.date) {
                            if (!period.timesheet[timesheetDayIndex]._id) {
                                day.isFirstDayRecord = true;
                                period.timesheet[timesheetDayIndex] = day;
                            }
                            else {
                                day.isFirstDayRecord = false;
                                day.position = day.position ? day.position : period.timesheet[timesheetDayIndex].position + 1;
                                period.timesheet.splice(lastDayWithSameDate + 1, 0, day);
                            }
                        }
                        else {
                            day.isFirstDayRecord = true;
                            if (!_.findWhere(period.timesheet, {date: day.date}).comment) {
                                _.findWhere(period.timesheet, {date: day.date}).comment = day.comment;
                            }
                            angular.extend(period.timesheet[timesheetDayIndex], day);
                        }
                    }
                });
            }

            function applyProjectDefaultValues(project) {
                if (project.defaultValues) {
                    project.defaultValues.forEach(function (day) {
                        var existedDays = $scope.getSameDateDays($scope.getCurrentLogData(), day.date);

                        if (existedDays.length && day.dayId) {
                            existedDays.forEach(function (existedDay) {
                                var assignedDayType = _.findWhere(project.dayTypes, {id: day.dayId});

                                existedDay.color = assignedDayType.color;
                                existedDay.placeholder = assignedDayType.name;

                                if (!existedDay.timePlaceholder) {
                                    existedDay.timePlaceholder = assignedDayType.time;
                                }
                                if (assignedDayType.time < existedDay.timePlaceholder) {
                                    existedDay.timePlaceholder = assignedDayType.time;
                                }
                            });
                        }
                    });
                }
            }

            function generateDaysTemplates(project, periodIndex) {
                var startDate = moment(new Date(project.periods[periodIndex].start)),
                    endDate = moment(new Date(project.periods[periodIndex].end)),
                    daysToGenerate = endDate.diff(startDate, 'days'),
                    userRole = project.assignments[0].role,
                    timePlaceholder = getTimePlaceholder(project);

                for (var i = 0; i < daysToGenerate + 1; i++) {
                    var dayToPush;

                    //TODO: to template
                    project.template.userId = user._id;
                    delete project.template.time;

                    dayToPush = _.clone(project.template);
                    dayToPush.date = angular.copy(startDate).add(i, 'days').format("MM/DD/YYYY");
                    dayToPush.role = userRole;
                    dayToPush.isFirstDayRecord = true;
                    dayToPush.userName = user.displayName;
                    dayToPush.timePlaceholder = timePlaceholder;
                    project.periods[periodIndex].timesheet.push(dayToPush);
                }
            }

            function initWatchers(property) {
                $scope.lastSavedLogs = angular.copy($scope.logs);
                $scope.$watch(property, function (newValue, oldValue) {
                if($scope.logs.length > 1) {
                    $scope.lastSavedLogs = angular.copy(oldValue);
                }
                    updateTimelog();
                }, true);
            }

            function updateTimelog() {
                var newLogs = $scope.getCurrentLog($scope.logs),
                    oldLogs = $scope.getCurrentLog($scope.lastSavedLogs);
                if (newLogs && !oldLogs) return;

                var newLogsData = newLogs.data,
                    oldLogsData = oldLogs.data;
                if (newLogsData.length >= oldLogsData.length) {
                    var newValueToCompare = $scope.getNotEmptyLogs(newLogsData).map(function (log) {
                        return {projectId: log.projectId, time: log.time, comment: log.comment};
                    });

                    var oldValueToCompare = $scope.getNotEmptyLogs(oldLogsData).map(function (log) {
                        return {projectId: log.projectId, time: log.time, comment: log.comment};
                    });

                    if (!_.isEqual(newValueToCompare, oldValueToCompare)) {
                        var dates = $scope.getSortedLogs();

                        var timesheetToSave = angular.copy(dates);

                        timesheetToSave.map(function (log) {
                            if (log.time !== '' && log.time !== null) {
                                log.time = +log.time;
                            }
                            if (log.time == "") {
                                log.time = null;
                            }
                            return log;
                        });

                        if ($scope.timer) {
                            $timeout.cancel($scope.timer);
                        }

                        var logsToDelete = angular.copy($scope.getLogsToDelete());

                        if (logsToDelete.length || timesheetToSave.length) {
                            $scope.timer = $timeout(function () {
                                if (!$scope.activeRequest) {
                                    $scope.activeRequest = true;

                                    $scope.lastSavedLogs = angular.copy($scope.logs);

                                    timesheetService.updateTimesheet(user._id, timesheetToSave, logsToDelete).success(function (data) {
                                        var periodTimesheet = $scope.getNotEmptyDates(),
                                            noIdLog = _.find(periodTimesheet, function (log) {
                                                return !log._id;
                                            });

                                        if (noIdLog) {
                                            var index = 0;
                                            dates.forEach(function (item) {
                                                if (item.time || item.comment) {
                                                    if (!item._id) {
                                                        item._id = data.timesheet[index]._id;
                                                    }
                                                    index++;
                                                }
                                            });
                                        }

                                        Notification.success('Changes saved');

                                        $scope.activeRequest = false;

                                        if ($scope.pendingChanges) {
                                            console.log('pending changes are saving...');
                                            $scope.pendingChanges = false;
                                            updateTimelog();
                                        } else {
                                            console.log('no pending changes');
                                        }
                                    }).error(function () {
                                        $scope.activeRequest = false;
                                    });
                                }
                                else {
                                    $scope.pendingChanges = true;
                                }
                            }, 500);
                        }
                    }
                }
            }

            $scope.getSortedLogs = function () {
                var dates = $scope.getNotEmptyDates();
                return dates.sort(function (a, b) {
                    var result = 0;
                    if (a.date > b.date) {
                        result = 1;
                    }
                    if (a.date < b.date) {
                        result = -1;
                    }

                    if (!result && a.position > b.position) {
                        result = 1;
                    }
                    if (!result && a.position < b.position) {
                        result = -1;
                    }
                    return result;
                });
            };

            $scope.calcNewLogPosition = function (logs, date) {
                var sameDateDays = $scope.getSameDateDays(logs, date);

                var maxPosition = 0;

                sameDateDays.forEach(function (sameDateDay) {
                    if (sameDateDay.position > maxPosition) {
                        maxPosition = sameDateDay.position;
                    }
                });

                return maxPosition + 1;
            };

            $scope.getSameDateDays = function (logs, date) {
                return _.filter(logs, function (log) {
                    return log.date == date;
                });
            };
            // function AddTimesheetBt() {
            //     var add_timesheet = document.getElementsByClassName("add-timesheet");
            //     console.log(add_timesheet.length);
            //     for(var i; i<add_timesheet.length;i++){
            //         add_timesheet[i].onclick=function () {
            //             console.log(123);
            //         }
            //     }
            // }
            $scope.addLog = function (log) {

                var projectId = $scope.getDefaultProject()._id;
                var project = $scope.getProjectById(projectId);
                var newRow = angular.copy(project.template),
                    currentPeriod = $scope.getCurrentLogData(),
                    dayPeriodIndex = _.findIndex(currentPeriod, {date: log.date});

                newRow.date = log.date;
                newRow.userName = log.userName;
                newRow.color = log.color;
                newRow.placeholder = log.placeholder;
                newRow.timePlaceholder = getTimePlaceholder(project);
                newRow.role = log.role;
                newRow.isFirstDayRecord = false;
                newRow.position = $scope.calcNewLogPosition(currentPeriod, log.date);
                $scope.setDefaultProject(newRow);

                newRow.hasLog = true;
                newRow.isCreatedManually = true;
                currentPeriod.splice(dayPeriodIndex + $scope.getSameDateDays(currentPeriod, log.date).length, 0, newRow);

                $scope.filteredLogs = $scope.getFilteredDates();
            };
            $scope.removeRow = function (log, project, periodIndex) {
                var dates = $scope.getCurrentLogData();

                if (log._id && (log.time || log.comment)) {
                    timesheetService.removeTimesheet(log).success(function () {
                        Notification.success('Changes saved');
                    });
                }

                dates.splice(dates.indexOf(log), 1);

                $scope.filteredLogs = $scope.getFilteredDates();
                $scope.lastSavedLogs = angular.copy($scope.logs);
            };

            $scope.showPreviousPeriod = function (projects) {
                delete localStorage["redirectDate"];
                var lastPeriod = $scope.currentPeriodIndex;

                if ($scope.currentPeriodIndex) {
                    $scope.currentPeriodIndex--;

                    loadLogs(projects, lastPeriod, $scope.currentPeriodIndex);
                }

                preferences.set('currentPeriodIndex', $scope.currentPeriodIndex);
            };

            $scope.showNextPeriod = function (projects) {
                delete localStorage["redirectDate"];
                var lastPeriod = $scope.currentPeriodIndex;

                if ($scope.currentPeriodIndex < projects[0].periods.length - 1) {
                    $scope.currentPeriodIndex++;

                    loadLogs(projects, lastPeriod, $scope.currentPeriodIndex);
                }

                preferences.set('currentPeriodIndex', $scope.currentPeriodIndex);
            };

            $scope.showCurrentPeriod = function (projects) {
                delete localStorage["redirectDate"];
                var today = moment(),
                    lastPeriod = $scope.currentPeriodIndex;

                if (!$scope.currentDatePeriod) {
                    projects[0].periods.some(function (period, index) {
                        var momentStart = moment(new Date(period.start)),
                            momentEnd = moment(new Date(period.end));

                        if (today.isBetween(momentStart, momentEnd) || today.isSame(momentStart, 'day') || today.isSame(momentEnd, 'day')) {
                            $scope.currentDatePeriod = index;

                            return true;
                        }
                    });
                }

                var isCurrentExist = $scope.currentDatePeriod !== undefined;

                if(isCurrentExist) {
                    $scope.currentPeriodIndex = $scope.currentDatePeriod;
                    loadLogs(projects, lastPeriod, $scope.currentDatePeriod);
                }

                preferences.set('currentPeriodIndex', $scope.currentPeriodIndex);
            };

            function loadLogs(projects, lastPeriod, targetPeriod) {
                var promises = [];
                projects.forEach(function (project) {
                    project.lastPeriodRecords = project.periods[lastPeriod].timesheet.length;

                    if (!project.periods[targetPeriod].timesheet) {
                        promises.push(initPeriod(project, targetPeriod));
                    }
                });

                $q.all(promises).then(function () {
                    $scope.addLogs(targetPeriod);

                    $scope.currentPeriodLogsLoaded();

                    $scope.filteredLogs = $scope.getFilteredDates();

                    blockTable();
                });
            }

            $scope.getCurrentLog = function (logs) {
                return _.findWhere(logs, {index: $scope.currentPeriodIndex});
            };
            function maxSize() {
                var maxSizeArr = document.getElementsByClassName("timesheet-hours");
                for(var i=0; i< maxSizeArr.length;i++){
                    maxSizeArr[i].setAttribute("maxlength","4");
                }
            }
            setTimeout(function () {
                maxSize();
            },200);
            $scope.getCurrentLogData = function () {
                var log = $scope.getCurrentLog($scope.logs);
                return log ? log.data : [];
            };

            $scope.getCheckedProjectFilters = function () {
                var filterProjects = _.findWhere($scope.grid.options.reportFilters, {field: "projects"});
                var checkedProjects = _.filter(filterProjects.value, {isChecked: true});
                return checkedProjects.length ? checkedProjects : filterProjects.value;
            };

            $scope.getFilteredLogs = function (logs) {
                if (!logs.length) return [];
                var checkedProjects = $scope.getCheckedProjectFilters();
                return _.filter(logs, function (logPeriod) {
                    return _.filter(checkedProjects, {_id: logPeriod.projectId}).length > 0;
                });
            };

            $scope.onSearchProjectByText = function () {
                var text = this.$parent.searchProjectByText.toLocaleLowerCase();

                var filterProjects = $scope.projects.map(function (project) {
                    return {_id: project._id, name: project.name};
                });
                $scope.grid.options.reportFilters = [{field: "projects", value: filterProjects}];
                var filterProjectsByName = _.filter($scope.grid.options.reportFilters[0].value, function (filter) {
                    return filter.name.toLowerCase().startsWith(text);
                });
                $scope.grid.options.reportFilters[0].value = filterProjectsByName;
            };

            $scope.getFilteredDates = function () {
                var data = $scope.getCurrentLogData();
                var filteredLogs = $scope.getFilteredLogs(data);
                var startDate = moment(new Date($scope.projects[0].periods[$scope.currentPeriodIndex].start)),
                    endDate = moment(new Date($scope.projects[0].periods[$scope.currentPeriodIndex].end));
                if (localStorage["redirectDate"]) {
                    var endRedirectDate = $scope.startRedirectDate.split("/");
                    endRedirectDate[1] = String(Number(endRedirectDate[1])+6);
                    endRedirectDate = endRedirectDate.join("/");
                    startDate = moment(new Date($scope.startRedirectDate));
                    endDate = moment(new Date(endRedirectDate));
                }
                var daysToGenerate = endDate.diff(startDate, 'days');
                var projectId = $scope.getDefaultProject()._id;
                var project = $scope.getProjectById(projectId);
                var logs = [];
                for (var i = 0; i < daysToGenerate + 1; i++) {
                    var date = angular.copy(startDate).add(i, 'days').format("MM/DD/YYYY");

                    var logsOnDate = $scope.getSameDateDays(filteredLogs, date);

                    if (!logsOnDate.length) {
                        var newRow = angular.copy(project.template);
                        newRow.date = date;
                        newRow.time = null;
                        newRow.comment = null;
                        newRow._id = null;
                        newRow.isCreatedManually = false;
                        newRow.position = $scope.calcNewLogPosition(data, date);
                        newRow.timePlaceholder = getTimePlaceholder(project);
                        newRow.userName = user.displayName;

                        $scope.setDefaultProject(newRow);
                        newRow.isFirstDayRecord = $scope.isFirstDayRecord(logs, date);

                        logs.push(newRow);

                        var dayPeriodIndex = _.findIndex(data, {date: date});
                        data.splice(dayPeriodIndex + $scope.getSameDateDays(data, date).length, 0, newRow);

                        applyProjectDefaultValues($scope.projects[0], $scope.currentPeriodIndex);
                    }
                    else {
                        var wasAdded = false;
                        logsOnDate.forEach(function (log, index) {
                            if (log._id || log.time || log.comment || log.isCreatedManually ||
                                (!index && $scope.isAtOrAfterIndexCreatedManuallyLog(index, logsOnDate))) {
                                log.isFirstDayRecord = $scope.isFirstDayRecord(logs, log.date);
                                logs.push(log);

                                applyProjectDefaultValues($scope.projects[0], $scope.currentPeriodIndex);

                                wasAdded = true;
                            }
                        });
                        if (!wasAdded) {
                            var log = logsOnDate[0];

                            log.isFirstDayRecord = $scope.isFirstDayRecord(logs, log.date);

                            logs.push(log);

                            applyProjectDefaultValues($scope.projects[0], $scope.currentPeriodIndex);
                        }
                    }
                }

                return logs;
            };
            $scope.isAtOrAfterIndexCreatedManuallyLog = function (index, logs) {
                for (var i = index; i < logs.length; i++) {
                    if (logs[i].isCreatedManually) {
                        return true;
                    }
                }
                return false;
            };

            $scope.getSortedProjects = function () {
                return $scope.projects.sort(function (a, b) {
                    var result = 0;
                    if (!result && a.assignments[0].workload && !b.assignments[0].workload) {
                        result = -1;
                    }
                    if (!result && !a.assignments[0].workload && b.assignments[0].workload) {
                        result = 1;
                    }
                    if (!result && a.assignments[0].workload && b.assignments[0].workload) {
                        if (!result && +a.assignments[0].workload > +b.assignments[0].workload) {
                            result = -1;
                        }
                        if (!result && +a.assignments[0].workload < +b.assignments[0].workload) {
                            result = 1;
                        }
                    }
                    if (!result && a.name > b.name) {
                        result = 1;
                    }
                    if (!result && a.name < b.name) {
                        result = -1;
                    }
                    return result;
                });
            };

            $scope.getNotEmptyLogs = function (logs) {
                return _.filter(logs, function (item) {
                    return item.time || item.comment;
                });
            };

            $scope.getNotEmptyDates = function () {
                var dates = $scope.getCurrentLogData();
                return $scope.getNotEmptyLogs(dates);
            };

            $scope.getLogsToDelete = function () {
                var dates = $scope.getCurrentLogData();
                return _.filter(dates, function (item) {
                    return !item.time && !item.comment && item._id;
                });
            };

            $scope.status = {
                isOpen: false
            };

            $scope.toggleDropdown = function ($event) {
                $event.preventDefault();
                $event.stopPropagation();
                $scope.status.isOpen = !$scope.status.isOpen;
            };

            $scope.assignRole = function (role, log) {
                log.role = role;
            };

            function getTimePlaceholder(project) {
                return project ? (project.assignments[0].workload ? project.assignments[0].workload : '0') : '0';
            }

            $scope.getProjectById = function (projectId) {
                return _.findWhere($scope.projects, {_id: projectId});
            };

            $scope.assignProject = function (projectId, log) {
                var project = $scope.getProjectById(projectId);
                log.projectName = project ? project.name : '';
                log.projectId = projectId;
                log.timePlaceholder = Number(getTimePlaceholder(project));
            };

            $scope.getWeekDay = function (date) {
                return moment(new Date(date)).format("dddd");
            };

            $scope.isToday = function (date) {
                return moment(new Date(date)).isSame(new Date(), 'day');
            };

            $scope.isLastTodaysRecord = function (timesheet, index) {
                if (timesheet[index + 1]) {
                    return timesheet[index].date != timesheet[index + 1].date;
                }
            };

            $scope.getTotalLoggedTime = function () {
                return projectSummaryService.getTotalLoggedTime($scope.filteredLogs);
            };

            $scope.getTotalWorkload = function () {
                var projectsWithTime = projectSummaryService.getProjectsWithTime($scope.projects, $scope.getCurrentLogData());
                return projectSummaryService.getTotalWorkloadTime(projectsWithTime, $scope.getCurrentLogData());
            };

            $scope.watchFilterChanges = function () {
                $scope.$watch("grid.options.reportFilters", function (newValue, oldValue) {
                    $scope.filteredLogs = $scope.getFilteredDates();
                }, true);
            };

            $scope.groupDatePeriodsProjects = function (periodIndex) {
                if (!$scope.projects.length || !$scope.projects[0].periods[periodIndex].timesheet) return [];

                var allLogs = [];
                $scope.projects[0].periods[periodIndex].timesheet.forEach(function (logGroup) {
                    var logOfDate = $scope.getSameDateDays(allLogs, logGroup.date);

                    if (logOfDate.length == 0) {
                        $scope.projects.forEach(function (project) {
                            var timesheet = project.periods[periodIndex].timesheet;
                            timesheet.forEach(function (log) {
                                if (log.date == logGroup.date) {
                                    if (!log._id) {
                                        var thisDayHasLog = $scope.getSameDateDays(allLogs, log.date).length > 0;
                                        if (!thisDayHasLog && !$scope.someProjectHasLog(log.date)) {
                                            $scope.addLogToArray(log, allLogs);
                                        }
                                    }
                                    else {
                                        $scope.addLogToArray(log, allLogs);
                                    }
                                }
                            });
                        });
                    }
                });
                return allLogs;
            };

            $scope.getDefaultProject = function () {
                var checked = $scope.getCheckedProjectFilters();
                return checked.length ? checked[0] : $scope.projects[0];
            };

            $scope.setDefaultProject = function (log) {
                var project = $scope.getDefaultProject();
                log.projectId = project._id;
                log.projectName = project.name;
            };

            $scope.addLogToArray = function (log, allLogs) {
                if (!log.projectId) {
                    $scope.setDefaultProject(log);
                }

                allLogs.push(log);
            };

            $scope.isFirstDayRecord = function (allLogs, date) {
                return $scope.getSameDateDays(allLogs, date).length == 0;
            };

            $scope.someProjectHasLog = function (date) {
                var someProjectHasLog = false;
                $scope.projects.forEach(function (project) {
                    var timesheet = project.periods[$scope.currentPeriodIndex].timesheet;
                    timesheet.forEach(function (log) {
                        if (log.date == date && (log.projectId || log.time || log.comment)) {
                            someProjectHasLog = true;
                        }
                    });
                });

                return someProjectHasLog;
            };

            $scope.isStartEndPeriodSameMonth = function (period) {
                if (period) {
                    var periodStart = moment(new Date(period.start)),
                        periodEnd = moment(new Date(period.end));
                    return periodStart.format("MMM") == periodEnd.format("MMM")
                }
                return false;
            };
            $scope.dateMonth = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            $scope.getPeriodLabel = function (period) {
                if (period) {
                    var periodStart = moment(new Date(period.start)),
                        periodEnd = moment(new Date(period.end));
                    if (periodStart.format("MMM") == periodEnd.format("MMM")) {
                        periodStart = periodStart.format("DD");
                    }
                    else {
                        periodStart = periodStart.format("DD MMM");
                    }
                    periodEnd = periodEnd.format("DD MMM");
                    if (localStorage["redirectDate"]){
                        var startRedirectDate = JSON.parse(localStorage["redirectDate"]).slice(3,5);
                        $scope.startRedirectDate = JSON.parse(localStorage["redirectDate"]);
                        var monthIndex = Number(JSON.parse(localStorage["redirectDate"]).slice(0,2));
                        var monthName = $scope.dateMonth[monthIndex-1];
                        var endRedirectDate = Number(startRedirectDate) + 6;
                        if (endRedirectDate < 10){
                            endRedirectDate = "0"+endRedirectDate;
                        }
                        endRedirectDate = endRedirectDate + " " + monthName;
                        return startRedirectDate + ' - ' + endRedirectDate;
                    } else {
                        return periodStart + ' - ' + periodEnd;
                    }

                }
                else {
                    return '';
                }
            };

            $scope.userRole = preferences.get('user').role.toLowerCase();

            if ($location.$$path === "/timesheet") {
                $scope.viewUser = false;
            } else {
                $scope.viewUser = true;
            }

            $scope.locations = preferences.get('location');

            $scope.backTo = function () {
                if ($scope.locations === 'Employees') {
                    $location.path('/employees');
                } else if ($scope.locations === 'Report') {
                    $location.path('/report');
                }
            };
            $scope.approve = function (button) {
                var dates = $scope.getSortedLogs();
                var timesheetToSave = angular.copy(dates);
                timesheetToSave.forEach(function (userData) {
                    if(button === "ready") {
                        userData.readyForApprove = true;
                        userData.isreadyForApproveNeeded = true;
                        userData.Approve = false;
                    }
                    if(button === "approve") {
                        userData.Approve = true;
                        userData.readyForApprove = true;
                    }
                    if(button === "reject") {
                        userData.readyForApprove = false;
                        userData.Approve = false;
                    }
                });
                var logsToDelete = angular.copy($scope.getLogsToDelete());
                timesheetService.updateTimesheet(user._id, timesheetToSave, logsToDelete).success(function (data) {
                    Notification.success('Changes saved');
                    if(button === "ready") {
                        $scope.readonly = true;
                        $scope.approveColor = false;
                        $scope.rejectColor = false;
                    }
                    if(button === "approve") {
                        $scope.readonly = true;
                        $scope.approveColor = true;
                        $scope.rejectColor = false;
                    }
                    if(button === "reject") {
                        $scope.readonly = false;
                        $scope.approveColor = false;
                        $scope.rejectColor = true;
                    }
                }).error(function () {
                    Notification.error('Changes not saved');
                });
            };

        }]);


text:
""" A collection of functions to assist with archiving/restoring epoch files.
    Epoch files are the few files which can change from one backup to the next and so must be
    date stamped to differentiate multiple backups from each other.
    Typically only archive_epoch_files and restore_epoch_files are called

Copyright 2014 Hewlett-Packard Development Company, L.P.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT.

IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from glob import glob
import logging
import os
import shutil

log = logging.getLogger(__name__)

class EpochFiles(object):
    """ The on disk epoch files and methods to archive/restore them for a given date.
    """

    def __init__(self, backup_dir, catalog_dir, snapshot_name, date):
        self.date_str = date.strftime("%Y_%m_%d_%H%M")
        self.epoch_files = self._get_epoch_files(backup_dir, snapshot_name)

    @staticmethod
    def _get_epoch_files(backup_dir, snapshot_name):
        snap_dir = 'Snapshots/' + snapshot_name + '*/v_*_node*/'
        files = [
            glob(os.path.join(backup_dir, snap_dir))[0] + snapshot_name + '.txt',
            glob(os.path.join(backup_dir, snap_dir))[0] + snapshot_name + '.info',
            glob(os.path.join(backup_dir, snap_dir))[0] + snapshot_name + '.ctlg',
        ]
        return files

    @staticmethod
    def _move_file(from_path, to_path):
        """ Move a file on the local filesystem, logging an error if the from file does not exist.
        """
        if os.path.exists(from_path):
            shutil.move(from_path, to_path)
        else:
            log.error('File %s not found when attempting to move to %s' % (from_path, to_path))

    def archive(self):
        """ Copy epoch files to their date stamped names
        """
        for path in self.epoch_files:
            self._move_file(path, "%s_%s" % (path, self.date_str))

    def restore(self):
        """ Copy epoch files from their date stamped names to their standard names
        """
        for path in self.epoch_files:
            self._move_file("%s_%s" % (path, self.date_str), path)


text:
package commands

import (
	"compress/gzip"
	"errors"
	"fmt"
	"io"
	"os"
	gopath "path"
	"strings"

	"gx/ipfs/QmeWjRodbcZFKe5tMN7poEx3izym6osrLSnTLf9UjJZBbs/pb"

	cmds "github.com/ipfs/go-ipfs/commands"
	core "github.com/ipfs/go-ipfs/core"
	dag "github.com/ipfs/go-ipfs/merkledag"
	path "github.com/ipfs/go-ipfs/path"
	tar "github.com/ipfs/go-ipfs/thirdparty/tar"
	uarchive "github.com/ipfs/go-ipfs/unixfs/archive"
)

var ErrInvalidCompressionLevel = errors.New("Compression level must be between 1 and 9")

var GetCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Download IPFS objects.",
		ShortDescription: `
Stores to disk the data contained an IPFS or IPNS object(s) at the given path.

By default, the output will be stored at './<ipfs-path>', but an alternate
path can be specified with '--output=<path>' or '-o=<path>'.

To output a TAR archive instead of unpacked files, use '--archive' or '-a'.

To compress the output with GZIP compression, use '--compress' or '-C'. You
may also specify the level of compression by specifying '-l=<1-9>'.
`,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
	},
	Options: []cmds.Option{
		cmds.StringOption("output", "o", "The path where the output should be stored."),
		cmds.BoolOption("archive", "a", "Output a TAR archive.").Default(false),
		cmds.BoolOption("compress", "C", "Compress the output with GZIP compression.").Default(false),
		cmds.IntOption("compression-level", "l", "The level of compression (1-9).").Default(-1),
	},
	PreRun: func(req cmds.Request) error {
		_, err := getCompressOptions(req)
		return err
	},
	Run: func(req cmds.Request, res cmds.Response) {
		if len(req.Arguments()) == 0 {
			res.SetError(errors.New("not enough arugments provided"), cmds.ErrClient)
			return
		}

		cmplvl, err := getCompressOptions(req)
		if err != nil {
			res.SetError(err, cmds.ErrClient)
			return
		}

		node, err := req.InvocContext().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		p := path.Path(req.Arguments()[0])
		ctx := req.Context()
		dn, err := core.Resolve(ctx, node.Namesys, node.Resolver, p)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

		switch dn := dn.(type) {
		case *dag.ProtoNode:
			size, err := dn.Size()
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			res.SetLength(size)
		case *dag.RawNode:
			res.SetLength(uint64(len(dn.RawData())))
		default:
			res.SetError(fmt.Errorf("'ipfs get' only supports unixfs nodes"), cmds.ErrNormal)
			return
		}

		archive, _, _ := req.Option("archive").Bool()
		reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl)
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(reader)
	},
	PostRun: func(req cmds.Request, res cmds.Response) {
		if res.Output() == nil {
			return
		}
		outReader := res.Output().(io.Reader)
		res.SetOutput(nil)

		outPath, _, _ := req.Option("output").String()
		if len(outPath) == 0 {
			_, outPath = gopath.Split(req.Arguments()[0])
			outPath = gopath.Clean(outPath)
		}

		cmplvl, err := getCompressOptions(req)
		if err != nil {
			res.SetError(err, cmds.ErrClient)
			return
		}

		archive, _, _ := req.Option("archive").Bool()

		gw := getWriter{
			Out:         os.Stdout,
			Err:         os.Stderr,
			Archive:     archive,
			Compression: cmplvl,
			Size:        int64(res.Length()),
		}

		if err := gw.Write(outReader, outPath); err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
	},
}

type clearlineReader struct {
	io.Reader
	out io.Writer
}

func (r *clearlineReader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	if err == io.EOF {
		// callback
		fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF
	}
	return
}

func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader) {
	bar := makeProgressBar(out, l)
	barR := bar.NewProxyReader(r)
	return bar, &clearlineReader{barR, out}
}

func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar {
	// setup bar reader
	// TODO: get total length of files
	bar := pb.New64(l).SetUnits(pb.U_BYTES)
	bar.Output = out

	// the progress bar lib doesn't give us a way to get the width of the output,
	// so as a hack we just use a callback to measure the output, then git rid of it
	bar.Callback = func(line string) {
		terminalWidth := len(line)
		bar.Callback = nil
		log.Infof("terminal width: %v\n", terminalWidth)
	}
	return bar
}

type getWriter struct {
	Out io.Writer // for output to user
	Err io.Writer // for progress bar output

	Archive     bool
	Compression int
	Size        int64
}

func (gw *getWriter) Write(r io.Reader, fpath string) error {
	if gw.Archive || gw.Compression != gzip.NoCompression {
		return gw.writeArchive(r, fpath)
	}
	return gw.writeExtracted(r, fpath)
}

func (gw *getWriter) writeArchive(r io.Reader, fpath string) error {
	// adjust file name if tar
	if gw.Archive {
		if !strings.HasSuffix(fpath, ".tar") && !strings.HasSuffix(fpath, ".tar.gz") {
			fpath += ".tar"
		}
	}

	// adjust file name if gz
	if gw.Compression != gzip.NoCompression {
		if !strings.HasSuffix(fpath, ".gz") {
			fpath += ".gz"
		}
	}

	// create file
	file, err := os.Create(fpath)
	if err != nil {
		return err
	}
	defer file.Close()

	fmt.Fprintf(gw.Out, "Saving archive to %s\n", fpath)
	bar, barR := progressBarForReader(gw.Err, r, gw.Size)
	bar.Start()
	defer bar.Finish()

	_, err = io.Copy(file, barR)
	return err
}

func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error {
	fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath)
	bar := makeProgressBar(gw.Err, gw.Size)
	bar.Start()
	defer bar.Finish()
	defer bar.Set64(gw.Size)

	extractor := &tar.Extractor{fpath, bar.Add64}
	return extractor.Extract(r)
}

func getCompressOptions(req cmds.Request) (int, error) {
	cmprs, _, _ := req.Option("compress").Bool()
	cmplvl, cmplvlFound, _ := req.Option("compression-level").Int()
	switch {
	case !cmprs:
		return gzip.NoCompression, nil
	case cmprs && !cmplvlFound:
		return gzip.DefaultCompression, nil
	case cmprs && cmplvlFound && (cmplvl < 1 || cmplvl > 9):
		return gzip.NoCompression, ErrInvalidCompressionLevel
	}
	return cmplvl, nil
}


text:
using namespace std;

class BadRace : public exception {
	virtual const char* what() const throw() {
		return "Invalid Race";
	}
};

class UnitNotFound : public exception {
	virtual const char* what() const throw() {
		return "Unit Not Found";
	}
};


text:
require 'dragonfly/data_storage/mongo_grid_fs_store'
require 'dragonfly/mongoid_extensions/attachment'
require 'dragonfly/mongoid_extensions/validations'
require 'dragonfly/mongoid_extensions/class_methods'
require 'dragonfly/mongoid_extensions/instance_methods'


text:
package com.intellij.velocity.inspections;

import com.intellij.codeInsight.template.Expression;
import com.intellij.codeInsight.template.Template;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.velocity.VelocityBundle;
import com.intellij.velocity.psi.PsiUtil;
import com.intellij.velocity.psi.VtlLanguage;
import com.intellij.velocity.psi.directives.VtlMacroCall;
import com.intellij.velocity.psi.files.VtlFile;
import com.intellij.velocity.psi.reference.VtlReferenceExpression;
import javax.annotation.Nonnull;

import java.util.List;

/**
 * @author Alexey Chmutov
 */
public abstract class DefineMacroLibraryRefIntention extends DefineInCommentIntention {
    public DefineMacroLibraryRefIntention(@Nonnull String text) {
        super(text, VelocityBundle.message("add.macro.library.ref.fix.name"));
    }

    @Override
    protected boolean isAvailable(@Nonnull VtlReferenceExpression ref) {
        return ref.getParent() instanceof VtlMacroCall && Util.canSetVelocityProperties(ref.getContainingFile());
    }

    protected void prepareTemplate(@Nonnull Template template, @Nonnull final PsiElement element, String relativePath, @Nonnull final PsiFile fileToInsertComment) {
        assert element instanceof VtlReferenceExpression;
        final List<String> allFiles = Util.collectFilePaths(element, new Function<PsiFile, String>() {
            public String fun(@Nonnull final PsiFile psiFile) {
                PsiFile file = psiFile.getViewProvider().getPsi(VtlLanguage.INSTANCE);
                if (file instanceof VtlFile) {
                    VtlFile vtlFile = (VtlFile) file;
                    if (vtlFile.getNumberOfMacros(((VtlReferenceExpression)element).getReferenceName()) > 0) {
                        return PsiUtil.getRelativePath(fileToInsertComment, vtlFile);
                    }
                }
                return null;
            }
        });

        template.addTextSegment("#* @vtlmacrolibrary path=\"");
        final Expression pathExpression = new StringCollectionExpression(allFiles);
        template.addVariable("PATH", pathExpression, pathExpression, true);
        final String fileRef = relativePath != null ? " file=\"" + relativePath + "\"" : "";
        template.addTextSegment("\"" + fileRef + " *#\n");
        template.addEndVariable();
    }

    public static class Local extends DefineMacroLibraryRefIntention {
        public Local() {
            super(VelocityBundle.message("add.macro.library.ref.fix.name.local"));
        }

        public void invoke(@Nonnull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
            defineInComment(editor, file, file, false);
        }
    }

    public static class LocalExternal extends DefineMacroLibraryRefIntention {
        public LocalExternal() {
            super(VelocityBundle.message("add.macro.library.ref.fix.name.external"));
        }

        public void invoke(@Nonnull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
            chooseTargetFile(file, editor, true);
        }
    }

    public static class ModuleWide extends DefineMacroLibraryRefIntention {
        public ModuleWide() {
            super(VelocityBundle.message("add.macro.library.ref.fix.name.module.wide"));
        }

        public void invoke(@Nonnull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
            chooseTargetFile(file, editor, false);
        }
    }
}


text:
package com.amazonaws.services.simpleworkflow.model;

/**
 * Event Type
 */
public enum EventType {

    WorkflowExecutionStarted("WorkflowExecutionStarted"),
    WorkflowExecutionCancelRequested("WorkflowExecutionCancelRequested"),
    WorkflowExecutionCompleted("WorkflowExecutionCompleted"),
    CompleteWorkflowExecutionFailed("CompleteWorkflowExecutionFailed"),
    WorkflowExecutionFailed("WorkflowExecutionFailed"),
    FailWorkflowExecutionFailed("FailWorkflowExecutionFailed"),
    WorkflowExecutionTimedOut("WorkflowExecutionTimedOut"),
    WorkflowExecutionCanceled("WorkflowExecutionCanceled"),
    CancelWorkflowExecutionFailed("CancelWorkflowExecutionFailed"),
    WorkflowExecutionContinuedAsNew("WorkflowExecutionContinuedAsNew"),
    ContinueAsNewWorkflowExecutionFailed("ContinueAsNewWorkflowExecutionFailed"),
    WorkflowExecutionTerminated("WorkflowExecutionTerminated"),
    DecisionTaskScheduled("DecisionTaskScheduled"),
    DecisionTaskStarted("DecisionTaskStarted"),
    DecisionTaskCompleted("DecisionTaskCompleted"),
    DecisionTaskTimedOut("DecisionTaskTimedOut"),
    ActivityTaskScheduled("ActivityTaskScheduled"),
    ScheduleActivityTaskFailed("ScheduleActivityTaskFailed"),
    ActivityTaskStarted("ActivityTaskStarted"),
    ActivityTaskCompleted("ActivityTaskCompleted"),
    ActivityTaskFailed("ActivityTaskFailed"),
    ActivityTaskTimedOut("ActivityTaskTimedOut"),
    ActivityTaskCanceled("ActivityTaskCanceled"),
    ActivityTaskCancelRequested("ActivityTaskCancelRequested"),
    RequestCancelActivityTaskFailed("RequestCancelActivityTaskFailed"),
    WorkflowExecutionSignaled("WorkflowExecutionSignaled"),
    MarkerRecorded("MarkerRecorded"),
    RecordMarkerFailed("RecordMarkerFailed"),
    TimerStarted("TimerStarted"),
    StartTimerFailed("StartTimerFailed"),
    TimerFired("TimerFired"),
    TimerCanceled("TimerCanceled"),
    CancelTimerFailed("CancelTimerFailed"),
    StartChildWorkflowExecutionInitiated("StartChildWorkflowExecutionInitiated"),
    StartChildWorkflowExecutionFailed("StartChildWorkflowExecutionFailed"),
    ChildWorkflowExecutionStarted("ChildWorkflowExecutionStarted"),
    ChildWorkflowExecutionCompleted("ChildWorkflowExecutionCompleted"),
    ChildWorkflowExecutionFailed("ChildWorkflowExecutionFailed"),
    ChildWorkflowExecutionTimedOut("ChildWorkflowExecutionTimedOut"),
    ChildWorkflowExecutionCanceled("ChildWorkflowExecutionCanceled"),
    ChildWorkflowExecutionTerminated("ChildWorkflowExecutionTerminated"),
    SignalExternalWorkflowExecutionInitiated("SignalExternalWorkflowExecutionInitiated"),
    SignalExternalWorkflowExecutionFailed("SignalExternalWorkflowExecutionFailed"),
    ExternalWorkflowExecutionSignaled("ExternalWorkflowExecutionSignaled"),
    RequestCancelExternalWorkflowExecutionInitiated("RequestCancelExternalWorkflowExecutionInitiated"),
    RequestCancelExternalWorkflowExecutionFailed("RequestCancelExternalWorkflowExecutionFailed"),
    ExternalWorkflowExecutionCancelRequested("ExternalWorkflowExecutionCancelRequested"),
    LambdaFunctionScheduled("LambdaFunctionScheduled"),
    LambdaFunctionStarted("LambdaFunctionStarted"),
    LambdaFunctionCompleted("LambdaFunctionCompleted"),
    LambdaFunctionFailed("LambdaFunctionFailed"),
    LambdaFunctionTimedOut("LambdaFunctionTimedOut"),
    ScheduleLambdaFunctionFailed("ScheduleLambdaFunctionFailed"),
    StartLambdaFunctionFailed("StartLambdaFunctionFailed");

    private String value;

    private EventType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *            real value
     * @return EventType corresponding to the value
     */
    public static EventType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");

        } else if ("WorkflowExecutionStarted".equals(value)) {
            return EventType.WorkflowExecutionStarted;
        } else if ("WorkflowExecutionCancelRequested".equals(value)) {
            return EventType.WorkflowExecutionCancelRequested;
        } else if ("WorkflowExecutionCompleted".equals(value)) {
            return EventType.WorkflowExecutionCompleted;
        } else if ("CompleteWorkflowExecutionFailed".equals(value)) {
            return EventType.CompleteWorkflowExecutionFailed;
        } else if ("WorkflowExecutionFailed".equals(value)) {
            return EventType.WorkflowExecutionFailed;
        } else if ("FailWorkflowExecutionFailed".equals(value)) {
            return EventType.FailWorkflowExecutionFailed;
        } else if ("WorkflowExecutionTimedOut".equals(value)) {
            return EventType.WorkflowExecutionTimedOut;
        } else if ("WorkflowExecutionCanceled".equals(value)) {
            return EventType.WorkflowExecutionCanceled;
        } else if ("CancelWorkflowExecutionFailed".equals(value)) {
            return EventType.CancelWorkflowExecutionFailed;
        } else if ("WorkflowExecutionContinuedAsNew".equals(value)) {
            return EventType.WorkflowExecutionContinuedAsNew;
        } else if ("ContinueAsNewWorkflowExecutionFailed".equals(value)) {
            return EventType.ContinueAsNewWorkflowExecutionFailed;
        } else if ("WorkflowExecutionTerminated".equals(value)) {
            return EventType.WorkflowExecutionTerminated;
        } else if ("DecisionTaskScheduled".equals(value)) {
            return EventType.DecisionTaskScheduled;
        } else if ("DecisionTaskStarted".equals(value)) {
            return EventType.DecisionTaskStarted;
        } else if ("DecisionTaskCompleted".equals(value)) {
            return EventType.DecisionTaskCompleted;
        } else if ("DecisionTaskTimedOut".equals(value)) {
            return EventType.DecisionTaskTimedOut;
        } else if ("ActivityTaskScheduled".equals(value)) {
            return EventType.ActivityTaskScheduled;
        } else if ("ScheduleActivityTaskFailed".equals(value)) {
            return EventType.ScheduleActivityTaskFailed;
        } else if ("ActivityTaskStarted".equals(value)) {
            return EventType.ActivityTaskStarted;
        } else if ("ActivityTaskCompleted".equals(value)) {
            return EventType.ActivityTaskCompleted;
        } else if ("ActivityTaskFailed".equals(value)) {
            return EventType.ActivityTaskFailed;
        } else if ("ActivityTaskTimedOut".equals(value)) {
            return EventType.ActivityTaskTimedOut;
        } else if ("ActivityTaskCanceled".equals(value)) {
            return EventType.ActivityTaskCanceled;
        } else if ("ActivityTaskCancelRequested".equals(value)) {
            return EventType.ActivityTaskCancelRequested;
        } else if ("RequestCancelActivityTaskFailed".equals(value)) {
            return EventType.RequestCancelActivityTaskFailed;
        } else if ("WorkflowExecutionSignaled".equals(value)) {
            return EventType.WorkflowExecutionSignaled;
        } else if ("MarkerRecorded".equals(value)) {
            return EventType.MarkerRecorded;
        } else if ("RecordMarkerFailed".equals(value)) {
            return EventType.RecordMarkerFailed;
        } else if ("TimerStarted".equals(value)) {
            return EventType.TimerStarted;
        } else if ("StartTimerFailed".equals(value)) {
            return EventType.StartTimerFailed;
        } else if ("TimerFired".equals(value)) {
            return EventType.TimerFired;
        } else if ("TimerCanceled".equals(value)) {
            return EventType.TimerCanceled;
        } else if ("CancelTimerFailed".equals(value)) {
            return EventType.CancelTimerFailed;
        } else if ("StartChildWorkflowExecutionInitiated".equals(value)) {
            return EventType.StartChildWorkflowExecutionInitiated;
        } else if ("StartChildWorkflowExecutionFailed".equals(value)) {
            return EventType.StartChildWorkflowExecutionFailed;
        } else if ("ChildWorkflowExecutionStarted".equals(value)) {
            return EventType.ChildWorkflowExecutionStarted;
        } else if ("ChildWorkflowExecutionCompleted".equals(value)) {
            return EventType.ChildWorkflowExecutionCompleted;
        } else if ("ChildWorkflowExecutionFailed".equals(value)) {
            return EventType.ChildWorkflowExecutionFailed;
        } else if ("ChildWorkflowExecutionTimedOut".equals(value)) {
            return EventType.ChildWorkflowExecutionTimedOut;
        } else if ("ChildWorkflowExecutionCanceled".equals(value)) {
            return EventType.ChildWorkflowExecutionCanceled;
        } else if ("ChildWorkflowExecutionTerminated".equals(value)) {
            return EventType.ChildWorkflowExecutionTerminated;
        } else if ("SignalExternalWorkflowExecutionInitiated".equals(value)) {
            return EventType.SignalExternalWorkflowExecutionInitiated;
        } else if ("SignalExternalWorkflowExecutionFailed".equals(value)) {
            return EventType.SignalExternalWorkflowExecutionFailed;
        } else if ("ExternalWorkflowExecutionSignaled".equals(value)) {
            return EventType.ExternalWorkflowExecutionSignaled;
        } else if ("RequestCancelExternalWorkflowExecutionInitiated".equals(value)) {
            return EventType.RequestCancelExternalWorkflowExecutionInitiated;
        } else if ("RequestCancelExternalWorkflowExecutionFailed".equals(value)) {
            return EventType.RequestCancelExternalWorkflowExecutionFailed;
        } else if ("ExternalWorkflowExecutionCancelRequested".equals(value)) {
            return EventType.ExternalWorkflowExecutionCancelRequested;
        } else if ("LambdaFunctionScheduled".equals(value)) {
            return EventType.LambdaFunctionScheduled;
        } else if ("LambdaFunctionStarted".equals(value)) {
            return EventType.LambdaFunctionStarted;
        } else if ("LambdaFunctionCompleted".equals(value)) {
            return EventType.LambdaFunctionCompleted;
        } else if ("LambdaFunctionFailed".equals(value)) {
            return EventType.LambdaFunctionFailed;
        } else if ("LambdaFunctionTimedOut".equals(value)) {
            return EventType.LambdaFunctionTimedOut;
        } else if ("ScheduleLambdaFunctionFailed".equals(value)) {
            return EventType.ScheduleLambdaFunctionFailed;
        } else if ("StartLambdaFunctionFailed".equals(value)) {
            return EventType.StartLambdaFunctionFailed;
        } else {
            throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
        }
    }
}


text:
require "tao_ui/engine"

module TaoUi
end


text:
void EditTracker::Add(const clang::SourceManager& source_manager,
                      clang::SourceLocation location,
                      llvm::StringRef original_text,
                      llvm::StringRef new_text) {
  llvm::StringRef filename;
  for (int i = 0; i < 10; i++) {
    filename = source_manager.getFilename(location);
    if (!filename.empty() || !location.isMacroID())
      break;
    // Otherwise, no filename and the SourceLocation is a macro ID. Look one
    // level up the stack...
    location = source_manager.getImmediateMacroCallerLoc(location);
  }
  assert(!filename.empty() && "Can't track edit with no filename!");
  auto result = tracked_edits_.try_emplace(original_text);
  if (result.second) {
    result.first->getValue().new_text = new_text;
  }
  result.first->getValue().filenames.try_emplace(filename);
}

void EditTracker::SerializeTo(llvm::StringRef tag,
                              llvm::raw_ostream& output) const {
  for (const auto& edit : tracked_edits_) {
    for (const auto& filename : edit.getValue().filenames) {
      output << filename.getKey() << ":" << tag << ":" << edit.getKey() << ":"
             << edit.getValue().new_text << "\n";
    }
  }
}


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="navig.graphics">
<refmeta>
<refentrytitle>navig.graphics</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">boolean</refmiscinfo>
</refmeta>
<refnamediv>
<refname>navig.graphics</refname>
<refpurpose>Use graphics in navigational headers and footers?</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="navig.graphics.frag">
<xsl:param name="navig.graphics" select="0"/>
</src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>

<para>If non-zero, the navigational headers and footers in chunked
HTML are presented in an alternate style that uses graphical icons for
Next, Previous, Up, and Home.  Default graphics are provided in the
distribution. If zero, text is used instead of graphics.
</para>

</refsection>
</refentry>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaerella angelicae (Woron.) Sacc., 1928

### Remarks
null


text:
namespace Despise
{
    public class CommonChineseSentenseGenerator : GeneratorBase<string>
    {
        public override string Generate()
        {
            return Get<CommonChinesePhraseGenerator>().Generate(3, 15) + "。";
        }
    }
}