text:
using Neo.VM;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;

[assembly: InternalsVisibleTo("Neo.SmartContract.Framework.UnitTests")]
namespace Neo.Compiler.MSIL.UnitTests.Utils
{
    internal static class NeonTestTool
    {
        /// <summary>
        /// Is not the official script hash, just a unique hash related to the script used for unit test purpose
        /// </summary>
        /// <param name="context">Context</param>
        /// <returns>UInt160</returns>
        public static UInt160 ScriptHash(this ExecutionContext context)
        {
            using (var sha = SHA1.Create())
            {
                return new UInt160(sha.ComputeHash(((byte[])context.Script)));
            }
        }

        public static string Bytes2HexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var d in data)
            {
                sb.Append(d.ToString("x02"));
            }
            return sb.ToString();
        }

        public static byte[] HexString2Bytes(string str)
        {
            if (str.IndexOf("0x") == 0)
                str = str.Substring(2);
            byte[] outd = new byte[str.Length / 2];
            for (var i = 0; i < str.Length / 2; i++)
            {
                outd[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }
            return outd;
        }

        /// <summary>
        /// Build script
        /// </summary>
        /// <param name="filename">File</param>
        /// <param name="releaseMode">Release mode (default=false)</param>
        /// <param name="optimizer">Optimize script (default=false)</param>
        /// <returns>BuildScript</returns>
        public static BuildScript BuildScript(string filename, bool releaseMode = false, bool optimizer = false)
        {
            return BuildScript(new string[] { filename }, releaseMode, optimizer);
        }

        /// <summary>
        /// Build script
        /// </summary>
        /// <param name="filenames">Files</param>
        /// <param name="releaseMode">Release mode (default=false)</param>
        /// <param name="optimizer">Optimize script (default=false)</param>
        /// <returns>BuildScript</returns>
        public static BuildScript BuildScript(string[] filenames, bool releaseMode = false, bool optimizer = false)
        {
            var ext = System.IO.Path.GetExtension(filenames.First());
            var comp = (ext.ToLowerInvariant()) switch
            {
                ".cs" => Compiler.CompileCSFiles(filenames, new string[0] { }, releaseMode),
                ".vb" => Compiler.CompileVBFiles(filenames, new string[0] { }, releaseMode),
                _ => throw new System.Exception("do not support extname = " + ext),
            };

            using (var streamDll = new MemoryStream(comp.Dll))
            using (var streamPdb = new MemoryStream(comp.Pdb))
            {
                var bs = new BuildScript();
                bs.Build(streamDll, streamPdb, optimizer);

                if (bs.Error != null)
                {
                    throw (bs.Error);
                }

                if (bs.Error != null) throw bs.Error;

                return bs;
            }
        }
    }
}


text:
DOCKER_REPO?=frosenberg
IMAGE_NAME?=gcs-module-time-source
IMAGE_TAG?=1.0.3

default: builddocker

buildgo:
	go get github.com/tools/godep
	CGO_ENABLED=0 GOOS=linux godep go build -ldflags "-s" -a -installsuffix cgo -o main *.go

builddocker:
	docker build -t ${DOCKER_REPO}/${IMAGE_NAME}:${IMAGE_TAG} -f ./Dockerfile.build .
	docker run -t ${DOCKER_REPO}/${IMAGE_NAME}:${IMAGE_TAG} /bin/true
	docker cp `docker ps -q -n=1`:/main .
	chmod 755 ./main
	docker build --rm=true --tag=${DOCKER_REPO}/${IMAGE_NAME}:${IMAGE_TAG} -f Dockerfile.static .

run: builddocker
	docker run ${DOCKER_REPO}/${IMAGE_NAME}:${IMAGE_TAG}

push:
	docker push ${DOCKER_REPO}/${IMAGE_NAME}:${IMAGE_TAG}

clean:
	rm main

refresh-deps:
	rm -rf Godeps
	godep save

run-kafka-sample:
	godep go run *.go -v --spring.cloud.stream.bindings.output.destination=topic:output --spring.cloud.stream.binder.kafka.brokers=localhost:9092

.PHONY: clean

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * core
 *
 * @version 1.0
 * @package Flow
 *
 */

namespace Core\Flow\Models;

use  Illuminate\Database\Eloquent\Model  as Eloquent;

/**
 * Flow
 *
 *
 */
class Flow extends Eloquent
{
    protected $table = 'x_flows';

    /** @var status waiting for dispatch */
    const STATUS_DISPATCHING = 1;
    /** @var status waiting for operation */
    const STATUS_PROCESSING = 2;
    /** @var status over */
    const STATUS_OVER = 3;

