text:
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";

    var fileToken;

    var page = WinJS.UI.Pages.define("/html/scenario6_SaveCachedFile.html", {
        ready: function (element, options) {
            element.querySelector(".saveFileButton").addEventListener("click", saveFile, false);
            element.querySelector(".writeFileButton").addEventListener("click", writeFile, false);

            if (options && options.activationKind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
                continueFileSavePicker(options.activatedEventArgs);
            }
        }
    });

    function saveFile() {
        // Clean scenario output
        WinJS.log && WinJS.log("", "sample", "status");

        // Create the picker object and set options
        var savePicker = new Windows.Storage.Pickers.FileSavePicker();
        // Dropdown of file types the user can save the file as
        savePicker.fileTypeChoices.insert("Plain Text", [".txt"]);
        // Default file name if the user does not type one in or select a file to replace
        savePicker.suggestedFileName = "New Document";

        savePicker.pickSaveFileAndContinue();
    }

    // Called when app is activated from file save picker
    // eventObject contains the returned file picked by user
    function continueFileSavePicker(eventObject) {
        var file = eventObject[0].file;

        if (file) {
            fileToken = Windows.Storage.AccessCache.StorageApplicationPermissions.futureAccessList.add(file);
            WinJS.log && WinJS.log("Recieved File: " + file.name, "sample", "status");
            writeFileButton.disabled = false;
        } else {
            // The picker was dismissed with no selected file
            WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
        }
    }

    function writeFile() {
        if (fileToken) {
            Windows.Storage.AccessCache.StorageApplicationPermissions.futureAccessList.getFileAsync(fileToken).then(function (file) {
                if (file) {
                    // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                    Windows.Storage.CachedFileManager.deferUpdates(file);
                    var now = Windows.Globalization.DateTimeFormatting.DateTimeFormatter.longTime.format(new Date());
                    Windows.Storage.FileIO.appendTextAsync(file, "\nText Added @ " + now).then(function () {
                        Windows.Storage.CachedFileManager.completeUpdatesAsync(file).then(function (fileUpdateStatus) {
                            switch (fileUpdateStatus) {
                                case Windows.Storage.Provider.FileUpdateStatus.complete:
                                    WinJS.log && WinJS.log("File " + file.name + " was saved.", "sample", "status");
                                    printFileAsync(file);
                                    break;

                                case Windows.Storage.Provider.FileUpdateStatus.completeAndRenamed:
                                    WinJS.log && WinJS.log("File " + file.name + " was renamed and saved.", "sample", "status");
                                    Windows.Storage.AccessCache.StorageApplicationPermissions.futureAccessList.addOrReplace(fileToken, file);
                                    printFileAsync(file);
                                    break;

                                default:
                                    WinJS.log && WinJS.log("File " + file.name + " couldn't be saved.", "sample", "status");
                                    break;
                            }
                        }, WinJS.log);
                    }, WinJS.log);
                }
            }, WinJS.log);
        }
    }

    function printFileAsync(file) {
        Windows.Storage.FileIO.readTextAsync(file).then(function (fileContent) {
            WinJS.log && WinJS.log("Recieved File: " + file.name + "\n" + "File Content: " + fileContent, "sample", "status");
        }, WinJS.log);
    }
})();


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================================
	WinRTMisc.h: WinRT platform misc functions
==============================================================================================*/

#pragma once
#include "GenericPlatform/GenericPlatformMisc.h"
#include "HAL/Platform.h"
#include "Misc/Build.h"
#include "WinRT/WinRTSystemIncludes.h"

class FString;

/**
 * WinRT implementation of the misc OS functions
 */
struct CORE_API FWinRTMisc : public FGenericPlatformMisc
{
	static void PlatformPreInit();
	static void PlatformInit();
	static class GenericApplication* CreateApplication();
	static void GetEnvironmentVariable(const TCHAR* VariableName, TCHAR* Result, int32 ResultLength);

#if !UE_BUILD_SHIPPING
	FORCEINLINE static bool IsDebuggerPresent()
	{
		return !!::IsDebuggerPresent();
	}
	FORCEINLINE static void DebugBreak()
	{
		if (IsDebuggerPresent())
		{
			int32* pBreak = NULL;
			*pBreak++;
		}
	}
#endif

	static void PumpMessages(bool bFromMainLoop);
	static uint32 GetKeyMap(uint32* KeyCodes, FString* KeyNames, uint32 MaxMappings);
	static uint32 GetCharKeyMap(uint32* KeyCodes, FString* KeyNames, uint32 MaxMappings);
	static void LowLevelOutputDebugString(const TCHAR *Message);
	static void RequestExit(bool Force);
	static const TCHAR* GetSystemErrorMessage(TCHAR* OutBuffer, int32 BufferCount, int32 Error);
	static void CreateGuid(struct FGuid& Result);
	static int32 NumberOfCores();

	/** Get the application root directory. */
	static const TCHAR* RootDir();
};

typedef FWinRTMisc FPlatformMisc;

redpajama_set_name: RedPajamaGithub


text:
package org.jbb.e2e.serenity.web.editprofile;

import static org.assertj.core.api.Assertions.assertThat;

import net.serenitybdd.core.pages.PageObject;
import net.thucydides.core.annotations.DefaultUrl;
import net.thucydides.core.annotations.Step;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;

@DefaultUrl(UcpEditProfilePage.URL)
public class UcpEditProfilePage extends PageObject {
    public static final String URL = "/ucp/profile/edit";

    @FindBy(id = "displayedName")
    WebElement displayedNameField;

    @FindBys({@FindBy(xpath = "//button[contains(text(),'Save')]")})
    WebElement saveButton;

    @FindBy(id = "ucpText")
    WebElement displayedNameLink;

    public void typeDisplayedName(String displayedName) {
        displayedNameField.clear();
        displayedNameField.sendKeys(displayedName);
    }

    public void sendForm() {
        saveButton.click();
    }

    public void containsInfoAboutIncorrectDisplayedNameLength() {
        shouldContainText("size must be between 3 and 64");
    }

    public void containsInfoAboutSavingSettingsCorrectly() {
        shouldContainText("Your settings saved correctly");
    }

    public void containsDisplayedNameAsLinkToUcp(String displayedName) {
        assertThat(displayedNameLink.getText()).isEqualTo(displayedName);
    }

    @Step
    public void dislayedNameFieldShouldBeReadOnly() {
        assertThat(displayedNameField.getAttribute("readonly")).isEqualTo("true");
    }
}


text:
package com.sequenceiq.redbeams.flow.redbeams.stop.actions;

import java.util.Map;
import java.util.Optional;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.statemachine.StateContext;
import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.common.event.Selectable;
import com.sequenceiq.flow.core.Flow;
import com.sequenceiq.flow.core.FlowParameters;
import com.sequenceiq.redbeams.api.model.common.DetailedDBStackStatus;
import com.sequenceiq.redbeams.domain.stack.DBStack;
import com.sequenceiq.redbeams.flow.redbeams.common.RedbeamsContext;
import com.sequenceiq.redbeams.flow.redbeams.common.RedbeamsEvent;
import com.sequenceiq.redbeams.flow.redbeams.common.RedbeamsFailureEvent;
import com.sequenceiq.redbeams.flow.redbeams.stop.RedbeamsStopEvent;
import com.sequenceiq.redbeams.flow.redbeams.stop.RedbeamsStopState;
import com.sequenceiq.redbeams.metrics.MetricType;
import com.sequenceiq.redbeams.metrics.RedbeamsMetricService;
import com.sequenceiq.redbeams.service.stack.DBStackStatusUpdater;

@Component("REDBEAMS_STOP_FAILED_STATE")
public class StopDatabaseServerFailedAction extends AbstractRedbeamsStopAction<RedbeamsFailureEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(StopDatabaseServerFailedAction.class);

    @Inject
    private DBStackStatusUpdater dbStackStatusUpdater;

    @Inject
    private RedbeamsMetricService metricService;

    public StopDatabaseServerFailedAction() {
        super(RedbeamsFailureEvent.class);
    }

    @Override
    protected void prepareExecution(RedbeamsFailureEvent payload, Map<Object, Object> variables) {
        Exception failureException = payload.getException();
        LOGGER.info("Error during database server stop flow:", failureException);

        String errorReason = failureException == null ? "Unknown error" : failureException.getMessage();
        Optional<DBStack> dbStack = dbStackStatusUpdater.updateStatus(payload.getResourceId(), DetailedDBStackStatus.STOP_FAILED, errorReason);
        metricService.incrementMetricCounter(MetricType.DB_STOP_FAILED, dbStack);
    }

    @Override
    protected RedbeamsContext createFlowContext(
            FlowParameters flowParameters,
            StateContext<RedbeamsStopState,
            RedbeamsStopEvent> stateContext,
            RedbeamsFailureEvent payload) {
        Flow flow = getFlow(flowParameters.getFlowId());
        flow.setFlowFailed(payload.getException());

        return super.createFlowContext(flowParameters, stateContext, payload);
    }

    @Override
    protected Selectable createRequest(RedbeamsContext context) {
        return new RedbeamsEvent(RedbeamsStopEvent.REDBEAMS_STOP_FAILURE_HANDLED_EVENT.event(), context.getDBStack().getId());
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Adobe Cyrillic 1</title>
<meta charset="UTF-8">

<link type="text/css" rel="stylesheet" href="styles.css" media="all">

Adobe Cyrillic Character Sets

                        Adobe Cyrillic 1
                        Adobe Cyrillic 2
                        Adobe Cyrillic 3

Adobe Cyrillic 1

Total number of characters: 107

Download Adobe Cyrillic 1 table

Unicode
Character
Glyph name
Character name
Notes

0400
Ѐ
uni0400
CYRILLIC CAPITAL LETTER IE WITH GRAVE

0401
Ё
uni0401
CYRILLIC CAPITAL LETTER IO

0402
Ђ
uni0402
CYRILLIC CAPITAL LETTER DJE

0403
Ѓ
uni0403
CYRILLIC CAPITAL LETTER GJE

0404
Є
uni0404
CYRILLIC CAPITAL LETTER UKRAINIAN IE

0405
Ѕ
uni0405
CYRILLIC CAPITAL LETTER DZE

0406
І
uni0406
CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I

0407
Ї
uni0407
CYRILLIC CAPITAL LETTER YI

0408
Ј
uni0408
CYRILLIC CAPITAL LETTER JE

0409
Љ
uni0409
CYRILLIC CAPITAL LETTER LJE
Upright and italic styles requires alternate form for Bulgarian

040A
Њ
uni040A
CYRILLIC CAPITAL LETTER NJE

040B
Ћ
uni040B
CYRILLIC CAPITAL LETTER TSHE

040C
Ќ
uni040C
CYRILLIC CAPITAL LETTER KJE

040D
Ѝ
uni040D
CYRILLIC CAPITAL LETTER I WITH GRAVE

040E
Ў
uni040E
CYRILLIC CAPITAL LETTER SHORT U

040F
Џ
uni040F
CYRILLIC CAPITAL LETTER DZHE

0410
А
uni0410
CYRILLIC CAPITAL LETTER A

0411
Б
uni0411
CYRILLIC CAPITAL LETTER BE

0412
В
uni0412
CYRILLIC CAPITAL LETTER VE

0413
Г
uni0413
CYRILLIC CAPITAL LETTER GHE

0414
Д
uni0414
CYRILLIC CAPITAL LETTER DE

0415
Е
uni0415
CYRILLIC CAPITAL LETTER IE

0416
Ж
uni0416
CYRILLIC CAPITAL LETTER ZHE

0417
З
uni0417
CYRILLIC CAPITAL LETTER ZE

0418
И
uni0418
CYRILLIC CAPITAL LETTER I

0419
Й
uni0419
CYRILLIC CAPITAL LETTER SHORT I

041A
К
uni041A
CYRILLIC CAPITAL LETTER KA

041B
Л
uni041B
CYRILLIC CAPITAL LETTER EL
Upright and italic styles requires alternate form for Bulgarian

041C
М
uni041C
CYRILLIC CAPITAL LETTER EM

041D
Н
uni041D
CYRILLIC CAPITAL LETTER EN

041E
О
uni041E
CYRILLIC CAPITAL LETTER O

041F
П
uni041F
CYRILLIC CAPITAL LETTER PE

0420
Р
uni0420
CYRILLIC CAPITAL LETTER ER

0421
С
uni0421
CYRILLIC CAPITAL LETTER ES

0422
Т
uni0422
CYRILLIC CAPITAL LETTER TE

0423
У
uni0423
CYRILLIC CAPITAL LETTER U

0424
Ф
uni0424
CYRILLIC CAPITAL LETTER EF

0425
Х
uni0425
CYRILLIC CAPITAL LETTER HA

0426
Ц
uni0426
CYRILLIC CAPITAL LETTER TSE

0427
Ч
uni0427
CYRILLIC CAPITAL LETTER CHE

0428
Ш
uni0428
CYRILLIC CAPITAL LETTER SHA

0429
Щ
uni0429
CYRILLIC CAPITAL LETTER SHCHA

042A
Ъ
uni042A
CYRILLIC CAPITAL LETTER HARD SIGN

042B
Ы
uni042B
CYRILLIC CAPITAL LETTER YERU

042C
Ь
uni042C
CYRILLIC CAPITAL LETTER SOFT SIGN

042D
Э
uni042D
CYRILLIC CAPITAL LETTER E

042E
Ю
uni042E
CYRILLIC CAPITAL LETTER YU

042F
Я
uni042F
CYRILLIC CAPITAL LETTER YA

0430
а
uni0430
CYRILLIC SMALL LETTER A

0431
б
uni0431
CYRILLIC SMALL LETTER BE
Upright and italic styles requires alternate form for Serbian and Macedonian

0432
в
uni0432
CYRILLIC SMALL LETTER VE
Upright and italic styles requires alternate form for Bulgarian

0433
г
uni0433
CYRILLIC SMALL LETTER GHE
Italic style requires alternate form for Serbian and Macedonian. Upright style requires alternate form for Bulgarian

0434
д
uni0434
CYRILLIC SMALL LETTER DE
Italic style requires alternate form for Serbian, Macedonian and Bulgarian. Upright style requires alternate form for Bulgarian

0435
е
uni0435
CYRILLIC SMALL LETTER IE

0436
ж
uni0436
CYRILLIC SMALL LETTER ZHE
Upright and italic styles requires alternate form for Bulgarian

0437
з
uni0437
CYRILLIC SMALL LETTER ZE

0438
и
uni0438
CYRILLIC SMALL LETTER I
Upright style requires alternate form for Bulgarian

0439
й
uni0439
CYRILLIC SMALL LETTER SHORT I
Upright style requires alternate form for Bulgarian

043A
к
uni043A
CYRILLIC SMALL LETTER KA
Upright and italic styles requires alternate form for Bulgarian

043B
л
uni043B
CYRILLIC SMALL LETTER EL
Upright and italic styles requires alternate form for Bulgarian

043C
м
uni043C
CYRILLIC SMALL LETTER EM

043D
н
uni043D
CYRILLIC SMALL LETTER EN

043E
о
uni043E
CYRILLIC SMALL LETTER O

043F
п
uni043F
CYRILLIC SMALL LETTER PE
Italic style requires alternate form for Serbian and Macedonian. Upright style requires alternate form for Bulgarian

0440
р
uni0440
CYRILLIC SMALL LETTER ER

0441
с
uni0441
CYRILLIC SMALL LETTER ES

0442
т
uni0442
CYRILLIC SMALL LETTER TE
Italic style requires alternate form for Serbian and Macedonian. Upright style requires alternate form for Bulgarian

0443
у
uni0443
CYRILLIC SMALL LETTER U

0444
ф
uni0444
CYRILLIC SMALL LETTER EF

0445
х
uni0445
CYRILLIC SMALL LETTER HA

0446
ц
uni0446
CYRILLIC SMALL LETTER TSE
Upright style requires alternate form for Bulgarian

0447
ч
uni0447
CYRILLIC SMALL LETTER CHE

0448
ш
uni0448
CYRILLIC SMALL LETTER SHA
Upright style requires alternate form for Bulgarian

0449
щ
uni0449
CYRILLIC SMALL LETTER SHCHA
Upright style requires alternate form for Bulgarian

044A
ъ
uni044A
CYRILLIC SMALL LETTER HARD SIGN
Upright style requires alternate form for Bulgarian

044B
ы
uni044B
CYRILLIC SMALL LETTER YERU
Upright style requires alternate form for Bulgarian

044C
ь
uni044C
CYRILLIC SMALL LETTER SOFT SIGN
Upright style requires alternate form for Bulgarian

044D
э
uni044D
CYRILLIC SMALL LETTER E

044E
ю
uni044E
CYRILLIC SMALL LETTER YU
Upright and italic styles requires alternate form for Bulgarian

044F
я
uni044F
CYRILLIC SMALL LETTER YA

0450
ѐ
uni0450
CYRILLIC SMALL LETTER IE WITH GRAVE

0451
ё
uni0451
CYRILLIC SMALL LETTER IO

0452
ђ
uni0452
CYRILLIC SMALL LETTER DJE

0453
ѓ
uni0453
CYRILLIC SMALL LETTER GJE
Upright style requires alternate form for Bulgarian

0454
є
uni0454
CYRILLIC SMALL LETTER UKRAINIAN IE

0455
ѕ
uni0455
CYRILLIC SMALL LETTER DZE

0456
і
uni0456
CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I

0457
ї
uni0457
CYRILLIC SMALL LETTER YI

0458
ј
uni0458
CYRILLIC SMALL LETTER JE

0459
љ
uni0459
CYRILLIC SMALL LETTER LJE
Upright and italic styles requires alternate form for Bulgarian

045A
њ
uni045A
CYRILLIC SMALL LETTER NJE
Upright and italic styles requires alternate form for Bulgarian

045B
ћ
uni045B
CYRILLIC SMALL LETTER TSHE

045C
ќ
uni045C
CYRILLIC SMALL LETTER KJE
Upright and italic styles requires alternate form for Bulgarian

045D
ѝ
uni045D
CYRILLIC SMALL LETTER I WITH GRAVE
Upright style requires alternate form for Bulgarian

045E
ў
uni045E
CYRILLIC SMALL LETTER SHORT U

045F
џ
uni045F
CYRILLIC SMALL LETTER DZHE

0462
Ѣ
uni0462
CYRILLIC CAPITAL LETTER YAT

0463
ѣ
uni0463
CYRILLIC SMALL LETTER YAT

0472
Ѳ
uni0472
CYRILLIC CAPITAL LETTER FITA

0473
ѳ
uni0473
CYRILLIC SMALL LETTER FITA

0474
Ѵ
uni0474
CYRILLIC CAPITAL LETTER IZHITSA

0475
ѵ
uni0475
CYRILLIC SMALL LETTER IZHITSA

0490
Ґ
uni0490
CYRILLIC CAPITAL LETTER GHE WITH UPTURN

0491
ґ
uni0491
CYRILLIC SMALL LETTER GHE WITH UPTURN

20B4
₴
uni20B4
HRYVNIA SIGN

20BD
₽
uni20BD
RUBLE SIGN

2116
№
uni2116
NUMERO SIGN


text:
<?xml version="1.0" ?>
<job>
  <property name="generatecopyouter">
    <string>NOT_GENERATEOUTTER</string>
  </property>
  <property name="user.input.dir">
    <string>/Users/jelovirt/Work/dita-ot/src/test/testsuite/testcase/chunk_fix_conflict_to_content/src</string>
  </property>
  <property name="outputdir">
    <string>/Users/jelovirt/Work/dita-ot/src/test/testsuite/testresult/chunk_fix_conflict_to_content/preprocess</string>
  </property>
  <property name="onlytopicinmap">
    <string>false</string>
  </property>
  <property name="InputMapDir.uri">
    <string>file:/Users/jelovirt/Work/dita-ot/src/test/testsuite/testcase/chunk_fix_conflict_to_content/src/map1.ditamap</string>
  </property>
  <property name="tempdirToinputmapdir.relative.value">
    <string/>
  </property>
  <property name="user.input.file.listfile">
    <string>usr.input.file.list</string>
  </property>
  <property name="relflagimagelist">
    <string/>
  </property>
  <property name="outercontrol">
    <string>WARN</string>
  </property>
  <property name="relflagimagefile">
    <string>relflagimage.list</string>
  </property>
  <property name="InputMapDir">
    <string>/Users/jelovirt/Work/dita-ot/src/test/testsuite/testcase/chunk_fix_conflict_to_content/src/map1.ditamap</string>
  </property>
  <property name="user.input.file.uri">
    <string>map1.ditamap</string>
  </property>
  <property name="user.input.dir.uri">
    <string>file:/Users/jelovirt/Work/dita-ot/src/test/testsuite/testcase/chunk_fix_conflict_to_content/src/</string>
  </property>
  <property name="user.input.file">
    <string>map1.ditamap</string>
  </property>
  <property name="uplevels">
    <string/>
  </property>
  <files>
    <file
      src="file:/Users/jelovirt/Work/dita-ot/src/test/testsuite/testcase/chunk_fix_conflict_to_content/src/map5.dita"
      uri="map5.dita" path="map5.dita" format="dita"/>
    <file uri="map1.dita" path="map1.dita" format="dita"/>
    <file
      src="file:/Users/jelovirt/Work/dita-ot/src/test/testsuite/testcase/chunk_fix_conflict_to_content/src/map1.ditamap"
      uri="map1.ditamap" path="map1.ditamap" format="ditamap"/>
  </files>
</job>


text:
<template name="selectComponent">

    {{initializeData}}

        {{#if readOnly}}

                {{#unless withoutLabel}}
                    {{selectLabel}}
                {{/unless}}

        {{else}}
            <div class="custom-select-label-wrapper hasPopover" data-popover="true"
                 data-toggle="popover" title="{{title}}"
                 data-content='
                    {{#if optionCollectionIndex}}

                            <input class="search-input" type="text" placeholder="{{filterPlaceHolder}}">

                    {{/if}}

                            {{#each sortedCollectionItems}}

<input id="{{_id}}" type="checkbox" {{isChecked}}/> {{optionValue}}

                            {{/each}}

             '>
                {{#unless withoutLabel}}
                    {{selectLabel}}{{#unless
                        readOnly}}{{/unless}}
                {{/unless}}

        {{/if}}

        {{#unless readOnly}}
            {{#if withoutLabel}}

            {{/if}}
        {{/unless}}

            {{#if maxSelectedOptionDisplayed}}

                    {{#unless maxSelectedOptionDisplayedReached}}
                        {{#each collectionSelectedItems}}

{{optionValue}}

                        {{else}}

{{nothingSelectedLabel}}{{#if quickSelectLabel}}
                                - {{quickSelectLabel}}{{/if}}

                        {{/each}}
                    {{else}}

{{cursorLength
                                collectionSelectedItems}}{{maxSelectedOptionDisplayedLabel}}

                    {{/unless}}

            {{/if}}

    {{cloneSearchResultInPopover}}

</template>

<template name="nonMandatorySelectComponent">

    {{initializeData}}

        {{#if readOnly}}

                {{#unless withoutLabel}}
                    {{selectLabel}}
                {{/unless}}

        {{else}}
            <div class="custom-select-label-wrapper hasPopover" data-popover="true"
                 data-toggle="popover" title="{{title}}"
                 data-content='
                 {{#if optionCollectionIndex}}

                    <input class="search-input" type="text" placeholder="{{filterPlaceHolder}}">

                {{/if}}

{{clearMessage}}

                        {{#each sortedCollectionItems}}

<input id="{{_id}}" type="checkbox" {{isChecked}}/> {{optionValue}}

                        {{/each}}

         '>
                {{#unless withoutLabel}}
                    {{selectLabel}}{{#unless
                        readOnly}}{{/unless}}
                {{/unless}}

        {{/if}}

            {{#unless readOnly}}
                {{#if withoutLabel}}

                {{/if}}
            {{/unless}}
            {{#if maxSelectedOptionDisplayed}}

                    {{#unless maxSelectedOptionDisplayedReached}}
                        {{#each collectionSelectedItems}}

{{optionValue}}

                        {{else}}

{{nothingSelectedLabel}}{{#if quickSelectLabel}}
                                - {{quickSelectLabel}}{{/if}}

                        {{/each}}
                    {{else}}

{{cursorLength
                                collectionSelectedItems}}{{maxSelectedOptionDisplayedLabel}}

                    {{/unless}}

            {{/if}}

    {{cloneSearchResultInPopover}}

</template>

<template name="customSelectPopoverOption">

        {{#each collectionItemsPopover}}

<input id="{{_id}}" type="checkbox" {{isChecked}}/>{{optionValue}}

        {{/each}}

</template>


text:
package com.itjh.doushi.Net;

/**
 * User: Axl_Jacobs(Axl.Jacobs@gmail.com)
 * Date: 2016-02-29
 * Time: 17:59
 * FIXME
 */
public interface Constant {
    String NET_NAME_SPACE = "https://api.ds.itjh.net/";
    String NET_SERVER_VERSION = "v1/rest/";
    String NET_SERVER_ADD = NET_NAME_SPACE + NET_SERVER_VERSION;
}


text:
<?php
if (!wb_has_layout()):
  return;
endif;
?>
<!DOCTYPE html>

<html class="no-js" <?php language_attributes(); ?>>

  <meta charset="<?php bloginfo('charset'); ?>" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="author" content="We studio" />

  <title><?php wb_page_title(); ?></title>

  <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />

  <link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/assets/images/favicon.ico" type="image/x-icon" />

  <?php wp_head(); ?>

<body <?php body_class(); ?>>

        <a
          class="navbar-brand"
          href="<?php echo home_url(); ?>"
          title="<?php echo esc_attr(get_bloginfo('name', 'display')); ?>"
          rel="home"><?php bloginfo('name'); ?>

        <button
          type="button"
          class="offcanvas-toggle"
          data-toggle="offcanvas"
          data-target="#offcanvas"
          title="<?php _e('Menu', 'bootstrap'); ?>">

        </button>

        <?php
        wp_nav_menu(array(
          'theme_location' => 'main',
          'menu_class'     => 'nav navbar-nav',
          'depth'          => 2,
          'walker'         => 'dropdowns',
        ));
        ?>

  <?php get_template_part('blocks/offcanvas') ?>


text:
echo "################################"
echo "Testeo de sintaxis de playbooks"
echo "Versiones:"
echo "Ansible Version: $(ansible --version)"
echo "Ansible Playbook Version: $(ansible-playbook --version)"
echo "Vagrant Version: $(vagrant --version)"
echo "################################"

echo localhost > inventory
ansible-playbook --syntax-check --list-tasks -i inventory $1
rm inventory

exit 0


text:
package com.bj58.spat.gaea.client.utility.logger;

/**
 * LogFactory
 *
 * @author Service Platform Architecture Team (spat@58.com)
 */
public final class LogFactory {

    /**
     * Get an instance of a logger object.
     *
     * @param cls the Class to log from
     * @return Logger the logger instance
     */
    public static ILog getLogger(Class cls) {
        return new FileLog(cls);
    }
}


text:
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package io.v.v23.security;

import com.google.common.base.Joiner;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.interfaces.ECPublicKey;
import java.util.ArrayList;
import java.util.List;

import io.v.v23.verror.VException;

/**
 * Encapsulator of all the cryptographic operations required to prove that a set of blessings
 * (human-readable strings) have been bound to a principal in a specific call.
 *

 * {@link Blessings} objects are meant to be presented to other principals to authenticate
 * and authorize actions.  Functions {@link VSecurity#getLocalBlessingNames} and
 * {@link VSecurity#getRemoteBlessingNames} can be used to uncover the blessing names encapsulated
 * in these objects.
 *

 * {@link Blessings} objects are immutable and multiple threads may invoke methods on
 * them simultaneously.
 *

 * See also: https://vanadium.github.io/glossary.html#blessing.
 */
public final class Blessings implements Serializable {
    private static final long serialVersionUID = 1L;

    private static native long nativeCreate(WireBlessings wire) throws VException;
    private static native Blessings nativeCreateUnion(Blessings[] blessings) throws VException;

    public static Blessings create(WireBlessings wire) {
        try {
            return new Blessings(nativeCreate(wire), wire);
        } catch (VException e) {
            throw new RuntimeException("Couldn't create blessings from WireBlessings", e);
        }
    }

    static Blessings createUnion(Blessings... blessings) throws VException {
        return nativeCreateUnion(blessings);
    }

    private long nativeRef;
    private volatile WireBlessings wire;  // can be null

    private native ECPublicKey nativePublicKey(long nativeRef) throws VException;
    private native Blessings nativeSigningBlessings(long nativeRef) throws VException;
    private native WireBlessings nativeWireFormat(long nativeRef) throws VException;

    private native void nativeFinalize(long nativeRef);

    private Blessings(long nativeRef) {
        this.nativeRef = nativeRef;
    }

    private Blessings(long nativeRef, WireBlessings wire) {
        this.nativeRef = nativeRef;
        this.wire = wire;
    }

    /**
     * Returns the public key of the principal to which blessings in this object are bound.
     * The return value may be {@code null} if the blessings are empty.
     */
    public ECPublicKey publicKey() {
        try {
            return nativePublicKey(nativeRef);
        } catch (VException e) {
            throw new RuntimeException("Couldn't get public key", e);
        }
    }

    /**
     * Returns the signing blessings in this object. (Signing blessings are blessings whose
     * caveats are universally understood and verifiable without third party discharges.)
     * The return value may be {@code null} if the blessings are empty.
     */
    public Blessings signingBlessings() {
        try {
            return nativeSigningBlessings(nativeRef);
      } catch (VException e) {
          throw new RuntimeException("Couldn't get signing blessings", e);
      }
    }

    /**
     * Returns the blessings in the wire format.
     */
    public WireBlessings wireFormat() {
        // Check the cache first as nativeWireFormat() is an expensive operation.
        synchronized (this) {
            if (wire != null) {
                return wire;
            }
        }
        WireBlessings ret = null;
        try {
            ret = nativeWireFormat(nativeRef);
        } catch (VException e) {
            throw new RuntimeException("Couldn't get wire blessings representation.", e);
        }
        synchronized (this) {
            if (wire == null) {
                wire = ret;
            }
        }
        return ret;
    }

    /**
     * Returns {@code true} iff the blessings are empty.
     */
    public boolean isEmpty() {
        return wireFormat().getCertificateChains().isEmpty();
    }

    /**
     * Returns the certificate chains stored inside the blessings.
     */
    public List<List<VCertificate>> getCertificateChains() {
        return wireFormat().getCertificateChains();
    }

    private long nativeRef() {
        return nativeRef;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(wireFormat());
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        wire = (WireBlessings) in.readObject();
        try {
            nativeRef = nativeCreate(wire);
        } catch (VException e) {
            throw new IOException("Couldn't create native blessings.", e);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (!(obj instanceof Blessings)) return false;
        Blessings other = (Blessings) obj;
        return wireFormat().equals(other.wireFormat());
    }

    @Override
    public int hashCode() {
        return wireFormat().hashCode();
    }

    @Override
    public String toString() {
        List<String> chains = new ArrayList<String>(getCertificateChains().size());
        for (List<VCertificate> certificateChain : getCertificateChains()) {
            List<String> certificateNames =
                    new ArrayList<String>(certificateChain.size());
            for (VCertificate certificate : certificateChain) {
                // TODO(ashankar): Remove once
                // https://github.com/vanadium/issues/issues/739
                // has been resolved.
                String e = certificate.getExtension().replaceAll("/", Constants.CHAIN_SEPARATOR);
                certificateNames.add(e);
            }
            chains.add(Joiner.on(Constants.CHAIN_SEPARATOR).join(certificateNames));
        }
        return Joiner.on(",").join(chains);
    }
    @Override
    protected void finalize() {
        nativeFinalize(nativeRef);
    }
}


text:
@interface WikiGlyphLabel : PaddedLabel

- (void)setWikiText:(NSString *)text color:(UIColor *)color size:(CGFloat)size baselineOffset:(CGFloat)baselineOffset;

@property (nonatomic, strong, readonly) UIColor *color;
@property (nonatomic, readonly) CGFloat size;
@property (nonatomic, readonly) CGFloat baselineOffset;

@end


text:
import re

def getwords(doc):
    splitter = re.compile('\\W*')

    # Split the words
    words = [s.lower() for s in splitter.split(doc) if len(s) > 2 and len(s) < 20]

    # Return the unique set of words only
    return dict([(w, 1) for w in words])

def initTrain(cl):
    cl.train('Nobody owns the water.', 'good')
    cl.train('the quick rabbit jumps fences', 'good')
    cl.train('buy pharmaceuticals now', 'bad')
    cl.train('make quick money at the online casino', 'bad')
    cl.train('the quick brown fox jumps', 'good')


text:
#include "tensorflow/lite/delegates/coreml/builders/pad_op_builder.h"

#include <string>

#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/core/c/builtin_op_data.h"
#include "tensorflow/lite/delegates/coreml/builders/op_factory.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"

namespace tflite {
namespace delegates {
namespace coreml {

const std::string& PadOpBuilder::DebugName() {
  if (!debug_name_.empty()) return debug_name_;
  SetDebugName(padding_type_ == PadType::kPad ? "PadOpBuilder (PAD)"
                                              : "PadOpBuilder (MIRROR_PAD)",
               node_id_);
  return debug_name_;
}

CoreML::Specification::NeuralNetworkLayer* PadOpBuilder::Build() {
  layer_->set_name(DebugName());
  if (padding_type_ == PadType::kPad) {
    layer_->mutable_padding()->mutable_constant();
  } else if (padding_type_ == PadType::kMirrorPad) {
    layer_->mutable_padding()->mutable_reflection();
  }
  return layer_.release();
}

// padding is d x 2 tensor, where d is the dimension of input.
// only paddings for width and height are considered.
void PadOpBuilder::SetPadding(const TfLiteTensor* padding) {
  const int32_t* padding_data = GetTensorData<int32_t>(padding);
  for (int i = 1; i <= 2; ++i) {
    auto* borderamount = layer_->mutable_padding()
                             ->mutable_paddingamounts()
                             ->add_borderamounts();
    borderamount->set_startedgesize(padding_data[i * 2]);
    borderamount->set_endedgesize(padding_data[i * 2 + 1]);
  }
}

void PadOpBuilder::SetConstantValue(const TfLiteTensor* constant_value) {
  layer_->mutable_padding()->mutable_constant()->set_value(
      GetTensorData<float>(constant_value)[0]);
}

TfLiteStatus PadOpBuilder::RegisterInputs(const TfLiteIntArray* inputs,
                                          TfLiteContext* context) {
  if (!(inputs->size == 2 || inputs->size == 3)) {
    TF_LITE_KERNEL_LOG(context, "Wrong # of inputs to Padding!.");
    return kTfLiteError;
  }
  AddInput(inputs->data[0]);
  SetPadding(GetInput(context, tflite_node_, 1));
  if (inputs->size == 3) {
    SetConstantValue(GetInput(context, tflite_node_, 2));
  }

  return kTfLiteOk;
}

TfLiteStatus PadOpBuilder::RegisterOutputs(const TfLiteIntArray* outputs,
                                           TfLiteContext* context) {
  if (outputs->size != 1) {
    TF_LITE_KERNEL_LOG(context, "Wrong # of outputs to Padding!.");
    return kTfLiteError;
  }
  graph_builder_->AddTensorWithID(outputs->data[0], GetOutput(context));
  return kTfLiteOk;
}

OpBuilder* CreatePadOpBuilder(GraphBuilder* graph_builder) {
  return new PadOpBuilder(graph_builder, PadType::kPad);
}

OpBuilder* CreateMirrorPadOpBuilder(GraphBuilder* graph_builder) {
  return new PadOpBuilder(graph_builder, PadType::kMirrorPad);
}

bool IsPadOpSupported(const TfLiteRegistration* registration,
                      const TfLiteNode* node, TfLiteContext* context) {
  // padding is d x 2 tensor, where d is the dimension of input.
  const TfLiteTensor* padding;
  TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &padding));
  if (!IsConstantTensor(padding)) {
    TF_LITE_KERNEL_LOG(context,
                       "%s: Only constant padding is supported for PAD.",
                       padding->name);
    return false;
  }
  if (padding->dims->data[0] != 4 || padding->dims->data[1] != 2) {
    TF_LITE_KERNEL_LOG(context, "%s: Only 4D inputs are supported for PAD.",
                       padding->name);
    return false;
  }
  const int32_t* padding_data = GetTensorData<int32_t>(padding);
  if (!(padding_data[0] == 0 && padding_data[1] == 0)) {
    TF_LITE_KERNEL_LOG(
        context, "%s: Padding for batch dimension is not supported in PAD.",
        padding->name);
    return false;
  }

  if (!(padding_data[6] == 0 && padding_data[7] == 0)) {
    TF_LITE_KERNEL_LOG(
        context, "%s: Padding for channel dimension is not supported in PAD.",
        padding->name);
    return false;
  }
  return true;
}

bool IsMirrorPadOpSupported(const TfLiteRegistration* registration,
                            const TfLiteNode* node, TfLiteContext* context) {
  auto* params =
      reinterpret_cast<TfLiteMirrorPaddingParams*>(node->builtin_data);
  if (params->mode != kTfLiteMirrorPaddingReflect) {
    TF_LITE_KERNEL_LOG(context,
                       "Only REFLECT mode is supported for MIRROR_PAD.");
    return false;
  }
  return IsPadOpSupported(registration, node, context);
}

}  // namespace coreml
}  // namespace delegates
}  // namespace tflite


text:
require 'active_record'
require 'standby/version'
require 'standby/base'
require 'standby/error'
require 'standby/connection_holder'
require 'standby/transaction'
require 'standby/active_record/base'
require 'standby/active_record/connection_handling'
require 'standby/active_record/relation'
require 'standby/active_record/log_subscriber'

module Standby
  class << self
    attr_accessor :disabled

    def standby_connections
      @standby_connections ||= {}
    end

    def on_standby(name = :null_state, &block)
      raise Standby::Error.new('invalid standby target') unless name.is_a?(Symbol)
      Base.new(name).run &block
    end

    def on_primary(&block)
      Base.new(:primary).run &block
    end
  end
end


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Venue.style'
        db.add_column(u'venues_venue', 'style',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True),
                      keep_default=False)

        # Adding field 'Venue.twitter'
        db.add_column(u'venues_venue', 'twitter',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True),
                      keep_default=False)

        # Adding field 'Venue.phone'
        db.add_column(u'venues_venue', 'phone',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=30, blank=True),
                      keep_default=False)

        # Adding field 'Venue.contact'
        db.add_column(u'venues_venue', 'contact',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=50, blank=True),
                      keep_default=False)

        # Adding field 'Venue.contact_email'
        db.add_column(u'venues_venue', 'contact_email',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=50, blank=True),
                      keep_default=False)

        # Adding field 'Venue.contact_twitter'
        db.add_column(u'venues_venue', 'contact_twitter',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True),
                      keep_default=False)

        # Adding field 'Venue.cost'
        db.add_column(u'venues_venue', 'cost',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True),
                      keep_default=False)

        # Adding field 'Venue.capacity'
        db.add_column(u'venues_venue', 'capacity',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=200, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Venue.style'
        db.delete_column(u'venues_venue', 'style')

        # Deleting field 'Venue.twitter'
        db.delete_column(u'venues_venue', 'twitter')

        # Deleting field 'Venue.phone'
        db.delete_column(u'venues_venue', 'phone')

        # Deleting field 'Venue.contact'
        db.delete_column(u'venues_venue', 'contact')

        # Deleting field 'Venue.contact_email'
        db.delete_column(u'venues_venue', 'contact_email')

        # Deleting field 'Venue.contact_twitter'
        db.delete_column(u'venues_venue', 'contact_twitter')

        # Deleting field 'Venue.cost'
        db.delete_column(u'venues_venue', 'cost')

        # Deleting field 'Venue.capacity'
        db.delete_column(u'venues_venue', 'capacity')

    models = {
        u'venues.address': {
            'Meta': {'object_name': 'Address'},
            'country': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'postcode': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
            'street': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'town': ('django.db.models.fields.CharField', [], {'max_length': '30'})
        },
        u'venues.facility': {
            'Meta': {'object_name': 'Facility'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '30'})
        },
        u'venues.venue': {
            'Meta': {'object_name': 'Venue'},
            'address': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['venues.Address']"}),
            'capacity': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'contact': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
            'contact_email': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
            'contact_twitter': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'cost': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'facilities': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['venues.Facility']", 'symmetrical': 'False'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
            'phone': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'style': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'twitter': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'website': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        }
    }

    complete_apps = ['venues']


text:
package org.javamoney.moneybook.chapter.four;

import java.util.Locale;

import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.format.MonetaryAmountFormat;

import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.MonetaryAmountDecimalFormatBuilder;

/**
 * Created by otaviojava on 29/05/15.
 */
public class MonetaryAmountDecimalFormatBuilderExample {

    public static void main(String[] args) {
    	MonetaryAmountFormat defaultFormat = MonetaryAmountDecimalFormatBuilder.newInstance().build();
    	MonetaryAmountFormat patternFormat = MonetaryAmountDecimalFormatBuilder.of("¤ ###,###.00").build();
    	MonetaryAmountFormat localeFormat = MonetaryAmountDecimalFormatBuilder.of(Locale.US).build();

        CurrencyUnit currency = Monetary.getCurrency("BRL");
        MonetaryAmount money = Money.of(12, currency);
        String format = defaultFormat.format(money);//$12.00
        MonetaryAmount moneyParsed = Money.parse(format, defaultFormat);//or using defafult.parse(format);

    }
}


text:
/*
 *
 *	Designed & Written by Jorge Israelian <jorgeisraelian@g.ucla.edu>
 *				  [2016] - [2017]
 *				All Rights Reserved.
 *
 */

/*
	NOTE: For the nope() and recommend() functions, it is important to use Math.floor() and NOT
	      Math.round() to ensure that every index has a fair chance of being selected. End cases
	      are neglected with Math.round()
*/

/*
	Using HTML GeoLocation to store latitude/longitude to later use them in Weather API call
	No parameters or return value; exits on completion
*/

function getLocation () {
	if (navigator.geolocation)
	{
		navigator.geolocation.getCurrentPosition(function(position) {
			var latitude = position.coords.latitude;
			var longitude = position.coords.longitude;
			callAPI (latitude, longitude);
  		});
	}
	else
	{
		alert ("Oops. Something went wrong! Most likely, you didn't give us access to your location. " +
		       "Try giving us access and refreshing the page. Thanks!");
	}

}

/*
	Collects time information - hours & minutes
	No parameters; Returns a string containing the time with AM/PM
*/

function getSetTime () {
	var time = new Date();
	var hours = time.getHours();
	var minutes = time.getMinutes();

	if (minutes < 10)
		minutes = "0" + minutes;

	if (hours == 0)
		hours = 12;

	if (hours > 12)
		return (hours-12) + ":" + minutes + " PM";
	else
		return hours + ":" + minutes + " AM";
}

/*
	Accepts weather forecast data in JSON format and returns the temperature in Fahrenheit
*/

function getSetTemp (data) {
	return Math.round(data.currently.temperature);
}

/*
	No parameters; Returns random index to be used in array containing "No" words
*/

function nope () {
	return Math.floor(Math.random () * no.length);
}

/*
	No parameters; Returns random index to be used in array containing recommendations
*/

function recommend () {
	return Math.floor(Math.random () * recommendation.length);
}

var icons = ["cloudy.png", "sunny.png","partlycloudy.png", "storm.png", "rain.png", "snow.png", "night.png"];
var no = ["Nah.", "No.", "Probably not.", "Naw.", "You Crazy? No.", "Nope.", "Definitely Not."];

var recommendation = [
	"Why go today when you can go next time?",
	"Violent delights have violent ends. It's best to avoid them.",
	"Wouldn't you rather sleep?",
	"That's such a far walk...",
	"Think of all the games you'll be missing out on.",
	"Not in this weather.",
	"Just take a day off. You deserve it.",
	"Class is a social construct. Stop conforming.",
	"You can just teach yourself everything you need to know from your bed."
];

var temperature = 0;

/*
	Accepts two parameters: latitude and longitude of user's location
	Displays corresponding data and exits on completion
*/

function callAPI (latitude, longitude) {

	var url = "https://crossorigin.me/https://api.darksky.net/forecast/816d2d6f6ef2679115f69db09a691c14/" + latitude + "," + longitude;

	$.getJSON(url, function(data) {

		$("#time").text (getSetTime());
		$("#showNo").text (no[nope()]);
		$("#recommend").text (recommendation[recommend()]);

		$("#temp").text (getSetTemp(data) + "\xB0 F");
		temperature = getSetTemp(data);

		switch (data.currently.icon)
		{
			case "clear-day":
				$("#image").html('');
				break;
			case "clear-night":
			case "partly-cloudy-night":
				$("#image").html('');
				break;
			case "cloudy":
			case "wind":
			case "fog":
				$("#image").html('');
				break;
			case "partly-cloudy-day":
				$("#image").html('');
				break;
			case "rain":
				$("#image").html('');
				break;
			case "snow":
			case "sleet":
				$("#image").html('');
				break;
			default: // Thunderstorm, tornado, hail will be implemented later by API
				$("#image").html('');
				break;
		}
	});
}

var stat = "f"; // Keeps track of whether last temperature reported was Celsius, "c", or Fahrenheit, "f"

$(document).ready(function (){
	getLocation();

	$("#temp").on("click", function(){
		var celsius = Math.round((temperature - 32) / 1.8);
		var fahrenheit = Math.round((celsius * 1.8) + 32);

		if (stat == "f"){
			$("#temp").text (celsius + "\xB0 C");
			stat = "c";
		}
		else {
			$("#temp").text (fahrenheit + "\xB0 F");
			stat = "f";
		}
	});
});


text:
/*
 *
 */

package jahirfiquitiva.iconshowcase.utilities;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;

/**
 * This Class was created by Patrick J
 * on 07.01.16. For more Details and Licensing
 * have a look at the README.md
 */

public final class PermissionUtils {

    public static final int PERMISSION_REQUEST_CODE = 42;
    public static String folderName;
    private static String VIEWER_ACTIVITY_ACTION;
    private static OnPermissionResultListener onPermissionResultListener;

    public interface OnPermissionResultListener {
        void onStoragePermissionGranted();
    }

    public static boolean canAccessStorage(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }else{
            return true;
        }
    }

    public static void requestStoragePermission(Activity activity) {
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }

    public static void requestStoragePermission(Activity activity, OnPermissionResultListener permissionResultListener) {
        onPermissionResultListener = permissionResultListener;
        requestStoragePermission(activity);
    }

    public static void requestStoragePermission(Activity activity, OnPermissionResultListener permissionResultListener, String folderName) {
        PermissionUtils.folderName = folderName;
        onPermissionResultListener = permissionResultListener;
        requestStoragePermission(activity);
    }

    public static OnPermissionResultListener permissionReceived() {
        return onPermissionResultListener;
    }

    public static void setViewerActivityAction(String viewerActivityAction) {
        VIEWER_ACTIVITY_ACTION = viewerActivityAction;
    }

    public static String getViewerActivityAction() {
        return VIEWER_ACTIVITY_ACTION;
    }
}


text:
import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Route.extend(AuthenticatedRouteMixin, {
  beforeModel() {
    this.get('authManager').logout();
    this.transitionTo('index');
  }
});


text:
package de.hbrs.aspgen.generator.dao;

import java.util.Map;

import de.hbrs.aspgen.api.generator.ExtendClassWithMethods;
import de.hbrs.aspgen.api.generator.MethodForClass;
import de.hbrs.aspgen.api.generator.MethodForClassGenerator;

public class DeleteableDaoGenerator implements MethodForClassGenerator {

    @Override
    public String getName() {
        return DeleteableDao.class.getName();
    }

    @Override
    public void extendJavaClass(final ExtendClassWithMethods methodBuilder,
            final Map<String, String> properties) {
        final String className = properties.get("entity").replace(".class", "");
        final String firstCharLowerCase = className.substring(0, 1).toLowerCase() + className.substring(1);
        final MethodForClass methodForClass = methodBuilder.appendNewMethod("Save");
        methodForClass.setMethodDeclaration("public void delete" + className + "(" + className + " " + firstCharLowerCase + ")");
        methodForClass.addLine("getHibernateTemplate().delete(" + firstCharLowerCase + ");");

        methodForClass.addAnnotation("@Transactional(readOnly = false)");
    }

}


text:
var logfmt = require('../logfmt'),
    assert = require('assert');

var OutStream = require('./outstream');

suite('new logfmt', function() {
  test("returns an isolated logfmt object", function(){
    var logfmt2 = new logfmt;
    logfmt2.stream = new OutStream;

    var logfmt3 = new logfmt;
    logfmt3.stream = new OutStream;

    var data = {foo: 'bar', a: 14}
    logfmt2.log(data);
    assert.equal("foo=bar a=14\n", logfmt2.stream.logline)
    assert.equal("", logfmt3.stream.logline)

    logfmt2.log({foo: 'bar'})
    logfmt3.log(data);
    assert.equal("foo=bar\n", logfmt2.stream.logline)
    assert.equal("foo=bar a=14\n", logfmt3.stream.logline)
  })

  test('constructor accepts a stream', function(){
    stream = new OutStream;
    var logfmt2 = new logfmt(stream);
    var data = {foo: 'bar', a: 14}
    logfmt2.log(data);
    assert.equal("foo=bar a=14\n", stream.logline)
  })
})


text:
from PyObjCTools.TestSupport import *
from AppKit import *

try:
    unicode
except NameError:
    unicode = str

class TestNSPrintInfo (TestCase):
    def testConstants(self):
        self.assertEqual(NSPortraitOrientation, 0)
        self.assertEqual(NSLandscapeOrientation, 1)

        self.assertEqual(NSAutoPagination, 0)
        self.assertEqual(NSFitPagination, 1)
        self.assertEqual(NSClipPagination, 2)

        self.assertIsInstance(NSPrintSpoolJob, unicode)
        self.assertIsInstance(NSPrintPreviewJob, unicode)
        self.assertIsInstance(NSPrintSaveJob, unicode)
        self.assertIsInstance(NSPrintCancelJob, unicode)
        self.assertIsInstance(NSPrintPaperName, unicode)
        self.assertIsInstance(NSPrintPaperSize, unicode)
        self.assertIsInstance(NSPrintOrientation, unicode)
        self.assertIsInstance(NSPrintScalingFactor, unicode)
        self.assertIsInstance(NSPrintLeftMargin, unicode)
        self.assertIsInstance(NSPrintRightMargin, unicode)
        self.assertIsInstance(NSPrintTopMargin, unicode)
        self.assertIsInstance(NSPrintBottomMargin, unicode)
        self.assertIsInstance(NSPrintHorizontallyCentered, unicode)
        self.assertIsInstance(NSPrintVerticallyCentered, unicode)
        self.assertIsInstance(NSPrintHorizontalPagination, unicode)
        self.assertIsInstance(NSPrintVerticalPagination, unicode)
        self.assertIsInstance(NSPrintPrinter, unicode)
        self.assertIsInstance(NSPrintCopies, unicode)
        self.assertIsInstance(NSPrintAllPages, unicode)
        self.assertIsInstance(NSPrintFirstPage, unicode)
        self.assertIsInstance(NSPrintLastPage, unicode)
        self.assertIsInstance(NSPrintMustCollate, unicode)
        self.assertIsInstance(NSPrintReversePageOrder, unicode)
        self.assertIsInstance(NSPrintJobDisposition, unicode)
        self.assertIsInstance(NSPrintSavePath, unicode)
        self.assertIsInstance(NSPrintPagesAcross, unicode)
        self.assertIsInstance(NSPrintPagesDown, unicode)
        self.assertIsInstance(NSPrintTime, unicode)
        self.assertIsInstance(NSPrintDetailedErrorReporting, unicode)
        self.assertIsInstance(NSPrintFaxNumber, unicode)
        self.assertIsInstance(NSPrintPrinterName, unicode)
        self.assertIsInstance(NSPrintHeaderAndFooter, unicode)

        self.assertIsInstance(NSPrintFormName, unicode)
        self.assertIsInstance(NSPrintJobFeatures, unicode)
        self.assertIsInstance(NSPrintManualFeed, unicode)
        self.assertIsInstance(NSPrintPagesPerSheet, unicode)
        self.assertIsInstance(NSPrintPaperFeed, unicode)
        self.assertIsInstance(NSPrintFaxCoverSheetName, unicode)
        self.assertIsInstance(NSPrintFaxHighResolution, unicode)
        self.assertIsInstance(NSPrintFaxModem, unicode)
        self.assertIsInstance(NSPrintFaxReceiverNames, unicode)
        self.assertIsInstance(NSPrintFaxReceiverNumbers, unicode)
        self.assertIsInstance(NSPrintFaxReturnReceipt, unicode)
        self.assertIsInstance(NSPrintFaxSendTime, unicode)
        self.assertIsInstance(NSPrintFaxTrimPageEnds, unicode)
        self.assertIsInstance(NSPrintFaxUseCoverSheet, unicode)
        self.assertIsInstance(NSPrintFaxJob, unicode)

    def testMethods(self):
        self.assertResultIsBOOL(NSPrintInfo.isHorizontallyCentered)
        self.assertResultIsBOOL(NSPrintInfo.isVerticallyCentered)
        self.assertArgIsBOOL(NSPrintInfo.setHorizontallyCentered_, 0)
        self.assertArgIsBOOL(NSPrintInfo.setVerticallyCentered_, 0)

    @min_os_level('10.6')
    def testConstants10_6(self):
        self.assertIsInstance(NSPrintSelectionOnly, unicode)
        self.assertIsInstance(NSPrintJobSavingURL, unicode)
        self.assertIsInstance(NSPrintJobSavingFileNameExtensionHidden, unicode)

    @min_os_level('10.6')
    def testMethods10_6(self):
        self.assertResultIsBOOL(NSPrintInfo.isSelectionOnly)
        self.assertArgIsBOOL(NSPrintInfo.setSelectionOnly_, 0)

if __name__ == "__main__":
    main()


text:
namespace Kalango
{
    partial class MenuConfigs
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.btnLista = new System.Windows.Forms.Button();
            this.btnCadastrar = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Segoe UI", 36F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.ForeColor = System.Drawing.Color.White;
            this.label1.Location = new System.Drawing.Point(185, 74);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(355, 65);
            this.label1.TabIndex = 0;
            this.label1.Text = "Config. Sistema";
            //
            // label2
            //
            this.label2.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Segoe UI", 16F);
            this.label2.ForeColor = System.Drawing.Color.White;
            this.label2.Location = new System.Drawing.Point(124, 191);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 30);
            this.label2.TabIndex = 1;
            this.label2.Text = "Geral";
            //
            // btnLista
            //
            this.btnLista.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.btnLista.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(53)))), ((int)(((byte)(106)))));
            this.btnLista.BackgroundImage = global::Kalango.Properties.Resources.relatorio_2;
            this.btnLista.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.btnLista.FlatAppearance.BorderSize = 0;
            this.btnLista.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnLista.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnLista.ForeColor = System.Drawing.Color.White;
            this.btnLista.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
            this.btnLista.Location = new System.Drawing.Point(419, 287);
            this.btnLista.Margin = new System.Windows.Forms.Padding(20);
            this.btnLista.Name = "btnLista";
            this.btnLista.Padding = new System.Windows.Forms.Padding(5);
            this.btnLista.Size = new System.Drawing.Size(252, 139);
            this.btnLista.TabIndex = 13;
            this.btnLista.Text = "Lista de Usuários";
            this.btnLista.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
            this.btnLista.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
            this.btnLista.UseVisualStyleBackColor = false;
            this.btnLista.Click += new System.EventHandler(this.btnLista_Click);
            //
            // btnCadastrar
            //
            this.btnCadastrar.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.btnCadastrar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(106)))), ((int)(((byte)(0)))), ((int)(((byte)(255)))));
            this.btnCadastrar.BackgroundImage = global::Kalango.Properties.Resources.user_2;
            this.btnCadastrar.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.btnCadastrar.FlatAppearance.BorderSize = 0;
            this.btnCadastrar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnCadastrar.Font = new System.Drawing.Font("Segoe UI", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnCadastrar.ForeColor = System.Drawing.Color.White;
            this.btnCadastrar.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
            this.btnCadastrar.Location = new System.Drawing.Point(127, 287);
            this.btnCadastrar.Margin = new System.Windows.Forms.Padding(20);
            this.btnCadastrar.Name = "btnCadastrar";
            this.btnCadastrar.Padding = new System.Windows.Forms.Padding(5);
            this.btnCadastrar.Size = new System.Drawing.Size(252, 139);
            this.btnCadastrar.TabIndex = 10;
            this.btnCadastrar.Text = "Cadastrar Usuários";
            this.btnCadastrar.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
            this.btnCadastrar.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
            this.btnCadastrar.UseVisualStyleBackColor = false;
            this.btnCadastrar.Click += new System.EventHandler(this.btnCadastrar_Click);
            //
            // MenuConfigs
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(120)))), ((int)(((byte)(170)))), ((int)(((byte)(28)))));
            this.ClientSize = new System.Drawing.Size(1356, 764);
            this.ControlBox = false;
            this.Controls.Add(this.btnLista);
            this.Controls.Add(this.btnCadastrar);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.MinimumSize = new System.Drawing.Size(1182, 630);
            this.Name = "MenuConfigs";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Menu de cadastros";
            this.Load += new System.EventHandler(this.MenuConfigs_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button btnCadastrar;
        private System.Windows.Forms.Button btnLista;
    }
}


text:
package com.rarepebble.colorpicker;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;

public class HueSatView extends SquareView implements ColorObserver {

	private final Paint borderPaint;
	private final Paint pointerPaint;
	private final Path pointerPath;
	private final Path borderPath;
	private final Rect viewRect = new Rect();
	private int w;
	private int h;

	// Bitmap is generated once and shared across instances.
	private static Bitmap bitmap;

	private final PointF pointer = new PointF();
	private ObservableColor observableColor = new ObservableColor(0);

	public HueSatView(Context context) {
		this(context, null);
	}

	public HueSatView(Context context, AttributeSet attrs) {
		super(context, attrs);

		borderPaint = Resources.makeLinePaint(context);
		pointerPaint = Resources.makeLinePaint(context);
		pointerPaint.setColor(0xff000000);
		pointerPath = Resources.makePointerPath(context);
		borderPath = new Path();
		if (bitmap == null) {
			bitmap = makeBitmap(optimalBitmapSize());
		}

		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			// Need clipPath() and setLayerType()...
			throw new UnsupportedOperationException("Android API 10 and below is not supported.");
		}
		else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
			// clipPath() is only supported on a software layer.
			setLayerType(LAYER_TYPE_SOFTWARE, null);
		}
	}

	private int optimalBitmapSize() {
		final int scale = 2;
		final int maxBitmapSize = 128;
		final DisplayMetrics dm = getResources().getDisplayMetrics();
		return Math.min(maxBitmapSize, Math.min(dm.widthPixels, dm.heightPixels) / scale);
	}

	public void observeColor(ObservableColor observableColor) {
		this.observableColor = observableColor;
		observableColor.addObserver(this);
	}

	@Override
	public void updateColor(ObservableColor observableColor) {
		setPointer(pointer, observableColor.getHue(), observableColor.getSat(), w);
		optimisePointerColor();
		invalidate();
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		this.w = w;
		this.h = h;
		viewRect.set(0, 0, w, h);

		float inset = borderPaint.getStrokeWidth() / 2;
		makeBorderPath(borderPath, w, h, inset);

		// Sets pointer position
		updateColor(observableColor);
	}

	private static void makeBorderPath(Path borderPath, int w, int h, float inset) {
		w -= inset;
		h -= inset;
		borderPath.reset();
		borderPath.moveTo(w, inset);
		borderPath.lineTo(w, h);
		borderPath.lineTo(inset, h);
		borderPath.addArc(new RectF(inset, inset, 2 * w, 2 * h), 180, 270);
		borderPath.close();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getActionMasked();
		switch (action) {
			case MotionEvent.ACTION_DOWN:
				boolean withinPicker = clamp(pointer, event.getX(), event.getY(), true);
				if (withinPicker) update();
				return withinPicker;
			case MotionEvent.ACTION_MOVE:
				clamp(pointer, event.getX(), event.getY(), false);
				update();
				getParent().requestDisallowInterceptTouchEvent(true);
				return true;
		}
		return super.onTouchEvent(event);
	}

	private void update() {
		observableColor.updateHueSat(
				hueForPos(pointer.x, pointer.y, w),
				satForPos(pointer.x, pointer.y, w),
				this);
		optimisePointerColor();
		invalidate();
	}

	private boolean clamp(PointF pointer, float x, float y, boolean rejectOutside) {
		x = Math.min(x, w);
		y = Math.min(y, h);
		final float dx = w - x;
		final float dy = h - y;
		final float r = (float)Math.sqrt(dx * dx + dy * dy);
		boolean outside = r > w;
		if (!outside || !rejectOutside) {
			if (outside) {
				x = w - dx * w / r;
				y = w - dy * w / r;
			}
			pointer.set(x, y);
		}
		return !outside;
	}

	private void optimisePointerColor() {
		pointerPaint.setColor(
				observableColor.getLightnessWithValue(1) > 0.5
				? 0xff000000 : 0xffffffff);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		canvas.save();

		canvas.clipPath(borderPath);
		canvas.drawBitmap(bitmap, null, viewRect, null);
		canvas.translate(pointer.x, pointer.y);
		canvas.drawPath(pointerPath, pointerPaint);

		canvas.restore();

		canvas.drawPath(borderPath, borderPaint);
	}

	private static Bitmap makeBitmap(int radiusPx) {
		int[] colors = new int[radiusPx * radiusPx];
		float[] hsv = new float[]{0f, 0f, 1f};
		for (int y = 0; y < radiusPx; ++y) {
			for (int x = 0; x < radiusPx; ++x) {
				final int i = x + y * radiusPx;
				final float sat = satForPos(x, y, radiusPx);
				final float arcBleed = 2f / radiusPx; // extend curved edge pixels just outside clip area.
				if (sat <= 1 + arcBleed) {
					hsv[0] = hueForPos(x, y, radiusPx);
					hsv[1] = sat;
					colors[i] = Color.HSVToColor(0xff, hsv);
				}
			}
		}
		return Bitmap.createBitmap(colors, radiusPx, radiusPx, Bitmap.Config.ARGB_8888);
	}

	private static float hueForPos(float x, float y, float radiusPx) {
		final double r = radiusPx - 1; // gives values 0...1 inclusive
		final double dx = (r - x) / r;
		final double dy = (r - y) / r;
		final double angle = Math.atan2(dy, dx);
		final double hue = 360 * angle / (Math.PI / 2);
		return (float)hue;
	}

	private static float satForPos(float x, float y, float radiusPx) {
		final double r = radiusPx - 1; // gives values 0...1 inclusive
		final double dx = (r - x) / r;
		final double dy = (r - y) / r;
		final double sat = dx * dx + dy * dy; // leave it squared -- exaggerates pale colors
		return (float)sat;
	}

	private static void setPointer(PointF pointer, float hue, float sat, float radiusPx) {
		final float r = radiusPx - 1; // for values 0...1 inclusive
		final double distance = r * Math.sqrt(sat);
		final double angle = hue / 360 * Math.PI / 2;
		final double dx = distance * Math.cos(angle);
		final double dy = distance * Math.sin(angle);
		pointer.set(r - (float)dx, r - (float)dy);
	}
}


text:
import motNav from './mot-nav.html';
export default function(angularModule) {
  angularModule.directive('motNav', function() {
              return {
                  replace: true,
                  restrict: 'E',
                  template: motNav,
                  // scope: {
                  //   logout: '='
                  // },
                  controller: ['$scope', 'viewService', '$auth', function($scope, viewService, $auth) {
                        $scope.view = viewService;
                          $scope.signIn = function() {
                            $scope.needSignIn = true;
                          };
                          $scope.noSignIn = function() {
                            $scope.needSignIn = false;
                          }
                      }]
                  }
          });
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * Date: 28 December 2000
 *
 * SUMMARY: Testing regular expressions containing the ? character.
 * Arose from Bugzilla bug 57572: "RegExp with ? matches incorrectly"
 *
 * See http://bugzilla.mozilla.org/show_bug.cgi?id=57572
 *
 */
//-----------------------------------------------------------------------------
var i = 0;
var BUGNUMBER = 57572;
var summary = 'Testing regular expressions containing "?"';
var cnEmptyString = ''; var cnSingleSpace = ' ';
var status = '';
var statusmessages = new Array();
var pattern = '';
var patterns = new Array();
var string = '';
var strings = new Array();
var actualmatch = '';
var actualmatches = new Array();
var expectedmatch = '';
var expectedmatches = new Array();

status = inSection(1);
pattern = /(\S+)?(.*)/;
string = 'Test this';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'Test', ' this');  //single space in front of 'this'
addThis();

status = inSection(2);
pattern = /(\S+)? ?(.*)/;  //single space between the ? characters
string= 'Test this';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'Test', 'this');  //NO space in front of 'this'
addThis();

status = inSection(3);
pattern = /(\S+)?(.*)/;
string = 'Stupid phrase, with six - (short) words';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'Stupid', ' phrase, with six - (short) words');  //single space in front of 'phrase'
addThis();

status = inSection(4);
pattern = /(\S+)? ?(.*)/;  //single space between the ? characters
string = 'Stupid phrase, with six - (short) words';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'Stupid', 'phrase, with six - (short) words');  //NO space in front of 'phrase'
addThis();

// let's add an extra back-reference this time - three instead of two -
status = inSection(5);
pattern = /(\S+)?( ?)(.*)/;  //single space before second ? character
string = 'Stupid phrase, with six - (short) words';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'Stupid', cnSingleSpace, 'phrase, with six - (short) words');
addThis();

status = inSection(6);
pattern = /^(\S+)?( ?)(B+)$/;  //single space before second ? character
string = 'AAABBB';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'AAABB', cnEmptyString, 'B');
addThis();

status = inSection(7);
pattern = /(\S+)?(!?)(.*)/;
string = 'WOW !!! !!!';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'WOW', cnEmptyString, ' !!! !!!');
addThis();

status = inSection(8);
pattern = /(.+)?(!?)(!+)/;
string = 'WOW !!! !!!';
actualmatch = string.match(pattern);
expectedmatch = Array(string, 'WOW !!! !!', cnEmptyString, '!');
addThis();

//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------

function addThis()
{
  statusmessages[i] = status;
  patterns[i] = pattern;
  strings[i] = string;
  actualmatches[i] = actualmatch;
  expectedmatches[i] = expectedmatch;
  i++;
}

function test()
{
  enterFunc ('test');
  printBugNumber(BUGNUMBER);
  printStatus (summary);
  testRegExp(statusmessages, patterns, strings, actualmatches, expectedmatches);
  exitFunc ('test');
}


text: require "google/apis/gameservices_v1"


text:
<?php

require_once dirname(__FILE__) . "/ClassLoader.php";
Swift_ClassLoader::load("Swift_AddressContainer");

/**
 * Swift_Address is just a lone e-mail address reprsented as an object
 * @package Swift
 * @author Chris Corbyn <chris@w3style.co.uk>
 */
class Swift_Address extends Swift_AddressContainer
{
  /**
   * The e-mail address portion
   * @var string
   */
  var $address = null;
  /**
   * The personal name part
   * @var string
   */
  var $name = null;

  /**
   * Constructor
   * @param string The address portion
   * @param string The personal name, optional
   */
  function Swift_Address($address, $name=null)
  {
    $this->setAddress($address);
    if ($name !== null) $this->setName($name);
  }
  /**
   * Set the email address
   * @param string
   */
  function setAddress($address)
  {
    $this->address = trim((string)$address);
  }
  /**
   * Get the address portion
   * @return string
   */
  function getAddress()
  {
    return $this->address;
  }
  /**
   * Set the personal name
   * @param string
   */
  function setName($name)
  {
    if ($name !== null) $this->name = (string) $name;
    else $this->name = null;
  }
  /**
   * Get personal name portion
   * @return string
   */
  function getName()
  {
    return $this->name;
  }
  /**
   * Build the address the way it should be structured
   * @param boolean If the string will be sent to a SMTP server as an envelope
   * @return string
   */
  function build($smtp=false)
  {
    if ($smtp)
    {
      return "<" . $this->address . ">";
    }
    else
    {
      if (($this->name !== null))
      {
        return $this->name . " <" . $this->address . ">";
      }
      else return $this->address;
    }
  }
}


text:
ACCEPTED

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

#### Published in
Mycologia 25: 63 (1933)

#### Original name
Acanthonitschkea macrobarbata Fitzp., 1933

### Remarks
null


text:
import pygame as pg

WIDTH = 1000
HEIGHT = 800
FPS = 60

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)

# initialize pg and create window
pg.init()
pg.mixer.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("Movement Example")
clock = pg.time.Clock()

class Player(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((64, 64))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)

    def update(self):
        self.vx, self.vy = 0, 0
        keystate = pg.key.get_pressed()
        if keystate[pg.K_UP]:
            self.vy = -5
        if keystate[pg.K_DOWN]:
            self.vy = 5
        if keystate[pg.K_LEFT]:
            self.vx = -2
        if keystate[pg.K_RIGHT]:
            self.vx = 1
        if self.vx != 0 and self.vy != 0:
            self.vx /= 1.414
            self.vy /= 1.414
        self.rect.x += self.vx
        self.rect.y += self.vy

all_sprites = pg.sprite.Group()
player = Player()
all_sprites.add(player)
# Game loop
running = True
while running:
    clock.tick(FPS)
    # Process input (events)
    for event in pg.event.get():
        # check for closing window
        if event.type == pg.QUIT:
            running = False
        if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
            running = False
    # Update
    all_sprites.update()
    # Draw / render
    screen.fill(BLACK)
    all_sprites.draw(screen)
    pg.display.flip()

pg.quit()


text:
using namespace Iop;

CFileIoHandler2100::CFileIoHandler2100(CIoman* ioman)
: CHandler(ioman)
{

}

void CFileIoHandler2100::Invoke(uint32 method, uint32* args, uint32 argsSize, uint32* ret, uint32 retSize, uint8* ram)
{
	switch(method)
	{
	case 0:
		{
			assert(retSize == 4);
			auto command = reinterpret_cast<OPENCOMMAND*>(args);
			*ret = m_ioman->Open(command->flags, command->fileName);
		}
		break;
	case 1:
		{
			assert(retSize == 4);
			auto command = reinterpret_cast<CLOSECOMMAND*>(args);
			*ret = m_ioman->Close(command->fd);
		}
		break;
	case 2:
		{
			assert(retSize == 4);
			auto command = reinterpret_cast<READCOMMAND*>(args);
			*ret = m_ioman->Read(command->fd, command->size, reinterpret_cast<void*>(ram + command->buffer));
		}
		break;
	case 4:
		{
			assert(retSize == 4);
			auto command = reinterpret_cast<SEEKCOMMAND*>(args);
			*ret = m_ioman->Seek(command->fd, command->offset, command->whence);
		}
		break;
	case 255:
		//Not really sure about that...
		if(retSize == 8)
		{
			memcpy(ret, "....rawr", 8);
		}
		else if(retSize == 4)
		{
			memcpy(ret, "....", 4);
		}
		else
		{
			assert(0);
		}
		break;
	default:
		CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called.\r\n", method);
		break;
	}
}


text:
spark-http-stream transfers Spark structured stream over HTTP protocol. Unlike tcp streams, Kafka streams and HDFS file streams, http streams often flow across distributed big data clusters on the Web. This feature is very helpful to build global data processing pipelines across different data centers (scientific research institues, for example) who own seperated data sets.

spark-http-stream provides:
* `HttpStreamServer`: a HTTP server which receives, collects and provides http streams
* `HttpStreamSource`: reads messages from a `HttpStreamServer`, acts as a structured streaming `Source`
* `HttpStreamSink`: sends messages to a `HttpStreamServer` using HTTP-POST commands, acts as a structured streaming `Sink`

also spark-http-stream provides:
* `HttpStreamClient`: a client used to communicate with a `HttpStreamServer`, developped upon HttpClient
* `HttpStreamSourceProvider`: a StreamSourceProvider which creates `HttpStreamSource`
* `HttpStreamSinkProvider`: a StreamSinkProvider which creates `HttpStreamSink`

The simple archtecture of spark-http-stream is shown below:

<img src="https://github.com/bluejoe2008/spark-http-stream/blob/master/docs/arch.png?raw=true" width="600">

## importing spark-http-stream

use maven to import spark-http-stream:

	<dependency>
	    <groupId>org.grapheco</groupId>
	    <artifactId>spark-http-stream</artifactId>
	    <version>0.9.1</version>
	</dependency>

## Starts a standalone HttpStreamServer

`HttpStreamServer` is actually a Jetty server with a `HttpStreamServlet`, it can be started using following code:

	val server = HttpStreamServer.start("/xxxx", 8080);

When `http://localhost:8080/xxxx` is requested, the `HttpStreamServlet` will use an embeded `ActionsHandler` to
parse request message, perform certain action(`fecthSchema`, `fetchStream`, etc), and return response message.

By default, an `NullActionsHandler` is provided. Of coz it can be replaced with a `MemoryBufferAsReceiver`:

	server.withBuffer()
		.addListener(new ObjectArrayPrinter())
		.createTopic[(String, Int, Boolean, Float, Double, Long, Byte)]("topic-1")
		.createTopic[String]("topic-2");

or with a `KafkaAsReceiver`:

	server.withKafka("vm105:9092,vm106:9092,vm107:9092,vm181:9092,vm182:9092")
		.addListener(new ObjectArrayPrinter());

as shown above, several kinds of `ActionsHandler` are defined in spark-http-stream:

* `NullActionsHandler`: does nothing
* `MemoryBufferAsReceiver`: maintains a local memory buffer, stores data sent from producers into buffer, and allows consumers to fetch data in batch
* `KafkaAsReceiver`: forwards all received data to Kafka

Notes that MemoryBufferAsReceiver maintains a server-side message buffer, while KafkaAsReceiver only forwards messages to Kafka cluster.

## HttpStreamSource, HttpStreamSink

The following code shows how to load messages from a `HttpStreamSource`:

	val lines = spark.readStream.format(classOf[HttpStreamSourceProvider].getName)
		.option("httpServletUrl", "http://localhost:8080/xxxx")
		.option("topic", "topic-1");
		.option("includesTimestamp", "true")
		.load();

options:

* `httpServletUrl`: path to the servlet
* `topic`: topic name of messages to be consumed
* `includesTimestamp`: tells if each row in the loaded DataFrame includes a time stamp or not, default value is `false`
* `timestampColumnName`: name assigned to the time stamp column, default value is '\_TIMESTAMP\_'
* `msFetchPeriod`: time interval in milliseconds for message polling, default value is `1`(1ms)

The following code shows how to output messages to a `HttpStreamSink`:

	val query = lines.writeStream
		.format(classOf[HttpStreamSinkProvider].getName)
		.option("httpServletUrl", "http://localhost:8080/xxxx")
		.option("topic", "topic-1")
		.start();

options:

* httpServletUrl: path to the servlet
* topic: topic name of produced messages
* maxPacketSize: max size in bytes of each message packet, if the actual DataFrame is too large, it will be splitted into serveral packets, default value is `10*1024*1024`(10M)

Note that `HttpStreamSource` is only available when the `HttpStreamServer` is equiped with a  `MemoryBufferAsReceiver` (use `withBuffer`, as shown above). If the HttpStreamServer choose Kafka as back-end message system (use `withKafka`), it is wrong to consume data from `HttpStreamSource`, just use `KafkaSource` (see http://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html) instead:

	val df = spark
		.readStream
		.format("kafka")
		.option("kafka.bootstrap.servers", "vm105:9092,vm106:9092,vm107:9092,vm181:9092,vm182:9092")
		.option("subscribe", "topic-1")
		.load()

see https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamSourceSinkTest.scala and https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamKafkaTest.scala to get complete example code.

## Understanding ActionsHandler

as shown in previous section, serveral kinds of `ActionsHandler` are defined in spark-http-stream: `NullActionsHandler`,
`MemoryBufferAsReceiver`, `KafkaAsReceiver`.

users can also customize their own `ActionsHandler` as they will. The interface looks like:

	trait ActionsHandler {
		def listActionHandlerEntries(requestBody: Map[String, Any]): ActionHandlerEntries;
		def destroy();
	}

here `ActionHandlerEntries` is just an alias of `PartialFunction[String, Map[String, Any]]`, which accepts an input argument `action: String`, and returns an output argument `responseBody: Map[String, Any]`. the `listActionHandlerEntries` method is often written as a set of `case` expression:

	override def listActionHandlerEntries(requestBody: Map[String, Any])
		: PartialFunction[String, Map[String, Any]] = {
		case "actionSendStream" ⇒ handleSendStream(requestBody);
	}

the code shown above says: this `ActionsHandler` only handles action `actionSendStream`, in this case, it calls  the method `handleSendStream(requestBody)` to handle request and output its return value as response. If other action is requested, an `UnsupportedActionException` will be thrown by the HttpStreamServer.

`ActionsHandlerFactory` is defined to tell how to create a ActionsHandler with required parameters:

	trait ActionsHandlerFactory {
		def createInstance(params: Params): ActionsHandler;
	}

## Embedding HttpStreamServer in Web application servers

spark-http-stream provides a servlet named `ConfigurableHttpStreamingServlet`, users can configure the servlet in web.xml:

	<servlet>
		<servlet-name>httpStreamServlet</servlet-name>
		<servlet-class>org.apache.spark.sql.execution.streaming.http.ConfigurableHttpStreamServlet</servlet-class>
		<init-param>
			<param-name>handlerFactoryName</param-name>
			<param-value>org.apache.spark.sql.execution.streaming.http.KafkaAsReceiverFactory</param-value>
		</init-param>
		<init-param>
			<param-name>bootstrapServers</param-name>
			<param-value>vm105:9092,vm106:9092,vm107:9092,vm181:9092,vm182:9092</param-value>
		</init-param>
	</servlet>

	<servlet-mapping>
		<servlet-name>httpStreamServlet</servlet-name>
		<url-pattern>/xxxx</url-pattern>
	</servlet-mapping>

As shown above, a servlet of `ConfigurableHttpStreamServlet` is defined with a ActionsHandlerFactory `KafkaAsReceiverFactory`, required parameters for the `ActionsHandlerFactory` (`bootstrapServers`, for example), are defined as a set of `init-param`s.

## Using HttpStreamClient

HttpStreamClient` provides a HTTP client used to communicate with a `HttpStreamServer`. It contains serveral methods:

* `sendDataFrame`: send a `DataFrame` to the server, if the `DataFrame` is too large, it will be splitted into smaller packets
* `sendRows`: send data (as `Array[Row]`) to server
* `fetchSchema`: retrieves schema of certain topic
* `fecthStream`: retrieves data (as 'Array[RowEx]') from server
* `subscribe`: subscribe a topic and retrieves a subscriberId
* `unsubscribe`: unsubscribe

Note that some methods are only available when the server is equipped with correct `ActionsHandler`. As an example, the `KafkaAsReceiver` only handles action `actionSendStream`, that means, if you called `fetchStream` and `sendDataFrame` methods of the HttpStreamClient, it works well. But it will fail and throw an `UnsupportedActionException` when you called `subscribe` method.

```
+---------------+------------------------+-----------------+
|  methods      | MemoryBufferAsReceiver | KafkaAsReceiver |
+---------------+------------------------+-----------------+
| sendDataFrame |             √          |        √        |
+---------------+------------------------+-----------------+
| sendRows      |             √          |        √        |
+---------------+------------------------+-----------------+
| fetchSchema   |             √          |        X        |
+---------------+------------------------+-----------------+
| fecthStream   |             √          |        X        |
+---------------+------------------------+-----------------+
| subscribe     |             √          |        X        |
+---------------+------------------------+-----------------+
| unsubscribe   |             √          |        X        |
+---------------+------------------------+-----------------+
```

## StreamListener

`StreamListener` works when new data is arrived and will be consumed by `ActionsHandler`:

	trait StreamListener {
		def onArrive(topic: String, objects: Array[RowEx]);
	}

Two kinds of `StreamListener`s are provided:

* `StreamCollector`: collects data in a local memory buffer
* `StreamPrinter`: prints data while arriving

an example messages look like this:

	++++++++topic=topic-1++++++++
	RowEx([hello1,1,true,0.1,0.1,1,49],1,0,2017-08-27 20:37:56.432)
	RowEx([hello2,2,false,0.2,0.2,2,50],1,1,2017-08-27 20:37:56.432)
	RowEx([hello3,3,true,0.3,0.3,3,51],1,2,2017-08-27 20:37:56.432)

## Schema, data types, RowEx

spark-http-stream only supports data types which can be recognized by Spark Encoders. These data types includes: `String`, `Boolean`, `Int`, `Long`, `Float`, `Double`, `Byte`, `Array[]`.

A row will be wrapped as a `RowEx` object on receiving. `RowEx` is a data structure richer than `Row`. It contains some members and methods:

* `originalRow`: original row
* `batchId`: batch id passed by Spark
* `offsetInBatch`: offset of this row in current batch
* `withTimestamp()`: returns a `Row` with a timestamp
* `withId()`: returns a `Row` with its id
* `extra()`: returns a triple (batchId, offsetInBatch, timestamp)

Considering an original row has values [hello1,1,true,0.1,0.1,1,49], following code show contents of mentioned structures:

### originalRow:
```
+---------------+-------+--------------+-----------+------------+--------+---------+
| String:hello1 | Int:1 | Boolean:true | Float:0.1 | Double:0.1 | Long:1 | Byte:49 |
+---------------+-------+--------------+-----------+------------+--------+---------+
```

### RowEx:
```
+---------------+-------+--------------+-----++--------+-------+-------------------------------+
| String:hello1 | Int:1 | Boolean:true | ... || Long:1 | Int:0 | Timestamp:2017-08-27 20:37:56 |
+---------------+-------+--------------+-----++--------+-------+-------------------------------+
```

### withTimestamp():
```
+---------------+-------+--------------+-----------+-----+-------------------------------+
| String:hello1 | Int:1 | Boolean:true | Float:0.1 | ... | Timestamp:2017-08-27 20:37:56 |
+---------------+-------+--------------+-----------+-----+-------------------------------+
```

### withId():
```
+---------------+-------+--------------+-----------+------------+--------+---------+------------+
| String:hello1 | Int:1 | Boolean:true | Float:0.1 | Double:0.1 | Long:1 | Byte:49 | String:1-0 |
+---------------+-------+--------------+-----------+------------+--------+---------+------------+
```

### extra():
```
+--------+-------+-------------------------------+
| Long:1 | Int:0 | Timestamp:2017-08-27 20:37:56 |
+--------+-------+-------------------------------+
```

## SerDe

spark-http-stream defines a SerilizerFactory to create a SerializerInstance:

	trait SerializerFactory {
		def getSerializerInstance(serializerName: String): SerializerInstance;
	}

an `SerializerFactory.DEFAULT` object is provided which is able to create two kinds of serializers:

* `java`: creates a JavaSerializer
* `kryo`: creates a KryoSerializer

New kind of Serializer, `json` serializer, for example, is welcome.

By default, `HttpStreamClient` and `HttpStreamServer` uses `kryo` serializer.

## Tests

* `HttpStreamServerClientTest`: tests HttpStreamServer/Client, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamServerClientTest.scala
* `HttpStreamSourceSinkTest`: tests HttpStreamSource and HttpStreamSink, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamSourceSinkTest.scala
* `HttpStreamKafkaTest`: tests HttpStreamSink with Kafka as underlying message reveiver, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamKafkaTest.scala
* `HttpStreamDemo`: a tool helps to test HttpTextStream and HttpTextSink, https://github.com/bluejoe2008/spark-http-stream/blob/master/src/test/scala/HttpStreamDemo.scala

steps to tests HttpStreamDemo:

1. choose machine A, run `HttpStreamDemo start-server-on 8080 /xxxx`, this starts a HTTP server which receives data from machine B
2. choose machine B, run `nc -lk 9999`
3. run `HttpStreamDemo read-from http://machine-a-host:8080/xxxx` on machine B
4. run `HttpStreamDemo write-into http://machine-a-host:8080/xxxx` on machine C
5. type some text in nc, data will be received by HttpStreamSink and then consumed as HttpStreamSource, finally displayed on console

## dependencies

* `kafka-clients-0.10`: used by `KafkaAsReceiver`
* `httpclient-4.5`: HttpStreamClient uses HttpClient project
* `jetty-9.0`: HttpStreamServer is devploped upon Jetty
* `spark-2.1`: spark structued streaming libray


text:
layout: post
unique_id: dolores_park
title: Dolores Park
categories: []
locations:
---

YESTERDAY:
* headed home around 10 pm
* dropped by Safeway
  * apples on sale for some reason
  * picked up a rotisserie chicken
* leftovers and chicken for dinner
* back was hurting when trying to sleep
  * tried sleeping with a back support in place ...

TODAY:
* back felt amazing!
* guitar lesson
* head to SF with Jackie and Bernice
  * Dolores Park!
  * haven't been here in ages
  * tried a vegan pina colada rum ice cream from Byrite
  * tasted terrible
* work in office until 7
* took Caltrain home!
* ramen for dinner
* failed a game of Eldritch Horror

LEARNINGS:
* Caltrain isn't so bad


text:
package com.centurylink.mdw.common.translator.impl;

import com.centurylink.mdw.annotations.Variable;

public class BooleanTranslator extends BaseTranslator {

    public String toString(Object obj){
       return obj.toString();
    }

    public Object toObject(String str){
        return Boolean.valueOf(str);
    }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace Microsoft.Azure.WebJobs.Script.Diagnostics
{
    internal class FileLogger : ILogger
    {
        private readonly FileWriter _fileWriter;
        private readonly Func<bool> _isFileLoggingEnabled;
        private readonly Func<bool> _isPrimary;
        private readonly string _categoryName;
        private readonly LogType _logType;

        public FileLogger(string categoryName, FileWriter fileWriter, Func<bool> isFileLoggingEnabled, Func<bool> isPrimary, LogType logType)
        {
            _fileWriter = fileWriter;
            _isFileLoggingEnabled = isFileLoggingEnabled;
            _isPrimary = isPrimary;
            _categoryName = categoryName;
            _logType = logType;
        }

        public IDisposable BeginScope<TState>(TState state) => DictionaryLoggerScope.Push(state);

        public bool IsEnabled(LogLevel logLevel)
        {
            return _isFileLoggingEnabled();
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            var stateValues = state as IEnumerable<KeyValuePair<string, object>>;
            string formattedMessage = formatter?.Invoke(state, exception);

            // If we don't have a message, there's nothing to log.
            if (string.IsNullOrEmpty(formattedMessage))
            {
                return;
            }

            bool isSystemTrace = Utility.GetStateBoolValue(stateValues, ScriptConstants.LogPropertyIsSystemLogKey);
            if (isSystemTrace)
            {
                // System traces are not logged to files.
                return;
            }

            bool isPrimaryHostTrace = Utility.GetStateBoolValue(stateValues, ScriptConstants.LogPropertyPrimaryHostKey);
            if (isPrimaryHostTrace && !_isPrimary())
            {
                return;
            }

            if (exception != null)
            {
                if (exception is FunctionInvocationException ||
                    exception is AggregateException)
                {
                    // we want to minimize the stack traces for function invocation
                    // failures, so we drill into the very inner exception, which will
                    // be the script error
                    Exception actualException = exception;
                    while (actualException.InnerException != null)
                    {
                        actualException = actualException.InnerException;
                    }

                    formattedMessage += $"{Environment.NewLine}{actualException.Message}";
                }
                else
                {
                    formattedMessage += $"{Environment.NewLine}{exception.ToFormattedString()}";
                }
            }

            formattedMessage = FormatLine(stateValues, logLevel, formattedMessage);
            _fileWriter.AppendLine(formattedMessage);

            // flush errors immediately
            if (logLevel == LogLevel.Error || exception != null)
            {
                _fileWriter.Flush();
            }
        }

        /// <summary>
        /// Format the log line for the current event being traced.
        /// </summary>
        /// <param name="stateValues">The event state.</param>
        /// <param name="level">The event level.</param>
        /// <param name="line">The log line to format.</param>
        /// <returns>The formatted log message.</returns>
        protected virtual string FormatLine(IEnumerable<KeyValuePair<string, object>> stateValues, LogLevel level, string line)
        {
            string tracePrefix = GetLogPrefix(stateValues, level, _logType);
            string timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture);
            string formattedLine = $"{timestamp} [{tracePrefix}] {line.Trim()}";

            return formattedLine;
        }

        internal static string GetLogPrefix(IEnumerable<KeyValuePair<string, object>> stateValues, LogLevel level, LogType logType)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(level.ToString());

            if (logType == LogType.Host)
            {
                var functionName = Utility.GetStateValueOrDefault<string>(stateValues, ScriptConstants.LogPropertyFunctionNameKey);
                if (!string.IsNullOrEmpty(functionName))
                {
                    sb.AppendFormat(",{0}", functionName);
                }
            }

            return sb.ToString();
        }
    }
}