    public static $status = [
        self::STATUS_DISPATCHING => 'dispatching',
        self::STATUS_PROCESSING => 'processing',
        self::STATUS_OVER => 'over',
    ];
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Roslyn.VisualStudio.IntegrationTests.Basic
{
    [Collection(nameof(SharedIntegrationHostFixture))]
    public class BasicEncapsulateField : AbstractEditorTest
    {
        public BasicEncapsulateField(VisualStudioInstanceFactory instanceFactory)
            : base(instanceFactory, nameof(BasicEncapsulateField))
        {
        }

        protected override string LanguageName => LanguageNames.VisualBasic;

        private const string TestSource = @"
Module Module1
        Public $$name As Integer? = 0
    Sub Main()
        name = 90
    End Sub
End Module";

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateThroughCommand()
        {
            SetUpEditor(TestSource);

            var encapsulateField = VisualStudio.EncapsulateField;
            var dialog = VisualStudio.PreviewChangesDialog;
            encapsulateField.Invoke();
            dialog.VerifyOpen(encapsulateField.DialogName);
            dialog.ClickCancel(encapsulateField.DialogName);
            dialog.VerifyClosed(encapsulateField.DialogName);
            encapsulateField.Invoke();
            dialog.VerifyOpen(encapsulateField.DialogName);
            dialog.ClickApplyAndWaitForFeature(encapsulateField.DialogName, FeatureAttribute.EncapsulateField);
            VisualStudio.Editor.Verify.TextContains(@"    Private _name As Integer? = 0

    Public Property Name As Integer?
        Get
            Return _name
        End Get
        Set(value As Integer?)
            _name = value
        End Set
    End Property");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateThroughLightbulbIncludingReferences()
        {
            SetUpEditor(TestSource);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (and use property)", applyFix: true, blockUntilComplete: true);
            VisualStudio.Editor.Verify.TextContains(@"
Module Module1
    Private _name As Integer? = 0

    Public Property Name As Integer?
        Get
            Return _name
        End Get
        Set(value As Integer?)
            _name = value
        End Set
    End Property

    Sub Main()
        Name = 90
    End Sub
End Module");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public void EncapsulateThroughLightbulbDefinitionsOnly()
        {
            SetUpEditor(TestSource);
            VisualStudio.Editor.InvokeCodeActionList();
            VisualStudio.Editor.Verify.CodeAction("Encapsulate field: 'name' (but still use field)", applyFix: true, blockUntilComplete: true);
            VisualStudio.Editor.Verify.TextContains(@"
Module Module1
    Private _name As Integer? = 0

    Public Property Name As Integer?
        Get
            Return _name
        End Get
        Set(value As Integer?)
            _name = value
        End Set
    End Property

    Sub Main()
        name = 90
    End Sub
End Module");
        }
    }
}


text:
	position: relative;
	width: 100%;
	height: 25%;
	max-height: 400px;
	min-height: 200px;
	margin-bottom: 2px;
}

.sectionPanel .appTitle.anchored{
	margin-top: 5px;
}

#context-map-info{
	display: none;
	position: fixed;
	background-color: #FFD700;
	color: black;
	font-weight: bold;
	padding: 5px;
	border-radius: 5px;
	z-index: 100;
}

#context-map-helper{
	display: none;
}

#context-map:hover #context-map-helper.active{
	display: block;
	background-color: gray;
	color: #FFD700;
	position: absolute;
	left: 50%;
	margin-left: -116px;
	bottom: 20px;
	padding: 5px 10px;
	border-radius: 30px;
	cursor: pointer;
	z-index: 30;
}


text:
// The MIT License (MIT)

// Copyright (c) 2013-2022 Rapptz, ThePhD and contributors

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

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

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef SOL_TABLE_HPP
#define SOL_TABLE_HPP

#include <sol/table_core.hpp>
#include <sol/lua_table.hpp>
#include <sol/usertype.hpp>

namespace sol {
	typedef table_core<false> table;

	template <bool is_global, typename base_type>
	template <typename Class, typename Key>
	usertype<Class> basic_table_core<is_global, base_type>::new_usertype(Key&& key) {
		constant_automagic_enrollments<> enrollments {};
		return this->new_usertype<Class>(std::forward<Key>(key), std::move(enrollments));
	}

	template <bool is_global, typename base_type>
	template <typename Class, typename Key, automagic_flags enrollment_flags>
	usertype<Class> basic_table_core<is_global, base_type>::new_usertype(Key&& key, constant_automagic_enrollments<enrollment_flags> enrollments) {
		int mt_index = u_detail::register_usertype<Class, enrollment_flags>(this->lua_state(), std::move(enrollments));
		usertype<Class> mt(this->lua_state(), -mt_index);
		lua_pop(this->lua_state(), 1);
		set(std::forward<Key>(key), mt);
		return mt;
	}

	template <bool is_global, typename base_type>
	template <typename Class, typename Key>
	usertype<Class> basic_table_core<is_global, base_type>::new_usertype(Key&& key, automagic_enrollments enrollments) {
		int mt_index = u_detail::register_usertype<Class, automagic_flags::all>(this->lua_state(), std::move(enrollments));
		usertype<Class> mt(this->lua_state(), -mt_index);
		lua_pop(this->lua_state(), 1);
		set(std::forward<Key>(key), mt);
		return mt;
	}

	template <bool is_global, typename base_type>
	template <typename Class, typename Key, typename Arg, typename... Args, typename>
	usertype<Class> basic_table_core<is_global, base_type>::new_usertype(Key&& key, Arg&& arg, Args&&... args) {
		constexpr automagic_flags enrollment_flags = meta::any_same_v<no_construction, meta::unqualified_t<Arg>, meta::unqualified_t<Args>...>
		     ? clear_flags(automagic_flags::all, automagic_flags::default_constructor)
		     : automagic_flags::all;
		constant_automagic_enrollments<enrollment_flags> enrollments;
		enrollments.default_constructor = !detail::any_is_constructor_v<Arg, Args...>;
		enrollments.destructor = !detail::any_is_destructor_v<Arg, Args...>;
		usertype<Class> ut = this->new_usertype<Class>(std::forward<Key>(key), std::move(enrollments));
		static_assert(sizeof...(Args) % 2 == static_cast<std::size_t>(!detail::any_is_constructor_v<Arg>),
		     "you must pass an even number of arguments to new_usertype after first passing a constructor");
		if constexpr (detail::any_is_constructor_v<Arg>) {
			ut.set(meta_function::construct, std::forward<Arg>(arg));
			ut.tuple_set(std::make_index_sequence<(sizeof...(Args)) / 2>(), std::forward_as_tuple(std::forward<Args>(args)...));
		}
		else {
			ut.tuple_set(std::make_index_sequence<(sizeof...(Args) + 1) / 2>(), std::forward_as_tuple(std::forward<Arg>(arg), std::forward<Args>(args)...));
		}
		return ut;
	}

	template <typename base_type>
	template <typename Key, typename Value>
	basic_metatable<base_type>& basic_metatable<base_type>::set(Key&& key, Value&& value) {
		this->push();
		lua_State* L = this->lua_state();
		int target = lua_gettop(L);
		optional<u_detail::usertype_storage_base&> maybe_uts = nullopt;
		maybe_uts = u_detail::maybe_get_usertype_storage_base(L, target);
		if (maybe_uts) {
			u_detail::usertype_storage_base& uts = *maybe_uts;
			uts.set(L, std::forward<Key>(key), std::forward<Value>(value));
			return *this;
		}
		else {
			base_t::set(std::forward<Key>(key), std::forward<Value>(value));
		}
		this->pop();
		return *this;
	}

	namespace stack {
		template <>
		struct unqualified_getter<metatable_key_t> {
			static metatable get(lua_State* L, int index = -1) {
				if (lua_getmetatable(L, index) == 0) {
					return metatable(L, ref_index(LUA_REFNIL));
				}
				return metatable(L, -1);
			}
		};
	} // namespace stack
} // namespace sol

#endif // SOL_TABLE_HPP


text:
namespace Microsoft.ApplicationInsights.AspNet.Extensions
{
    using Microsoft.AspNet.Http;
    using System;
    using System.Text;

    /// <summary>
    /// Set of extension methods for Microsoft.AspNet.Http.HttpRequest
    /// </summary>
    public static class HttpRequestExtensions
    {
        /// <summary>
        /// Gets http request Uri from request object
        /// </summary>
        /// <param name="request">request</param>
        /// <returns>A New Uri object representing request Uri</returns>
        public static Uri GetUri(this HttpRequest request)
        {
            if (null == request)
            {
                throw new ArgumentNullException("request");
            }

            if (true == string.IsNullOrWhiteSpace(request.Scheme))
            {
                throw new ArgumentException("Http request Scheme is not specified");
            }

            if (false == request.Host.HasValue)
            {
                throw new ArgumentException("Http request Host is not specified");
            }

            var builder = new StringBuilder();

            builder.Append(request.Scheme)
                .Append("://")
                .Append(request.Host);

            if (true == request.Path.HasValue)
            {
                builder.Append(request.Path.Value);
            }

            if (true == request.QueryString.HasValue)
            {
                builder.Append(request.QueryString);
            }

            return new Uri(builder.ToString());
        }
    }
}


text:
package org.slf4j.impl;

import org.slf4j.ILoggerFactory;

/**
 * The binding of {@link LoggerFactory} class with an actual instance of
 * {@link ILoggerFactory} is performed using information returned by this class.
 *
 * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module.
 * Real implementations are found in  each SLF4J binding project, e.g. slf4j-nop,
 * slf4j-log4j12 etc.
 *
 * @author Ceki Gülcü
 */
public class StaticLoggerBinder {

  /**
   * The unique instance of this class.
   */
  private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();

  /**
   * Return the singleton of this class.
   *
   * @return the StaticLoggerBinder singleton
   */
  public static final StaticLoggerBinder getSingleton() {
    return SINGLETON;
  }

  /**
   * Declare the version of the SLF4J API this implementation is compiled against.
   * The value of this field is usually modified with each release.
   */
  // to avoid constant folding by the compiler, this field must *not* be final
  public static String REQUESTED_API_VERSION = "1.6.99";  // !final

  private StaticLoggerBinder() {
    throw new UnsupportedOperationException("This code should have never made it into slf4j-api.jar");
  }

  public ILoggerFactory getLoggerFactory() {
    throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
  }

  public String getLoggerFactoryClassStr() {
    throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
  }
}


text:
<?php

namespace Google\AdsApi\AdManager\Testing;

/**
 * Provides test data for Ad Manager report downloader tests.
 */
class ReportDownloaderTestProvider
{

    /**
     * Gets the contents of a fake Ad Manager report for testing.
     *
     * @return string
     */
    public static function getFakeReport()
    {
        return file_get_contents(
            dirname(__FILE__)
            . DIRECTORY_SEPARATOR
            . 'inventory-report-A1bc23.csv.gz'
        );
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
V-Index
</TITLE>

<META NAME="date" CONTENT="2010-12-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C G I M P R S T V

V

verify() -
Method in class com.newrelic.pagerduty.PagerDutyAPI

Send a message to the service to verify the serviceKey and serviceURL

      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A C G I M P R S T V


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2015 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/keyboard_accessory"
    android:layout_gravity="start|bottom"
    android:contentDescription="@string/autofill_keyboard_accessory_content_description"
    android:scrollbars="none"
    android:visibility="gone"
    android:orientation="vertical"
    android:layout_height="@dimen/keyboard_accessory_height_with_shadow"
    android:layout_width="match_parent"
    android:paddingEnd="0dp"
    android:clickable="true"
    android:focusable="true">

     <ImageView
        android:id="@+id/accessory_shadow"
        android:layout_width="match_parent"
        android:layout_height="@dimen/toolbar_shadow_height"
        android:src="@drawable/modern_toolbar_shadow"
        android:scaleType="fitXY"
        android:scaleY="-1"
        tools:ignore="ContentDescription" />

    <LinearLayout
        android:id="@+id/accessory_bar_contents"
        android:layout_width="match_parent"
        android:layout_height="@dimen/keyboard_accessory_height"
        android:layout_gravity="start|bottom"
        android:orientation="horizontal"
        android:background="@color/default_bg_color_secondary">

        <include layout="@layout/keyboard_accessory_tabs"
            android:id="@+id/tabs"/>

        <View style="@style/VerticalDivider" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/bar_items_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
    </LinearLayout>

</org.chromium.chrome.browser.keyboard_accessory.bar_component.KeyboardAccessoryView>


text:
import React from "react";
import {
  Container,
  Row,
  Col,
  ListGroup,
  ListGroupItem,
  Card,
  CardBody,
  Button,
} from "helpers/reactstrap";
import {Mutation} from "react-apollo";
import gql from "graphql-tag.macro";
import {FormattedMessage} from "react-intl";
import {Duration} from "luxon";
import {FaSyncAlt} from "react-icons/fa";

function timeHue(time) {
  const redTime = 1000 * 60 * 20; // 20 minutes
  const calcTime = Math.min(redTime, time);
  const hue = (Math.abs(redTime - calcTime) / redTime) * 120;

  return Math.round(hue);
}
function getElapsed(time) {
  return Object.entries(
    Duration.fromObject({
      hours: 0,
      minutes: 0,
      seconds: 0,
      milliseconds: Math.round(time),
    })
      .normalize()
      .toObject(),
  )
    .filter(t => t[0] !== "milliseconds")
    .map(t => t[1].toString().padStart(2, 0))
    .join(":");
}

const tasksSort = (a, b) => {
  if (a.verified > b.verified) return 1;
  if (b.verified > a.verified) return -1;
  if (a.timeElapsedInMS  b.timeElapsedInMS) return -1;
  return 0;
};

const TaskItem = ({
  verifyRequested,
  verified,
  values,
  definition,
  timeElapsedInMS,
  instructions,
  selected,
  setSelectedTask,
}) => (
  <ListGroupItem active={selected} onClick={setSelectedTask}>

        {values.name || definition}
      {" "}
      {verifyRequested && <FaSyncAlt className="fa-spin" />}

    <div
      style={{
        color: `hsl(${timeHue(timeElapsedInMS)},100%,50%)`,
      }}
    >
      Time Elapsed:{getElapsed(timeElapsedInMS)}

{instructions}

  </ListGroupItem>
);

const Tasks = ({tasks, station: {name: stationName, executive}}) => {
  const [selectedTask, setSelectedTask] = React.useState(null);
  const [showDismissed, setShowDismissed] = React.useState(false);
  const myTasks = tasks
    .concat()
    .filter(t => {
      if (t.station !== stationName) return false;
      if (!showDismissed && t.verified) return false;
      return true;
    })
    .sort((a, b) => {
      if (a.verified > b.verified) return 1;
      if (a.verified  b.timeElapsedInMS) return -1;
      if (a.timeElapsedInMS  t.station !== stationName)
      .reduce((acc, t) => {
        acc[t.station] = acc[t.station] ? acc[t.station].concat(t) : [t];
        return acc;
      }, {}),
  )
    .map(([station, tasks]) => [
      station,
      tasks.filter(t => !t.verified).sort(tasksSort),
    ])
    .filter(([station, tasks]) => tasks.length > 0)
    .sort((a, b) => {
      if (a[1].verified > b[1].verified) return 1;
      if (a[1].verified  b[1].timeElapsedInMS) return -1;
      if (a[1].timeElapsedInMS  t.id === selectedTask);
  return (
    <Container className="card-tasks">
      <Row>
        <Col sm={4}>

            <FormattedMessage id="tasks-list" defaultMessage="Tasks List" />

          <ListGroup>
            {executive && (
              <ListGroupItem
                style={{
                  borderBottom: `solid 2px rgba(255,255,255,0.5)`,
                  backgroundColor: "rgba(255,255,255,0.05)",
                }}
              >
                My Tasks
              </ListGroupItem>
            )}
            {myTasks.length === 0 ? (
              <ListGroupItem>No Tasks</ListGroupItem>
            ) : (
              myTasks.map(t => (
                <TaskItem
                  key={t.id}
                  {...t}
                  selected={selectedTask === t.id}
                  setSelectedTask={() => setSelectedTask(t.id)}
                />
              ))
            )}
            {executive && (
              <>
                <ListGroupItem
                  style={{
                    borderTop: `solid 2px rgba(255,255,255,0.5)`,
                    borderBottom: `solid 2px rgba(255,255,255,0.5)`,
                    backgroundColor: "rgba(255,255,255,0.05)",
                  }}
                >
                  Crew Tasks
                </ListGroupItem>

                {crewTasks.length === 0 ? (
                  <ListGroupItem>No Tasks</ListGroupItem>
                ) : (
                  crewTasks.map(([station, tasks]) => (
                    <>
                      <ListGroupItem
                        style={{
                          borderTop: `solid 2px rgba(255,255,255,0.5)`,
                          borderBottom: `solid 1px rgba(255,255,255,0.1)`,
                        }}
                      >
                        {station}
                      </ListGroupItem>
                      {tasks.map(t => (
                        <TaskItem
                          key={t.id}
                          {...t}
                          instructions={""}
                          setSelectedTask={() => {}}
                        />
                      ))}
                    </>
                  ))
                )}
              </>
            )}
          </ListGroup>
          {showDismissed ? (
            <Button block onClick={() => setShowDismissed(false)}>
              Hide Completed
            </Button>
          ) : (
            <Button block onClick={() => setShowDismissed(true)}>
              Show Completed
            </Button>
          )}
        </Col>
        <Col sm={8} style={{display: "flex", flexDirection: "column"}}>

            <FormattedMessage
              id="tasks-instructions"
              defaultMessage="Task Instructions"
            />

          <Card>
            <CardBody style={{whiteSpace: "pre-line"}}>
              {task && task.instructions}
            </CardBody>
          </Card>

            <Mutation
              mutation={gql`
                mutation RequestVerify($id: ID!) {
                  requestTaskVerify(id: $id)
                }
              `}
              variables={{id: task && task.id}}
            >
              {action => (
                <Button
                  size="lg"
                  color="success"
                  disabled={
                    !task || (task && (task.verifyRequested || task.verified))
                  }
                  onClick={action}
                >
                  {task ? (
                    task.verifyRequested ? (
                      <FormattedMessage
                        id="tasks-verify-in-progress"
                        defaultMessage="Verification In Progress..."
                      />
                    ) : task.verified ? (
                      <FormattedMessage
                        id="tasks-completed"
                        defaultMessage="Task Completed"
                      />
                    ) : (
                      <FormattedMessage
                        id="tasks-verify-button"
                        defaultMessage="Verify Task Completion"
                      />
                    )
                  ) : (
                    <FormattedMessage
                      id="tasks-verify-button"
                      defaultMessage="Verify Task Completion"
                    />
                  )}
                </Button>
              )}
            </Mutation>

        </Col>
      </Row>
    </Container>
  );
};

export default Tasks;


text:
all: update_zen build_zen run_benchmarks upload_figures

update_zen:
	rm -rf zenlib/src; \
	git pull zenlib

build_zen:
	cd ../../src; \
	python setup.py build_ext --inplace

run_benchmarks:
	export PYTHONPATH="../../src:${PYTHONPATH}"; \
	python -m zen.benchmark plots

upload:
	scp *.png druths.webfactional.com:~/webapps/rr_static/zen/benchmarks


text:
All development on BookStack is currently done on the `development` branch.
When it's time for a release the `development` branch is merged into release with built & minified CSS & JS then tagged at its version. Here are the current development requirements:

* [Node.js](https://nodejs.org/en/) v16.0+

## Building CSS & JavaScript Assets

This project uses SASS for CSS development and this is built, along with the JavaScript, using a range of npm scripts. The below npm commands can be used to install the dependencies & run the build tasks:

``` bash
# Install NPM Dependencies
npm install

# Build assets for development
npm run build

# Build and minify assets for production
npm run production

# Build for dev (With sourcemaps) and watch for changes
npm run dev
```

BookStack has many integration tests that use Laravel's built-in testing capabilities which makes use of PHPUnit. There is a `mysql_testing` database defined within the app config which is what is used by PHPUnit. This database is set with the database name, username and password all defined as `bookstack-test`. You will have to create that database and that set of credentials before testing.

The testing database will also need migrating and seeding beforehand. This can be done by running `composer refresh-test-database`.

Once done you can run `composer test` in the application root directory to run all tests. Tests can be ran in parallel by running them via `composer t`. This will use Laravel's built-in parallel testing functionality, and attempt to create and seed a database instance for each testing thread. If required these parallel testing instances can be reset, before testing again, by running `composer t-reset`.

## Code Standards

PHP code standards are managed by [using PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer).
Static analysis is in place using [PHPStan](https://phpstan.org/) & [Larastan](https://github.com/nunomaduro/larastan).
The below commands can be used to utilise these tools:

```bash
# Run code linting using PHP_CodeSniffer
composer lint

# As above, but show rule names in output
composer lint -- -s

# Auto-fix formatting & lint issues via PHP_CodeSniffer phpcbf
composer format

# Run static analysis via larastan/phpstan
composer check-static
```

If submitting a PR, formatting as per our project standards would help for clarity but don't worry too much about using/understanding these tools as we can always address issues at a later stage when they're picked up by our automated tools.

## Development using Docker

This repository ships with a Docker Compose configuration intended for development purposes. It'll build a PHP image with all needed extensions installed and start up a MySQL server and a Node image watching the UI assets.

To get started, make sure you meet the following requirements:

- Docker and Docker Compose are installed
- Your user is part of the `docker` group

If all the conditions are met, you can proceed with the following steps:

1. **Copy `.env.example` to `.env`**, change `APP_KEY` to a random 32 char string and set `APP_ENV` to `local`.
2. Make sure **port 8080 is unused** *or else* change `DEV_PORT` to a free port on your host.
3. **Run `chgrp -R docker storage`**. The development container will chown the `storage` directory to the `www-data` user inside the container so BookStack can write to it. You need to change the group to your host's `docker` group here to not lose access to the `storage` directory.
4. **Run `docker-compose up`** and wait until the image is built and all database migrations have been done.
5. You can now login with `admin@admin.com` and `password` as password on `localhost:8080` (or another port if specified).

If needed, You'll be able to run any artisan commands via docker-compose like so:

```bash
docker-compose run app php artisan list
```

The docker-compose setup runs an instance of [MailHog](https://github.com/mailhog/MailHog) and sets environment variables to redirect any BookStack-sent emails to MailHog. You can view this mail via the MailHog web interface on `localhost:8025`. You can change the port MailHog is accessible on by setting a `DEV_MAIL_PORT` environment variable.

### Running tests

After starting the general development Docker, migrate & seed the testing database:

 ```bash
# This only needs to be done once
docker-compose run app php artisan migrate --database=mysql_testing
docker-compose run app php artisan db:seed --class=DummyContentSeeder --database=mysql_testing
```

Once the database has been migrated & seeded, you can run the tests like so:

 ```bash
docker-compose run app php vendor/bin/phpunit
```

### Debugging

The docker-compose setup ships with Xdebug, which you can listen to on port 9090.
NB : For some editors like Visual Studio Code, you might need to map your workspace folder to the /app folder within the docker container for this to work.


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#define SUITE exporter

#include "vast/system/exporter.hpp"

#include "vast/test/test.hpp"

#include "vast/test/fixtures/actor_system_and_events.hpp"

#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/detail/spawn_container_source.hpp"
#include "vast/query_options.hpp"
#include "vast/system/archive.hpp"
#include "vast/system/dummy_consensus.hpp"
#include "vast/system/importer.hpp"
#include "vast/system/index.hpp"
#include "vast/table_slice.hpp"
#include "vast/to_events.hpp"

using namespace caf;
using namespace vast;

using std::string;
using std::chrono_literals::operator""ms;

namespace {

using fixture_base = fixtures::deterministic_actor_system_and_events;

struct fixture : fixture_base {
  fixture() {
    expr = unbox(to<expression>("service == \"dns\" "
                                "&& :addr == 192.168.1.1"));
  }

  ~fixture() {
    for (auto& hdl : {index, importer, exporter})
      self->send_exit(hdl, exit_reason::user_shutdown);
    self->send_exit(archive, exit_reason::user_shutdown);
    self->send_exit(consensus, exit_reason::user_shutdown);
    run();
  }

  void spawn_type_registry() {
    type_registry
      = self->spawn(system::type_registry, directory / "type-registry");
  }

  void spawn_index() {
    index = self->spawn(system::index, directory / "index", 10000, 5, 5, 1);
  }

  void spawn_archive() {
    archive = self->spawn(system::archive, directory / "archive", 1, 1024);
  }

  void spawn_importer() {
    importer = self->spawn(system::importer, directory / "importer", slice_size,
                           archive, consensus, index, type_registry);
  }

  void spawn_consensus() {
    consensus = self->spawn(system::dummy_consensus, directory / "consensus");
  }

  void spawn_exporter(query_options opts) {
    exporter = self->spawn(system::exporter, expr, opts);
  }

  void importer_setup() {
    if (!type_registry)
      spawn_type_registry();
    if (!index)
      spawn_index();
    if (!archive)
      spawn_archive();
    if (!consensus)
      spawn_consensus();
    if (!importer)
      spawn_importer();
    run();
  }

  void exporter_setup(query_options opts) {
    spawn_exporter(opts);
    send(exporter, archive);
    send(exporter, system::index_atom::value, index);
    send(exporter, system::sink_atom::value, self);
    send(exporter, system::run_atom::value);
    send(exporter, system::extract_atom::value);
    run();
  }

  template <class Hdl, class... Ts>
  void send(Hdl hdl, Ts&&... xs) {
    self->send(hdl, std::forward<Ts>(xs)...);
  }

  auto fetch_results() {
    std::vector<event> result;
    bool running = true;
    self->receive_while(running)(
      [&](table_slice_ptr slice) {
        MESSAGE("... got " << slice->rows() << " events");
        to_events(result, *slice);
      },
      error_handler(),
      // Do a one-pass can over the mailbox without waiting for messages.
      after(0ms) >> [&] { running = false; });
    MESSAGE("got " << result.size() << " events in total");
    return result;
  }

  system::type_registry_type type_registry;
  actor index;
  system::archive_type archive;
  actor importer;
  actor exporter;
  system::consensus_type consensus;
  expression expr;
};

} // namespace <anonymous>

FIXTURE_SCOPE(exporter_tests, fixture)

TEST(historical query without importer) {
  MESSAGE("spawn index and archive");
  spawn_index();
  spawn_archive();
  run();
  MESSAGE("ingest conn.log into archive and index");
  vast::detail::spawn_container_source(sys, zeek_conn_log_slices, index,
                                       archive);
  run();
  MESSAGE("spawn exporter for historical query");
  exporter_setup(historical);
  MESSAGE("fetch results");
  auto results = fetch_results();
  REQUIRE_EQUAL(results.size(), 5u);
  std::sort(results.begin(), results.end());
  CHECK_EQUAL(results.front().id(), 10u);
  CHECK_EQUAL(results.front().type().name(), "zeek.conn");
  CHECK_EQUAL(results.back().id(), 19u);
}

TEST(historical query with importer) {
  MESSAGE("prepare importer");
  importer_setup();
  MESSAGE("ingest conn.log via importer");
  // We need to copy zeek_conn_log_slices here, because the importer will assign
  // IDs to the slices it received and we mustn't mess our static test data.
  vast::detail::spawn_container_source(sys, zeek_conn_log_slices, importer);
  run();
  MESSAGE("spawn exporter for historical query");
  exporter_setup(historical);
  MESSAGE("fetch results");
  auto results = fetch_results();
  REQUIRE_EQUAL(results.size(), 5u);
  std::sort(results.begin(), results.end());
  CHECK_EQUAL(results.front().id(), 10u);
  CHECK_EQUAL(results.front().type().name(), "zeek.conn");
  CHECK_EQUAL(results.back().id(), 19u);
}

TEST(continuous query with exporter only) {
  MESSAGE("prepare exporter for continuous query");
  spawn_exporter(continuous);
  send(exporter, system::sink_atom::value, self);
  send(exporter, system::extract_atom::value);
  run();
  MESSAGE("send conn.log directly to exporter");
  vast::detail::spawn_container_source(sys, zeek_conn_log_slices, exporter);
  run();
  MESSAGE("fetch results");
  auto results = fetch_results();
  REQUIRE_EQUAL(results.size(), 5u);
  std::sort(results.begin(), results.end());
  CHECK_EQUAL(results.front().id(), 10u);
  CHECK_EQUAL(results.front().type().name(), "zeek.conn");
  CHECK_EQUAL(results.back().id(), 19u);
}

TEST(continuous query with importer) {
  MESSAGE("prepare importer");
  importer_setup();
  MESSAGE("prepare exporter for continous query");
  exporter_setup(continuous);
  send(importer, system::exporter_atom::value, exporter);
  MESSAGE("ingest conn.log via importer");
  // Again: copy because we musn't mutate static test data.
  vast::detail::spawn_container_source(sys, zeek_conn_log_slices, importer);
  run();
  MESSAGE("fetch results");
  auto results = fetch_results();
  REQUIRE_EQUAL(results.size(), 5u);
  std::sort(results.begin(), results.end());
  CHECK_EQUAL(results.front().id(), 10u);
  CHECK_EQUAL(results.front().type().name(), "zeek.conn");
  CHECK_EQUAL(results.back().id(), 19u);
}

FIXTURE_SCOPE_END()


text:
package org.xlcloud.console.entitlements;

/**
 * Abstract representation of entitlement dictionary.
 * @author "Konrad Król", AMG.net
 */
public abstract class AbstractEntitlementDictionary implements EntitlementDictionary {

    private Long id;

    private String description;

    /**
     * Constructor for the AbstractEntitlementDictionary.
     * Note that, if the parent dictionary is provided, this entitlement is automatically
     * assigned to the parent dictionary:
     *  {@link CompositeEntitlementDictionary#addIncludedEntitlementDictionary(EntitlementDictionary)}
     *
     * @param id id of the entitlement dictionary
     * @param description description
     * @param parent parent dictionary
     */
    public AbstractEntitlementDictionary(Long id, String description, CompositeEntitlementDictionary parent) {
        this.id = id;
        this.description = description;

        if(parent != null) {
            parent.addIncludedEntitlementDictionary(this);
        }
    }

    /**
     * @param id id of the entitlement dictionary
     * @param description description
     */
    public AbstractEntitlementDictionary(Long id, String description) {
        this.id = id;
        this.description = description;
    }

    /** {@inheritDoc} */
    @Override
    public Long getId() {
        return id;
    }

    /** {@inheritDoc} */
    @Override
    public void setId(Long id) {
        this.id = id;
    }

    /** {@inheritDoc} */
    @Override
    public String getDescription() {
        return description;
    }

    /** {@inheritDoc} */
    @Override
    public void setDescription(String description) {
        this.description = description;
    }

}


text:
(function () {
    'use strict';

    angular.module('motech-auth')
        .service('LoginModal', LoginModal);

    LoginModal.$inject = ['$compile', '$rootScope', 'ModalWindow'];
    function LoginModal ($compile, $rootScope, ModalWindow) {
        var modal;
        return {
            open: function () {
                modal = ModalWindow(
                    $compile('<motech-login />')($rootScope),
                    $compile('<span>{{ "security.signInUser" | translate}}</span>')($rootScope),
                    false);
                modal.open();
            },
            close: function(){
                if(modal){
                    modal.close();
                    modal = false;
                }
            }
        };
    }

})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="LOGVICE\PHPLogger" default="build" basedir=".">
    <property name="basedir" value="${project.basedir}" />
    <property name="vendorBinDir" value="${basedir}/vendor/bin" />
    <property name="source" value="${basedir}/src" />
    <property name="threads" value="4"/>

    <target name="build" depends="clean,try_parallel_tasks,phpunit,phpcb" />

    <target name="clean" description="Clean up and create artifact directories">
        <delete dir="${basedir}/build/code-browser" />
        <delete dir="${basedir}/build/coverage" />
        <delete dir="${basedir}/build/logs" />
        <mkdir dir="${basedir}/build/code-browser" />
        <mkdir dir="${basedir}/build/coverage" />
        <mkdir dir="${basedir}/build/logs" />
    </target>

    <target name="run_parallel_tasks">
        <parallel threadCount="${threads}">
            <phingcall target="tasks_to_try" />
        </parallel>
    </target>

    <target name="run_serial_tasks">
        <phingcall target="tasks_to_try" />
    </target>

    <target name="tasks_to_try">
        <phingcall target="phpmd" />
        <phingcall target="phpcpd" />
        <phingcall target="phploc" />
        <phingcall target="phpcs" />
    </target>

    <!-- # THIS TASK CALL THE ABOVE tasks_to_try and run them in parallel-->
    <target name="try_parallel_tasks" description="Run the phpmd, phpcpd, phpcs, phpdoc and phploc tasks. Checks for parallel support in PHP.">
        <exec command="php -m | grep pcntl" returnProperty="pcntl_enabled"/>
        <if>
            <equals arg1="${pcntl_enabled}" arg2="pcntl" />
            <then>
                <echo message="PCNTL Enabled. Running Taks in parallel with ${threads} threads." />
                <phingcall target="run_parallel_tasks"/>
            </then>
            <else>
                <echo message="PCNTL is not enabled. Running task serially." />
                <phingcall target="run_serial_tasks"/>
            </else>
        </if>
    </target>

    <target name="phpmd" description="Perform project mess detection using PHPMD creating a log file">
        <exec executable="${vendorBinDir}/phpmd" logoutput="true">
            <arg path="${source}"/>
            <arg value="xml"/>
            <arg value="${project.basedir}/phpmd.xml"/>
            <arg value="--reportfile"/>
            <arg value="${project.basedir}/build/logs/pmd.xml"/>
        </exec>
    </target>

    <target name="phpcpd" description="Generate pmd-cpd.xml using PHPCPD">
        <exec logoutput="true" command="${vendorBinDir}/phpcpd --log-pmd ${basedir}/build/logs/pmd-cpd.xml ${source}" />
    </target>

    <target name="phploc" description="Generate phploc.csv">
        <exec logoutput="true" command="${vendorBinDir}/phploc --log-csv ${basedir}/build/logs/phploc.csv ${source}" />
    </target>

    <target name="phpcs" description="Generate checkstyle.xml using PHP_CodeSniffer">
        <exec executable="${vendorBinDir}/phpcs" logoutput="true">
            <arg value="--ignore=*/test"/>
            <arg value="--report=checkstyle"/>
            <arg value="--report-file=${basedir}/build/logs/checkstyle.xml"/>
            <arg value="--standard=PSR2"/>
            <arg value="${source}"/>
        </exec>
    </target>

    <target name="phpunit" description="Run unit tests using PHPUnit and generates junit.xml and clover.xml">
        <exec logoutput="true" command="${vendorBinDir}/phpunit --configuration=phpunit.xml" />
    </target>

    <target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser">
        <exec logoutput="true" command="${vendorBinDir}/phpcb --log ${basedir}/build/logs --source ${source} --output ${basedir}/build/code-browser" />
    </target>
</project>


text:
package registry.util;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Created by anzhen on 2016/5/25.
 */
public class PathUtil {

    /**
     * 创建路径
     *
     * @param parent   父节点
     * @param children 孩子节点
     * @return 全路径
     */
    public static String makePath(String parent, String... children) {
        StringBuilder path = new StringBuilder();

        if (parent == null || parent.isEmpty()) {
            parent = "/";
        }
        parent = parent.trim();
        char[] data = parent.toCharArray();
        if (data.length == 0 || data[0] != '/') {
            path.append('/');
        }
        path.append(parent);
        if ((children == null) || (children.length == 0)) {
            return path.toString();
        }
        if (data.length > 0 && data[data.length - 1] != '/') {
            path.append('/');
        }
        String child;
        for (int i = 0; i < children.length; i++) {
            child = children[i];
            if (child == null) {
                continue;
            }
            data = child.trim().toCharArray();
            if (data.length == 0 || (data.length == 1 && data[0] == '/')) {
                continue;
            }
            if (data[0] == '/') {
                path.append(data, 1, data.length - 1);
            } else {
                path.append(data);
            }
            if (data[data.length - 1] != '/') {
                path.append('/');
            }
        }
        if (path.length() > 1 && path.charAt(path.length() - 1) == '/') {
            return path.substring(0, path.length() - 1);
        }

        return path.toString();
    }

    /**
     * 获取子节点
     *
     * @param path 路径
     * @return 子节点
     */
    public static List<String> getNodes(final String path) {
        List<String> result = new ArrayList<String>();
        if (path != null) {
            String token;
            StringTokenizer tokenizer = new StringTokenizer(path, "/");
            while (tokenizer.hasMoreTokens()) {
                token = tokenizer.nextToken();
                if (!token.isEmpty()) {
                    result.add(token);
                }
            }
        }
        return result;
    }

    /**
     * Given a full path, return the node name. i.e. "/one/two/three" will return "three"
     *
     * @param path the path
     * @return the node
     */

    public static String getNodeFromPath(String path) {
        int i = path.lastIndexOf('/');
        if (i < 0) {
            return path;
        }
        if ((i + 1) >= path.length()) {
            return "";
        }
        return path.substring(i + 1);
    }

    /**
     * Validate the provided znode path string
     *
     * @param path znode path string
     * @throws IllegalArgumentException if the path is invalid
     */
    public static void validatePath(String path) throws IllegalArgumentException {
        if (path == null) {
            throw new IllegalArgumentException("Path cannot be null");
        }
        if (path.length() == 0) {
            throw new IllegalArgumentException("Path length must be > 0");
        }
        if (path.charAt(0) != '/') {
            throw new IllegalArgumentException("Path must start with / character");
        }
        if (path.length() == 1) { // done checking - it's the root
            return;
        }
        if (path.charAt(path.length() - 1) == '/') {
            throw new IllegalArgumentException("Path must not end with / character");
        }

        String reason = null;
        char lastc = '/';
        char chars[] = path.toCharArray();
        char c;
        for (int i = 1; i < chars.length; lastc = chars[i], i++) {
            c = chars[i];

            if (c == 0) {
                reason = "null character not allowed @" + i;
                break;
            } else if (c == '/' && lastc == '/') {
                reason = "empty node name specified @" + i;
                break;
            } else if (c == '.' && lastc == '.') {
                if (chars[i - 2] == '/' && ((i + 1 == chars.length) || chars[i + 1] == '/')) {
                    reason = "relative paths not allowed @" + i;
                    break;
                }
            } else if (c == '.') {
                if (chars[i - 1] == '/' && ((i + 1 == chars.length) || chars[i + 1] == '/')) {
                    reason = "relative paths not allowed @" + i;
                    break;
                }
            } else if (c > '\u0000' && c < '\u001f' || c > '\u007f' && c < '\u009F' || c > '\ud800' && c < '\uf8ff'
                    || c > '\ufff0' && c < '\uffff') {
                reason = "invalid charater @" + i;
                break;
            }
        }

        if (reason != null) {
            throw new IllegalArgumentException("Invalid path string \"" + path + "\" caused by " + reason);
        }
    }

    /**
     * 获取父节点路径
     *
     * @param path 路径
     * @return 父节点路径
     */
    public static String getParentFromPath(String path) {
        if (path == null) {
            return null;
        }
        int pos = path.lastIndexOf('/');
        if (pos < 0) {
            return path;
        }
        return path.substring(0, pos);
    }

}


text:
//
//  NSURLRequest+BMCommons.h
//  BMCommons
//
//  Created by Werner Altewischer on 16/02/15.
//  Copyright (c) 2015 BehindMedia. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSURLRequest (BMCommons)

/**
 * Setter for the timeout interval for a request.
 */
- (void)bmSetTimeoutInterval:(NSTimeInterval)timeoutInterval;

/**
 * Setter for the cache policy of a request.
 */
- (void)bmSetCachePolicy:(NSURLRequestCachePolicy)cachePolicy;

/**
 * String containing a digest uniquely identifying the request.
 *
 * The digest is calculated from the HTTP method, URL, header fields and body.
 */
- (NSString *)bmDigest;

/**
 Calculates a digest by including the specified header fields and optionally also includes the request body.
 */
- (NSString *)bmDigestByIncludingHeaders:(nullable NSArray *)includeHeaders includeBody:(BOOL)includeBody;

/**
 Calculates a digest by using all the header fields exluding the specified headers and optionally also including the request body.
 */
- (NSString *)bmDigestByExcludingHeaders:(nullable NSArray *)excludeHeaders includeBody:(BOOL)includeBody;

/**
 Whether or not BMURLCaching based on the BMURLCachingProtocol is enabled for this request.
 */
- (BOOL)isBMURLCachingEnabled;

/**
 Whether or not handling by the BMURLCachingProtocol is enabled for this request.
 */
- (BOOL)isBMURLProtocolEnabled;

/**
 * Returns the raw description for the request including the method, url, headers and body.
 */
- (NSString *)bmRawDescription;

@end

@interface NSMutableURLRequest (BMCommons)

/**
 Enables/disables URL caching based on the BMURLCachingProtocol explicitly for this request, overriding the default behavior.
 */
- (void)setBMURLCachingEnabled:(BOOL)enabled;

/**
 * Enables/disables handling by the BMURLCachingProtocol explicitly for this request, overriding the default behavior.
 */
- (void)setBMURLProtocolEnabled:(BOOL)enabled;

@end

NS_ASSUME_NONNULL_END


text:
package org.kaaproject.kaa.server.common.dao;

import org.kaaproject.kaa.common.dto.admin.SdkProfileDto;

import java.util.List;

/**
 * The interface for SdkProfile service.
 */
public interface SdkProfileService {

  /**
   * Save sdk properties. If sdk properties object has id, then sdk key will
   * be updated, otherwise if there is no other sdk key object with the same
   * token, it will be inserted as a new sdk key object, if there is, nothing
   * will be saved, existent object will be returned
   *
   * @param sdkPropertiesDto the sdk properties dto
   * @return the saved application dto object
   */
  SdkProfileDto saveSdkProfile(SdkProfileDto sdkPropertiesDto);

  /**
   * Returns an SDK profile by its identifier.
   *
   * @param id An SDK profile identifier
   * @return An SDK profile with the given identifier
   */
  SdkProfileDto findSdkProfileById(String id);

  /**
   * Returns an SDK profile by its token.
   *
   * @param token An SDK profile token
   * @return An SDK profile with the given token
   */
  SdkProfileDto findSdkProfileByToken(String token);

  /**
   * Returns a list of SDK profiles for an application with the given
   * identifier.
   *
   * @param applicationId An application identifier
   * @return A list of SDK profiles for an application with the given identifier
   */
  List<SdkProfileDto> findSdkProfilesByApplicationId(String applicationId);

  /**
   * Removes an SDK profile from the database by its identifier.
   *
   * @param id The identifier of the SDK profile to remove
   */
  void removeSdkProfileById(String id);

  /**
   * Checks whether an SDK profile is used by at least one endpoint.
   *
   * @param token The token of the SDK profile to check
   * @return true if the SDK profile is used, false otherwise
   */
  boolean isSdkProfileUsed(String token);
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
in Sydow & Petrak, Annls mycol. 20(3/4): 182 (1922)

#### Original name
Clypeothecium Petr.

### Remarks
null


text:
package org.artificer.shell.core;

import org.artificer.common.visitors.ArtifactVisitorHelper;
import org.artificer.shell.common.AbstractCommand;
import org.artificer.shell.i18n.Messages;
import org.artificer.shell.util.PrintArtifactMetaDataVisitor;
import org.jboss.aesh.cl.CommandDefinition;
import org.jboss.aesh.console.command.CommandResult;
import org.jboss.aesh.console.command.invocation.CommandInvocation;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType;

/**
 * Shows the full meta-data for the artifact currently active in the
 * session/context.
 *
 * @author Brett Meyer
 */
@CommandDefinition(name = "showMetaData",
		description = "The \"showMetaData\" command prints out the meta-data for the artifact currently active in the session.\n")
public class ShowMetaDataCommand extends AbstractCommand {

	@Override
	protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception {
		BaseArtifactType artifact = currentArtifact(commandInvocation);

		// Print out the meta-data information
		commandInvocation.getShell().out().println(Messages.i18n.format("RefreshMetaData.MetaDataFor", artifact.getUuid()));
		commandInvocation.getShell().out().println("--------------");
		PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor(commandInvocation);
		ArtifactVisitorHelper.visitArtifact(visitor, artifact);
        return CommandResult.SUCCESS;
	}

	@Override
	protected String getName() {
		return "showMetaData";
	}

}


text:
package io.s4.comm.test;

import io.s4.comm.core.TaskManager;
import io.s4.comm.file.StaticTaskManager;
import io.s4.comm.util.ConfigParser.Cluster.ClusterType;
import io.s4.comm.zk.ZkTaskSetup;
import io.s4.comm.zk.ZkTaskManager;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class TaskManagerTest {
    public static void main(String[] args) throws Exception {
        // testZkTaskManager(args);
        testStaticTaskManager(args);
        Thread.sleep(10000);
    }

    private static void testStaticTaskManager(String[] args) {
        String address = null;
        address = "localhost:2181";
        TaskManager taskManager = new StaticTaskManager(address,
                                                        "taskmanagerTest",
                                                        ClusterType.S4,
                                                        null);
        Map<String, String> customTaskData = new HashMap<String, String>();
        Object acquireTask = taskManager.acquireTask(customTaskData);
        System.out.println("Acuired Task:" + acquireTask);

    }

    private static void testZkTaskManager(String[] args) {
        System.out.println("Here");
        // "effortfell.greatamerica.corp.yahoo.com:2181"
        String address = args[0];
        address = "localhost:2181";
        String processName = args[1];
        ZkTaskSetup taskSetup = new ZkTaskSetup(address,
                                                      "/taskmanagerTest",
                                                      ClusterType.S4);
        taskSetup.cleanUp();
        taskSetup.setUpTasks("1.0.0.0", new String[] { "task0", "task1" });
        Object obj;
        System.out.println(processName + " Going to Wait for a task");
        HashMap<String, String> map = new HashMap<String, String>();
        ZkTaskManager taskManager = new ZkTaskManager(address,
                                                      "/taskmanagerTest",
                                                      ClusterType.S4);
        obj = taskManager.acquireTask(map);
        System.out.println(processName + "taking up task: " + obj);
        File f = new File("c:/" + obj + ".file");
        f.delete();
        while (true) {
            if (f.exists()) {
                break;
            }
            System.out.println(processName + " processing task: " + obj);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Exiting task:" + obj);
    }
}


text:
package com.thoughtworks.go.listener;

import com.thoughtworks.go.config.AdminsConfig;
import com.thoughtworks.go.config.Role;
import com.thoughtworks.go.config.RolesConfig;
import com.thoughtworks.go.config.SecurityAuthConfig;

import java.util.Arrays;
import java.util.List;

public abstract class SecurityConfigChangeListener extends EntityConfigChangedListener<Object> {
    private final List<Class<?>> securityConfigClasses = Arrays.asList(
            SecurityAuthConfig.class,
            Role.class,
            AdminsConfig.class,
            RolesConfig.class
    );

    @Override
    public boolean shouldCareAbout(Object entity) {
        return securityConfigClasses.stream().anyMatch(aClass -> aClass.isAssignableFrom(entity.getClass()));
    }
}


text:
title: Font optimization
subtitle: Web Font Loader
id: webfontloaderjs
classes: overlay centered_block centered_content
image: palms.jpg
---

    WebFontConfig = {
      google: {
        families: ['Droid Sans']
      },
      loading: function() {},
      active: function() {},
      inactive: function() {},
      fontloading: function(familyName, fvd) {},
      fontactive: function(familyName, fvd) {},
      fontinactive: function(familyName, fvd) {}
    };


text:
const IDENTIFIER_NODE_NAME = '__test__';
const EXPORT_NAMED_DECLARATION = 'ExportNamedDeclaration';

function traverseBackUpToGetExportType(path) {
    if (path.parentPath && path.parentPath.parentPath && path.parentPath.parentPath.parent) {
        return path.parentPath.parentPath.parent.type;
    }

    return null;
}

const StripTestCodeVisitor = {
    Identifier(path) {
        if(path.node.name === IDENTIFIER_NODE_NAME) {
            if(traverseBackUpToGetExportType(path) === EXPORT_NAMED_DECLARATION) {
                path.parentPath.remove();
            }
        }
    }
};

export default function({types: t }) {
  return {
    visitor: StripTestCodeVisitor
  };
}


text:
{% if page.pdf or page.epub %}

 Download

    {% if page.pdf %}

Interactive PDF

    {% endif %}
    {% if page.epub %}

Epub

    {% endif %}

{% if page.pdf %}

{% endif %}
{% if page.epub %}

{% endif %}

{% endif %}


text:
nsq-to-es
=========

NSQ to Elasticsearch transport utility.


text:
/* --------------------------
 * ConnectivityInspector.java
 * --------------------------
 * (C) Copyright 2003-2008, by Barak Naveh and Contributors.
 *
 * Original Author:  Barak Naveh
 * Contributor(s):   John V. Sichi
 *                   Christian Hammer
 *
 * $Id$
 *
 * Changes
 * -------
 * 06-Aug-2003 : Initial revision (BN);
 * 10-Aug-2003 : Adaptation to new event model (BN);
 * 07-Jun-2005 : Made generic (CH);
 *
 */
package org.jgrapht.alg;

import java.util.*;

import org.jgrapht.*;
import org.jgrapht.event.*;
import org.jgrapht.graph.*;
import org.jgrapht.traverse.*;

/**
 * Allows obtaining various connectivity aspects of a graph. The inspected
 * graph is specified at construction time and cannot be modified.
 * Currently, the inspector supports connected components for an undirected
 * graph and weakly connected components for a directed graph. To find strongly
 * connected components, use {@link StrongConnectivityInspector} instead.
 *
 *
The inspector methods work in a lazy fashion: no computation is performed
 * unless immediately necessary. Computation are done once and results and
 * cached within this class for future need.

 *
 *
The inspector is also a {@link org.jgrapht.event.GraphListener}. If added
 * as a listener to the inspected graph, the inspector will amend internal
 * cached results instead of recomputing them. It is efficient when a few
 * modifications are applied to a large graph. If many modifications are
 * expected it will not be efficient due to added overhead on graph update
 * operations. If inspector is added as listener to a graph other than the one
 * it inspects, results are undefined.

 *
 * @author Barak Naveh
 * @author John V. Sichi
 * @since Aug 6, 2003
 */
public class ConnectivityInspector<V, E>
    implements GraphListener<V, E>
{

    List<Set<V>> connectedSets;
    Map<V, Set<V>> vertexToConnectedSet;
    private Graph<V, E> graph;

    /**
     * Creates a connectivity inspector for the specified undirected graph.
     *
     * @param g the graph for which a connectivity inspector to be created.
     */
    public ConnectivityInspector(UndirectedGraph<V, E> g)
    {
        init();
        this.graph = g;
    }

    /**
     * Creates a connectivity inspector for the specified directed graph.
     *
     * @param g the graph for which a connectivity inspector to be created.
     */
    public ConnectivityInspector(DirectedGraph<V, E> g)
    {
        init();
        this.graph = new AsUndirectedGraph<V, E>(g);
    }

    /**
     * Test if the inspected graph is connected. An empty graph is not
     * considered connected.
     *
     * @return true if and only if inspected graph is connected.
     */
    public boolean isGraphConnected()
    {
        return lazyFindConnectedSets().size() == 1;
    }

    /**
     * Returns a set of all vertices that are in the maximally connected
     * component together with the specified vertex. For more on maximally
     * connected component, see
     * http://www.nist.gov/dads/HTML/maximallyConnectedComponent.html.
     *
     * @param vertex the vertex for which the connected set to be returned.
     *
     * @return a set of all vertices that are in the maximally connected
     * component together with the specified vertex.
     */
    public Set<V> connectedSetOf(V vertex)
    {
        Set<V> connectedSet = vertexToConnectedSet.get(vertex);

        if (connectedSet == null) {
            connectedSet = new HashSet<V>();

            BreadthFirstIterator<V, E> i =
                new BreadthFirstIterator<V, E>(graph, vertex);

            while (i.hasNext()) {
                connectedSet.add(i.next());
            }

            vertexToConnectedSet.put(vertex, connectedSet);
        }

        return connectedSet;
    }

    /**
     * Returns a list of Set s, where each set contains all
     * vertices that are in the same maximally connected component. All graph
     * vertices occur in exactly one set. For more on maximally connected
     * component, see
     * http://www.nist.gov/dads/HTML/maximallyConnectedComponent.html.
     *
     * @return Returns a list of Set s, where each set contains all
     * vertices that are in the same maximally connected component.
     */
    public List<Set<V>> connectedSets()
    {
        return lazyFindConnectedSets();
    }

    /**
     * @see GraphListener#edgeAdded(GraphEdgeChangeEvent)
     */
    public void edgeAdded(GraphEdgeChangeEvent<V, E> e)
    {
        init(); // for now invalidate cached results, in the future need to
                // amend them.
    }

    /**
     * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent)
     */
    public void edgeRemoved(GraphEdgeChangeEvent<V, E> e)
    {
        init(); // for now invalidate cached results, in the future need to
                // amend them.
    }

    /**
     * Tests if there is a path from the specified source vertex to the
     * specified target vertices. For a directed graph, direction is ignored for
     * this interpretation of path.
     *
     *
Note: Future versions of this method might not ignore edge directions
     * for directed graphs.

     *
     * @param sourceVertex one end of the path.
     * @param targetVertex another end of the path.
     *
     * @return true if and only if there is a path from the source
     * vertex to the target vertex.
     */
    public boolean pathExists(V sourceVertex, V targetVertex)
    {
        /*
         * TODO: Ignoring edge direction for directed graph may be
         * confusing. For directed graphs, consider Dijkstra's algorithm.
         */
        Set<V> sourceSet = connectedSetOf(sourceVertex);

        return sourceSet.contains(targetVertex);
    }

    /**
     * @see VertexSetListener#vertexAdded(GraphVertexChangeEvent)
     */
    public void vertexAdded(GraphVertexChangeEvent<V> e)
    {
        init(); // for now invalidate cached results, in the future need to
                // amend them.
    }

    /**
     * @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent)
     */
    public void vertexRemoved(GraphVertexChangeEvent<V> e)
    {
        init(); // for now invalidate cached results, in the future need to
                // amend them.
    }

    private void init()
    {
        connectedSets = null;
        vertexToConnectedSet = new HashMap<V, Set<V>>();
    }

    private List<Set<V>> lazyFindConnectedSets()
    {
        if (connectedSets == null) {
            connectedSets = new ArrayList<Set<V>>();

            Set<V> vertexSet = graph.vertexSet();

            if (vertexSet.size() > 0) {
                BreadthFirstIterator<V, E> i =
                    new BreadthFirstIterator<V, E>(graph, null);
                i.addTraversalListener(new MyTraversalListener());

                while (i.hasNext()) {
                    i.next();
                }
            }
        }

        return connectedSets;
    }

    /**
     * A traversal listener that groups all vertices according to to their
     * containing connected set.
     *
     * @author Barak Naveh
     * @since Aug 6, 2003
     */
    private class MyTraversalListener
        extends TraversalListenerAdapter<V, E>
    {
        private Set<V> currentConnectedSet;

        /**
         * @see TraversalListenerAdapter#connectedComponentFinished(ConnectedComponentTraversalEvent)
         */
        public void connectedComponentFinished(
            ConnectedComponentTraversalEvent e)
        {
            connectedSets.add(currentConnectedSet);
        }

        /**
         * @see TraversalListenerAdapter#connectedComponentStarted(ConnectedComponentTraversalEvent)
         */
        public void connectedComponentStarted(
            ConnectedComponentTraversalEvent e)
        {
            currentConnectedSet = new HashSet<V>();
        }

        /**
         * @see TraversalListenerAdapter#vertexTraversed(VertexTraversalEvent)
         */
        public void vertexTraversed(VertexTraversalEvent<V> e)
        {
            V v = e.getVertex();
            currentConnectedSet.add(v);
            vertexToConnectedSet.put(v, currentConnectedSet);
        }
    }
}

// End ConnectivityInspector.java


text:
```zenscript
import mods.aether_legacy.Accessory;Accessory;
```
## Usage

```zenscript
// Possible types are "ring", "pendant", "cape", "shield", "gloves", and "miscellaneous" (case insensitive)
Accessory.registerAccessory(IItemStack input, String type); // Registers an item as an Aether accessory
```


text:
import requests
import uuid

__all__ = ['groups', 'messages']

with open('/Users/Adam/Projects/groupme-stats/core/service/groupme/sensitive.config') as f:
    access_token = f.readline()

base_url = 'https://api.groupme.com/v3'

the_land_id = '21964980'
test_group_id = '22511203'

session = requests.Session()
headers = {'Content-Type': 'application/json'}
session.headers.update(headers)

def generate_uuid():
    return uuid.uuid4()


text:
require './test_helper'

class OcurrenceCounterTest < Test::Unit::TestCase

  def test_array
    fixture = [1,1,1,1,1,3,3,1,3,3,3,5,5]
    array_count = fixture.count_ocurrences

    assert array_count.is_a? Hash
    assert_equal array_count[1], 6
    assert_equal array_count[3], 5
    assert_equal array_count[5], 2
  end

  def test_string
    fixture = "Hello I am a little string and I am very happy counting myself. Because myself is cool and I am myself..."
    word_count = fixture.word_ocurrences(:downcase)

    assert word_count.is_a? Hash
    assert_equal word_count["hello"], 1
    assert_equal word_count["i"], 3
    assert_equal word_count["am"], 3
    assert_equal word_count["a"], 1
    assert_equal word_count["and"], 2
    assert_equal word_count["myself"], 3
  end

  def test_custom_pre_processor
    fixture = "Hello I am a little string and I am very happy counting myself. Because myself is cool and I am myself..."
    word_count = fixture.word_ocurrences(lambda {|str|
        str = str.downcase
        str.length > 4 ? str : nil
    })

    assert word_count.is_a? Hash
    assert_equal word_count.length, 7
  end

end


text:
/*!
	\file WarpSynchronousGenerator.cpp
	\author Andrew Kerr <arkerr@gatech.edu>
	\date 1 April 2010
	\brief detects suitability for kernels to execute in warp-synchronized regions
*/

// C++ includes
#include <iostream>
#include <fstream>

// Boost includes
#include <boost/filesystem.hpp>

// Ocelot includes
#include <ocelot/ir/interface/ControlFlowGraph.h>
#include <traces/interface/TraceConfiguration.h>
#include <traces/interface/WarpSynchronousGenerator.h>
#include <ocelot/trace/interface/TraceEvent.h>
#include <ocelot/executive/interface/EmulatedKernel.h>
#include <ocelot/ir/interface/Module.h>

// Hydrazine includes
#include <hydrazine/interface/debug.h>
#include <hydrazine/interface/string.h>

// Debugging messages
#ifdef REPORT_BASE
#undef REPORT_BASE
#endif

#define REPORT_BASE 0
#define REPORT_KERNEL_INSTRUCTIONS 0

//! if 1, warp size is set to the number of threads in the CTA
#define UNIFORM_CONTROL_FLOW_ONLY 1

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::WarpSynchronousGenerator::WarpCounter::WarpCounter() :
	synchronous(0), events(0)
{
}

void trace::WarpSynchronousGenerator::WarpCounter::event(int warpSize,
	const trace::TraceEvent &event) {

	int warps = (event.active.size() + warpSize - 1) / warpSize;
	for (int warp = 0; warp < warps; warp++) {
		int tid = warp * warpSize;
		int active = 0;
		for (int i = 0; i < warpSize; i++) {
			if (event.active[tid + i]) {
				++active;
			}
		}

		if (active) {
			++events;
			synchronous += (active == warpSize ? 1 : 0); //= (size_t)active;
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::WarpSynchronousGenerator::InstructionCounter::InstructionCounter()
{

}

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::WarpSynchronousGenerator::LSInstructionCounter::LSInstructionCounter():
	wordsLoaded(0), wordsStored(0)
{

}

void trace::WarpSynchronousGenerator::LSInstructionCounter::event(int warpSize,
	const trace::TraceEvent &event) {

	if (event.instruction->addressSpace != ir::PTXInstruction::Global) {
		return;
	}

	ir::PTXU64 mask = (~(4 * warpSize - 1));
	size_t *wordsAccessed = (event.instruction->opcode == ir::PTXInstruction::St ?
		&wordsStored : &wordsLoaded);

	std::map< ir::PTXU64, int > addresses;
	int warps = (event.active.size() + warpSize - 1) / warpSize;
	for (int warp = 0; warp < warps; warp++) {
		int tid = warp * warpSize;
		int active = 0;
		for (int i = 0; i < warpSize; i++) {
			if (event.active[tid + i]) {
				++active;
				++*wordsAccessed;
			}
		}

		if (active) {
			addresses.clear();
			bool aligned = false;
			if (event.memory_size == 4) {
				aligned = true;
				for (int i = 0; i < warpSize; i++) {
					if (event.active[tid+i]) {
						addresses[event.memory_addresses[tid + i] & mask] = (tid + i);
					}
				}
				if (addresses.size() == 1) {
					++synchronous;
				}
			}
			++events;
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::WarpSynchronousGenerator::BranchCounter::BranchCounter()
{

}

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::WarpSynchronousGenerator::TargetCounter::TargetCounter()
{

}

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::WarpSynchronousGenerator::SynchronousInstructionCounter::SynchronousInstructionCounter() {
	// initialize the warp instruction counters

	// add, sub, mul, div, mad
	// f32, s32, u32

	InstructionCounter empty;

	counterVectorizable[ir::PTXInstruction::Add][ir::PTXOperand::f32] = empty;
	counterVectorizable[ir::PTXInstruction::Add][ir::PTXOperand::s32] = empty;
	counterVectorizable[ir::PTXInstruction::Add][ir::PTXOperand::u32] = empty;

	counterVectorizable[ir::PTXInstruction::Sub][ir::PTXOperand::f32] = empty;
	counterVectorizable[ir::PTXInstruction::Sub][ir::PTXOperand::s32] = empty;
	counterVectorizable[ir::PTXInstruction::Sub][ir::PTXOperand::u32] = empty;

	counterVectorizable[ir::PTXInstruction::Mul][ir::PTXOperand::f32] = empty;
	counterVectorizable[ir::PTXInstruction::Mul][ir::PTXOperand::s32] = empty;
	counterVectorizable[ir::PTXInstruction::Mul][ir::PTXOperand::u32] = empty;

	counterVectorizable[ir::PTXInstruction::Mad][ir::PTXOperand::f32] = empty;
	counterVectorizable[ir::PTXInstruction::Mad][ir::PTXOperand::s32] = empty;
	counterVectorizable[ir::PTXInstruction::Mad][ir::PTXOperand::u32] = empty;

	counterVectorizable[ir::PTXInstruction::Div][ir::PTXOperand::f32] = empty;
	counterVectorizable[ir::PTXInstruction::Div][ir::PTXOperand::s32] = empty;
	counterVectorizable[ir::PTXInstruction::Div][ir::PTXOperand::u32] = empty;
}

void trace::WarpSynchronousGenerator::SynchronousInstructionCounter::event(
	int warpSize, const trace::TraceEvent &event) {

	// count specific control flow targets
	std::map< int, TargetCounter >::iterator target_it = counterTargets.find(event.PC);
	if (target_it != counterTargets.end()) {
		target_it->second.event(warpSize, event);
	}

	// handle each specific opcode its own way
	switch (event.instruction->opcode) {
	case ir::PTXInstruction::Bra:
		// handle branches specially
		counterBranches[event.PC].event(warpSize, event);
		break;

	case ir::PTXInstruction::Ld:
	case ir::PTXInstruction::St:
		// handle loads and stores specially
		counterLoadStore.event(warpSize, event);
		break;

	default:
		// record inst
	{
		WarpInstructionCounter::iterator w_it = counterVectorizable.find(event.instruction->opcode);
		if (w_it != counterVectorizable.end()) {
			DataInstructionCounter::iterator inst_counter = w_it->second.find(event.instruction->type);
			if (inst_counter != w_it->second.end()) {
				inst_counter->second.event(warpSize, event);
			}
		}
	}
		break;
	}
}

static void write(std::ostream &out,
	const trace::WarpSynchronousGenerator::SynchronousInstructionCounter &counter) {

	out << "\t\t\"loadStore\": { \"events\": " << counter.counterLoadStore.events
		<< ", \"synchronous\": " << counter.counterLoadStore.synchronous
		<< ", \"accessed\": " << (counter.counterLoadStore.wordsLoaded + counter.counterLoadStore.wordsStored)
		<< " },\n";

	out << "\t\t\"arithmetic\": {\n";

	int someEvents = 0;
	trace::WarpSynchronousGenerator::WarpInstructionCounter::const_iterator warp_it = counter.counterVectorizable.begin();
	for (; warp_it != counter.counterVectorizable.end(); ++warp_it) {
		trace::WarpSynchronousGenerator::DataInstructionCounter::const_iterator inst_it = warp_it->second.begin();
		for (; inst_it != warp_it->second.end(); ++inst_it) {
			if (inst_it->second.events) {
				if (someEvents++) {
					out << ",\n";
				}
				out << "\t\t\t\"" << ir::PTXInstruction::toString(warp_it->first) << "." <<
					ir::PTXOperand::toString(inst_it->first) << "\": { ";
				out << " \"events\": " << inst_it->second.events << ", \"synchronous\": " << inst_it->second.synchronous;
				out << " }";
			}
		}
	}
	out << "\n";

	out << "\t\t},\n";
	out << "\t\t\"branches\": [\n";

	std::map< int, trace::WarpSynchronousGenerator::BranchCounter >::const_iterator bra_it;
	bra_it = counter.counterBranches.begin();
	for (; bra_it != counter.counterBranches.end();) {
		out << "\t\t\t{ \"pc\": " << bra_it->first << ", \"events\": " << bra_it->second.events
			<< ", \"synchronous\": " << bra_it->second.synchronous
			<< ", \"target\": " << bra_it->second.target;
		++bra_it;
		out << " }" << (bra_it != counter.counterBranches.end() ? "," :"") << "\n";
	}
	out << "\t\t],\n";

	out << "\t\t\"targets\": [\n";
	std::map< int, trace::WarpSynchronousGenerator::TargetCounter >::const_iterator targ_it;
	targ_it = counter.counterTargets.begin();
	for (; targ_it != counter.counterTargets.end();) {
		out << "\t\t\t{ \"pc\": " << targ_it->first << ", \"events\": " << targ_it->second.events
			<< ", \"synchronous\": " << targ_it->second.synchronous;
		++targ_it;
		out << " }" << (targ_it != counter.counterTargets.end() ? "," :"") << "\n";
	}
	out << "\t\t]\n";

}

//////////////////////////////////////////////////////////////////////////////////////////////////

unsigned int trace::WarpSynchronousGenerator::_counter = 0;

trace::WarpSynchronousGenerator::WarpSynchronousGenerator() {

	// warp sizes
//	int sizes[] = {2, 4, 8, 16, 32, 0};
	int sizes[] = {4, 0};
	for (int i = 0; sizes[i]; i++) {
		warpSizes.push_back(sizes[i]);
	}
}

trace::WarpSynchronousGenerator::~WarpSynchronousGenerator() {

}

/*!	\brief Initializes the trace generator when a new kernel is
		about to be launched.
	\param kernel The kernel used to initialize the generator
*/
void trace::WarpSynchronousGenerator::initialize(const executive::ExecutableKernel& kernel) {

	const executive::EmulatedKernel & emuKernel =
		static_cast<const executive::EmulatedKernel &>(kernel);

	//
	// initialize kernel header
	//
	_entry.name = kernel.name;
	_entry.module = kernel.module->path();
	_entry.format = TraceGenerator::WarpSynchronousTraceFormat;
	_entry.path = "";
	_entry.header = "";
	_entry.program = "";
	_entry.gridDim = kernel.gridDim();
	_entry.blockDim = kernel.blockDim();
		std::string name = kernel.name;

	// only look for complete uniformity
#if UNIFORM_CONTROL_FLOW_ONLY
	warpSizes.clear();
	warpSizes.push_back(_entry.blockDim.x * _entry.blockDim.y * _entry.blockDim.z);
#endif

	if( name.size() > 20 ) {
		name.resize( 20 );
	}

	std::stringstream stream;
	stream << _entry.format << "_" << trace::WarpSynchronousGenerator::_counter++;

	boost::filesystem::path path( database );
	path = path.parent_path();
	path /= _entry.program + "_" + name + "_" + stream.str() + ".json";
	path = boost::filesystem::system_complete( path );

	_entry.header = path.string();

	//
	// identify all branches and create counters for them
	//
	std::map< int, int > branchPCs;
	std::map< int, std::vector<int> > targetPCs; // map's a target PC to list of branches jumping to it
	if (kernel.ISA == ir::Instruction::Emulated) {
		const executive::EmulatedKernel & emuKernel =
			static_cast<const executive::EmulatedKernel &>(kernel);

		targetPCs[0].push_back(-1);	// first instruction gets a push

		executive::EmulatedKernel::PTXInstructionVector::const_iterator inst_it;

		int pc = 0;
		for (inst_it = emuKernel.instructions.begin(); inst_it != emuKernel.instructions.end();
			++inst_it, ++pc) {
			const ir::PTXInstruction &inst = *inst_it;

			// complete per-instruction analysis
			switch (inst.opcode) {
				case ir::PTXInstruction::Bra:
					branchPCs[pc] = inst.branchTargetInstruction;
					targetPCs[inst.branchTargetInstruction].push_back(pc);
					targetPCs[pc+1].push_back(pc);
					break;

				default:
					break;
			}
		}
	}

	// obtain control flow graph
	controlFlowGraph = emuKernel.cfg();
	branchTargetsToBlock = emuKernel.branchTargetsToBlock;
	for (std::map< int, std::string >::const_iterator it = branchTargetsToBlock.begin();
		it != branchTargetsToBlock.end(); ++it) {
		blockToBranchTarget[it->second] = it->first;
	}

	// for each warp size, initialize counters and create branch records
	warpCounters.clear();
	for (std::vector<int>::const_iterator ws_it = warpSizes.begin(); ws_it != warpSizes.end();
		++ws_it) {
		SynchronousInstructionCounter syncCounter;
		for (std::map<int,int>::const_iterator bra_it = branchPCs.begin();
			bra_it != branchPCs.end(); ++bra_it) {

			BranchCounter braCounter;
			braCounter.target = bra_it->second;
			syncCounter.counterBranches[bra_it->first] = braCounter;
		}
		for (std::map<int, std::vector<int> >::const_iterator targ_it = targetPCs.begin();
			targ_it != targetPCs.end(); ++targ_it) {
			TargetCounter targCounter;

			syncCounter.counterTargets[targ_it->first] = targCounter;
		}
		warpCounters[*ws_it] = syncCounter;
	}
}

/*!
	\brief Called whenever an event takes place.

	\param even The TraceEvent that just occurred
	Note, the const reference 'event' is only valid until event()
	returns
*/
void trace::WarpSynchronousGenerator::event( const trace::TraceEvent& event ) {
	for (std::map< int, SynchronousInstructionCounter >::iterator counter_it = warpCounters.begin();
		counter_it != warpCounters.end(); ++counter_it) {
		counter_it->second.event(counter_it->first, event);
	}
}

/*!	\brief Finalize the trace and dump the results to disk.

	Add a databse entry for the trace as well.
*/
void trace::WarpSynchronousGenerator::finish() {

	report("WarpSynchronousGenerator::finish()");

	// always update database and emit results as JSON
	outputSynchronousStatistics();

	if (TraceConfiguration::Singleton.warpSynchronous.emitHotPaths) {
		// emit DOT files
		for (std::vector<int>::const_iterator ws_it = warpSizes.begin();
			ws_it != warpSizes.end(); ++ws_it) {
			int warpSize = *ws_it;
			report("  outputting hot paths - ws: " << warpSize);
			outputHotPaths(warpSize);
		}
	}
}

void trace::WarpSynchronousGenerator::outputSynchronousStatistics() {

	// update database
	_entry.updateDatabase(database);

	std::ofstream traceLog(_entry.header.c_str());

	//
	// serialize results
	//
	traceLog << "{\n";
	traceLog << "\t\"kernel\": \"" << _entry.name << "\",\n";
	traceLog << "\t\"module\": \"" << _entry.module << "\",\n";
	traceLog << "\t\"threads\": "
		<< _entry.blockDim.x * _entry.blockDim.y * _entry.blockDim.z << ",\n";
	traceLog << "\t\"gridDim\": [" << _entry.gridDim.x << ", " << _entry.gridDim.y << ", "
		<< _entry.gridDim.z << "],\n";
	traceLog << "\t\"blockDim\": [" << _entry.blockDim.x << ", " << _entry.blockDim.y << ", "
		<< _entry.blockDim.z << "],\n";
	traceLog << "\t\"counters\":\n[\n";
	for (std::map< int, SynchronousInstructionCounter >::iterator
		counter_it = warpCounters.begin();
		counter_it != warpCounters.end(); ) {
		traceLog << "\t{\n\t\"warpSize\": " << counter_it->first << ",\n";
		write(traceLog, counter_it->second);
		++counter_it;
		traceLog << "\t}" << (counter_it != warpCounters.end() ? "," : "") << "\n";
	}
	traceLog << "]\n}\n\n";
}

//////////////////////////////////////////////////////////////////////////////////////////////////

/*
			class DotFormatter : public ir::ControlFlowGraph::BasicBlock::DotFormatter {
			public:

				const WarpSynchronousGenerator *traceGenerator;

				static std::string colorToString(unsigned int color);
			public:
				std::string toString(const ir::ControlFlowGraph::BasicBlock *block);
				std::string toString(const ir::ControlFlowGraph::Edge *edge);
			};
// trace::WarpSynchronousGenerator::DotFormatter::
*/

std::string trace::WarpSynchronousGenerator::DotFormatter::colorToString(unsigned int color) {

	unsigned short a = ((color >> 24) & 0x0ff);
	unsigned short r = ((color >> 16) & 0x0ff);
	unsigned short g = ((color >> 8) & 0x0ff);
	unsigned short b = ((color) & 0x0ff);

	return colorToString(r, g, b, a);
}

std::string trace::WarpSynchronousGenerator::DotFormatter::colorToString(
	unsigned int r, unsigned int g, unsigned int b, unsigned int a) {
	std::stringstream ss;

	ss << "#";
	ss << std::setfill('0') << std::setw(2) << std::hex << (r & 0x0ff);
	ss << std::setfill('0') << std::setw(2) << std::hex << (g & 0x0ff);
	ss << std::setfill('0') << std::setw(2) << std::hex << (b & 0x0ff);
//	ss << std::setfill('0') << std::setw(2) << std::hex << (a & 0x0ff);

	return ss.str();
}

std::string trace::WarpSynchronousGenerator::DotFormatter::toString(
	const ir::ControlFlowGraph::BasicBlock *block) {
	std::stringstream ss;

	std::string label = block->label();
	if (blockCounter.find(label) == blockCounter.end()) {
		ss << "[shape=record,label=\"" <<
			hydrazine::toGraphVizParsableLabel(block->label()) << "\"] // no block counter";
		return ss.str();
	}

	size_t events = blockCounter[block->label()].events,
		synchronous = blockCounter[block->label()].synchronous;
	float t = 0.0f;
	double activity = (events ? (double)synchronous / (double)events : 0);

	/*
	// log-scale color intensity based on number of times block has been reached by a warp
	if (events) {
		t = log((float)(events)) / (float)log((float)(maxEvents));
	}
	unsigned int r = (unsigned int)(t * 255.0);
	unsigned int g = 0, b = 0;
	*/
	if (events) {
		t = (float)activity;
		if (t < 0.95) { t = 0.0f; }
	}
	unsigned int r = (unsigned int)(t * 255.0);
	unsigned int g = 0, b = 0;

	ss << "[";
	ss << "fillcolor=\"" << colorToString(r,g,b) << "\",style=filled,";
	ss << "shape=record,label=\"{" << hydrazine::toGraphVizParsableLabel(block->label())
		<< " | events: " << events << " | synchronous: " << synchronous << " | activity: "
		<< activity << "}\"";
	if (t < 0.5) {
		ss << ",fontcolor=\"#aaaaaa\"";
	}
	ss << "]";
	return ss.str();
}

std::string trace::WarpSynchronousGenerator::DotFormatter::toString(
	const ir::ControlFlowGraph::BasicBlock::Edge *edge) {
	std::stringstream out;

	if (edge->type == ir::ControlFlowGraph::BasicBlock::Edge::Dummy) {
		out << "[style=dotted]";
	}
	else {
		// color it blue if the edge is entirely uniform or not
		if (counterEdges.find(edge) != counterEdges.end()) {
			if (counterEdges[edge].synchronous == counterEdges[edge].events) {
				out << "[color=blue,style=bold]";
			}
		}
	}

	return out.str();
}

//////////////////////////////////////////////////////////////////////////////////////////////////

/*!
	\brief emits DOT files for each kernel with blocks colored by hot path for a given warp size
*/
void trace::WarpSynchronousGenerator::outputHotPaths(int warpSize) {
	const SynchronousInstructionCounter & counter = warpCounters[warpSize];

	DotFormatter formatter;
	formatter.warpSize = warpSize;
	formatter.traceGenerator = this;

	std::map< int, TargetCounter >::const_iterator target_it;

	formatter.maxEvents = 0;
	for (target_it = counter.counterTargets.begin(); target_it != counter.counterTargets.end();
		++target_it) {
		//blockColors[branchTargetsToBlock[target_it->first]] = 0;
		if (formatter.maxEvents < target_it->second.events) {
			formatter.maxEvents = target_it->second.events;
		}
		if ( (!formatter.minEvents && target_it->second.events) || (target_it->second.events &&
			target_it->second.events < formatter.minEvents)) {
			formatter.minEvents = target_it->second.events;
		}
	}
	if (formatter.maxEvents) {
		for (target_it = counter.counterTargets.begin(); target_it != counter.counterTargets.end();
			++target_it) {
			//blockColors[branchTargetsToBlock[target_it->first]] = color;
			formatter.blockCounter[ branchTargetsToBlock[target_it->first] ] = target_it->second;
		}
	}

	std::stringstream ss;

	boost::filesystem::path path( database );
	path = path.parent_path();
	path = boost::filesystem::system_complete( path );
	ss << path.string() << "/" << _entry.program << "_" << _entry.name << "_"
		<< _counter << "_ws" << warpSize << "_hotpath.dot";

	std::string filename = ss.str();

	report(" outputHotPaths(ws: " << warpSize << ", filename = " << filename << ")");

	std::ofstream cfgFile(filename.c_str());
	cfgFile << "/*\n";
	cfgFile << "     kernel: " << " kernel-name " << "\n";
	cfgFile << "  warp size: " << warpSize << "\n";
	cfgFile << "*/\n";

	controlFlowGraph->write(cfgFile, formatter);
}

//////////////////////////////////////////////////////////////////////////////////////////////////


text:
#ifndef SEGGER_SEGGER_SYSVIEW_CONF_H_
#define SEGGER_SEGGER_SYSVIEW_CONF_H_

#include <stdint.h>

#define SEGGER_SYSVIEW_GET_TIMESTAMP sysview_get_timestamp
#define SEGGER_SYSVIEW_GET_INTERRUPT_ID sysview_get_interrupt

uint32_t sysview_get_timestamp(void);
uint32_t sysview_get_interrupt(void);

#define SEGGER_SYSVIEW_RTT_BUFFER_SIZE CONFIG_SEGGER_SYSVIEW_RTT_BUFFER_SIZE
#define SEGGER_SYSVIEW_POST_MORTEM_MODE CONFIG_SEGGER_SYSVIEW_POST_MORTEM_MODE

#if defined(CONFIG_SEGGER_SYSVIEW_SECTION_DTCM)
#define SEGGER_SYSVIEW_SECTION	".dtcm_data"
#endif

extern unsigned int zephyr_rtt_irq_lock(void);
extern void zephyr_rtt_irq_unlock(unsigned int key);

/* Lock SystemView (nestable) */
#define SEGGER_SYSVIEW_LOCK()	{					       \
					unsigned int __sysview_irq_key =       \
						zephyr_rtt_irq_lock()

/* Unlock SystemView (nestable) */
#define SEGGER_SYSVIEW_UNLOCK()		zephyr_rtt_irq_unlock(__sysview_irq_key);         \
				}

#endif  /* SEGGER_SEGGER_SYSVIEW_CONF_H_ */


text:
layout: post
title: Finding Bigrams with t-score in Perl
tags: [Text Processing, Natural Language Processing]
use_math: true
comment: true
---
In this post I will tell how we can find bigrams with tscore from an English text. If you are interested to read more on Bigram see the wiki article at [http://en.wikipedia.org/wiki/Bigram](http://en.wikipedia.org/wiki/Bigram).

There is a module called [Lingua::EN::Bigram](http://search.cpan.org/~emorgan/Lingua-EN-Bigram-0.01/lib/Lingua/EN/Bigram.pm) in the [CPAN](http://search.cpan.org/) directory. I know that if you are a Perl NLP man you might have created your own perl code for doing the same. Let it be there. We can see how it can be made possible with the above said module.

To install the module run 'cpan' as root(Assumes that you are connected to Internet). Type 'install Lingua::EN::Bigram' in the cpan terminal and follow the instructions. If the installation is ok then copy and paste below given code to your favourite editor and save it as 'bigram.pl' .

```perl

#!/usr/bin/env perl
use Lingua::EN::Bigram;

$bigram = new Lingua::EN::Bigram;

while (<>) {
    $text = $_;
    $text =~ tr/A-Z/a-z/;
    $text =~ s/\.//g;
    $text =~ s/\,//g;
    $text =~ s/\?//g;
    $text =~ s/\!//g;
    $text =~ s/\://g;
    $text =~ s/\;//g;
    $bigram->text($text);
    $tscore = $bigram->tscore;
    foreach ( sort { $$tscore{$b} <=> $$tscore{$a} } keys %$tscore ) {
        print "$$tscore{$_} \t " . "$_\n";
    }
}

```

To run the program, open terminal and go to the directory where the `bigram.pl` is located. Type `perl bigram.pl <your_textfile>` .

Migrated from my [old blog jaganadhg.freeflux.net](https://web.archive.org/web/20160323193721/http://jaganadhg.freeflux.net/blog)


text:
( function ( $, mw ) {
	QUnit.module( 'mediawiki.errorLogger', QUnit.newMwEnvironment() );

	QUnit.test( 'installGlobalHandler', 7, function ( assert ) {
		var w = {},
			errorMessage = 'Foo',
			errorUrl = 'http://example.com',
			errorLine = '123',
			errorColumn = '45',
			errorObject = new Error( 'Foo'),
			oldHandler = this.sandbox.stub();

		this.sandbox.stub( mw, 'track' );

		mw.errorLogger.installGlobalHandler( w );

		assert.ok( w.onerror, 'Global handler has been installed' );
		assert.strictEqual( w.onerror( errorMessage, errorUrl, errorLine ), false,
			'Global handler returns false when there is no previous handler' );
		sinon.assert.calledWithExactly( mw.track, 'global.error',
			sinon.match( { errorMessage: errorMessage, url: errorUrl, lineNumber: errorLine } ) );

		mw.track.reset();
		w.onerror( errorMessage, errorUrl, errorLine, errorColumn, errorObject );
		sinon.assert.calledWithExactly( mw.track, 'global.error',
			sinon.match( { errorMessage: errorMessage, url: errorUrl, lineNumber: errorLine,
			columnNumber: errorColumn, errorObject: errorObject } ) );

		w = { onerror: oldHandler };

		mw.errorLogger.installGlobalHandler( w );
		w.onerror( errorMessage, errorUrl, errorLine );
		sinon.assert.calledWithExactly( oldHandler, errorMessage, errorUrl, errorLine );

		oldHandler.returns( false );
		assert.strictEqual( w.onerror( errorMessage, errorUrl, errorLine ), false,
			'Global handler preserves false return from previous handler' );
		oldHandler.returns( true );
		assert.strictEqual( w.onerror( errorMessage, errorUrl, errorLine ), true,
			'Global handler preserves true return from previous handler' );
	} );
}( jQuery, mediaWiki ) );


text:
<?php
/**
 * info
 * https://developers.google.com/accounts/docs/OAuth2
 * http://code.google.com/p/google-api-php-client/wiki/OAuth2
 */

require_once VENDOR_DIR . 'google-api-php-client/src/apiClient.php';
require_once VENDOR_DIR . 'google-api-php-client/src/contrib/apiOauth2Service.php';
require_once CONFIG_DIR . 'google.php';

class GoogleAuth extends AppModel
{

    /**
     * GoogleのAPIクライアントを取得する
     */
    public static function getClient()
    {
        $client = new apiClient();
        $client->setClientId(GOOGLE_CLIENT_ID);
        $client->setClientSecret(GOOGLE_CLIENT_SECRET);
        $client->setRedirectUri(GOOGLE_REDIRECT_URI);
        $client->setDeveloperKey(GOOGLE_DEVELOPER_KEY);
        $client->setApprovalPrompt('auto');

        return $client;
    }

    /**
     * 認証するためのGoogleのURLを取得する
     * このURLにリダイレクトすることでGoogleアカウントの認証画面を表示する
     */
    public static function getAuthUrl()
    {
        $client = self::getClient();
        $oauth2 = new apiOauth2Service($client);
        return $client->createAuthUrl();
    }

    /**
     * Googleアカウントの認証結果を確認する
     * ユーザが認証を拒否した場合はAuthDeniedExceptionを発生させる
     * 認証は成功しても指定されたドメイン|メールアドレスではない場合PermissionDeniedExceptionを発生させる
     */
    public static function verify($code)
    {
        if (!$code) {
            throw new AuthDeniedException();
        }

        $client = self::getClient();
        $oauth2 = new apiOauth2Service($client);

        $client->authenticate();
        $token = $client->getAccessToken();

        $user = $oauth2->userinfo->get();
        if (!self::isAllowed($user)) {
            throw new PermissionDeniedException();
        }

        $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
        return array('identity' => $email, 'token' => $token);
    }

    /**
     * 指定されたドメイン|メールアドレスであるかを確認する
     */
    public static function isAllowed($user)
    {
        $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
        $tmp = explode('@', $email);
        $domain = array_pop($tmp);

        $allow_domains = explode(',', GOOGLE_ALLOW_DOMAINS);
        foreach ($allow_domains as $v) {
            if ($domain === trim($v)) {
                return true;
            }
        }

        $allow_emails = explode(',', GOOGLE_ALLOW_EMAILS);
        foreach ($allow_emails as $v) {
            if ($email === trim($v)) {
                return true;
            }
        }

        return false;
    }
}