text:
#include "tensorflow/core/framework/resource_mgr.h"

#include <atomic>

#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/demangle.h"
#include "tensorflow/core/platform/stacktrace.h"

namespace tensorflow {

ResourceHandle MakeResourceHandle(
    const string& container, const string& name, const DeviceBase& device,
    const TypeIndex& type_index,
    const std::vector<DtypeAndPartialTensorShape>& dtypes_and_shapes,
    const absl::optional<ManagedStackTrace>& definition_stack_trace) {
  ResourceHandle result;
  result.set_device(device.name());
  result.set_container(container);
  result.set_definition_stack_trace(definition_stack_trace);
  if (name == ResourceHandle::ANONYMOUS_NAME) {
    result.set_name(
        strings::StrCat("_AnonymousVar", ResourceHandle::GenerateUniqueId()));
  } else {
    result.set_name(name);
  }
  result.set_hash_code(type_index.hash_code());
  result.set_maybe_type_name(type_index.name());
  result.set_dtypes_and_shapes(dtypes_and_shapes);
  return result;
}

Status MakeResourceHandleToOutput(OpKernelContext* context, int output_index,
                                  const string& container, const string& name,
                                  const TypeIndex& type_index) {
  Tensor* handle;
  TF_RETURN_IF_ERROR(
      context->allocate_output(output_index, TensorShape({}), &handle));
  handle->scalar<ResourceHandle>()() =
      MakeResourceHandle(container, name, *context->device(), type_index);
  return OkStatus();
}

namespace internal {

Status ValidateDevice(OpKernelContext* ctx, const ResourceHandle& p) {
  if (ctx->device()->attributes().name() != p.device()) {
    return errors::InvalidArgument(
        "Trying to access resource ", p.name(), " located in device ",
        p.device(), " from device ", ctx->device()->attributes().name());
  }
  return OkStatus();
}

}  // end namespace internal

Status ResourceMgr::InsertDebugTypeName(uint64 hash_code,
                                        const string& type_name) {
  auto iter = debug_type_names_.emplace(hash_code, type_name);
  if (iter.first->second != type_name) {
    return errors::AlreadyExists("Duplicate hash code found for type ",
                                 type_name);
  }
  return OkStatus();
}

const char* ResourceMgr::DebugTypeName(uint64 hash_code) const {
  auto type_name_iter = debug_type_names_.find(hash_code);
  if (type_name_iter == debug_type_names_.end()) {
    return "<unknown>";
  } else {
    return type_name_iter->second.c_str();
  }
}

ResourceMgr::ResourceAndName::ResourceAndName() : name(nullptr) {}

ResourceMgr::ResourceAndName::ResourceAndName(const string& name)
    : name(absl::make_unique<string>(name)) {}

core::RefCountPtr<ResourceBase> ResourceMgr::ResourceAndName::GetResource()
    const {
  if (absl::holds_alternative<core::RefCountPtr<ResourceBase>>(resource)) {
    ResourceBase* ptr =
        absl::get<core::RefCountPtr<ResourceBase>>(resource).get();
    ptr->Ref();
    return core::RefCountPtr<ResourceBase>(ptr);
  } else if (absl::holds_alternative<core::WeakPtr<ResourceBase>>(resource)) {
    return absl::get<core::WeakPtr<ResourceBase>>(resource).GetNewRef();
  } else {
    return nullptr;
  }
}

ResourceMgr::ResourceAndName::ResourceAndName(
    ResourceAndName&& other) noexcept {
  name = std::move(other.name);
  resource = std::move(other.resource);
}

ResourceMgr::ResourceAndName::~ResourceAndName() {}

ResourceMgr::ResourceAndName& ResourceMgr::ResourceAndName::operator=(
    ResourceAndName&& other) noexcept {
  name = std::move(other.name);
  resource = std::move(other.resource);
  return *this;
}

ResourceMgr::ResourceMgr() : default_container_("localhost") {}

ResourceMgr::ResourceMgr(const string& default_container)
    : default_container_(default_container) {}

ResourceMgr::~ResourceMgr() { Clear(); }

void ResourceMgr::Clear() {
  // We do the deallocation outside of the lock to avoid a potential deadlock
  // in case any of the destructors access the resource manager.
  absl::flat_hash_map<string, Container*> tmp_containers;
  {
    mutex_lock l(mu_);
    tmp_containers = std::move(containers_);
  }
  for (const auto& p : tmp_containers) {
    delete p.second;
  }
  tmp_containers.clear();
}

string ResourceMgr::DebugString() const {
  mutex_lock l(mu_);
  struct Line {
    const string* container;
    const string type;
    const string* resource;
    const string detail;
  };
  std::vector<Line> lines;
  for (const auto& p : containers_) {
    const string& container = p.first;
    for (const auto& q : *p.second) {
      const Key& key = q.first;
      const char* type = DebugTypeName(key.first);
      const core::RefCountPtr<ResourceBase> resource = q.second.GetResource();
      Line l{&container, port::Demangle(type), q.second.name.get(),
             resource ? resource->DebugString() : "<nullptr>"};
      lines.push_back(l);
    }
  }
  std::vector<string> text;
  text.reserve(lines.size());
  for (const Line& line : lines) {
    text.push_back(strings::Printf(
        "%-20s | %-40s | %-40s | %-s", line.container->c_str(),
        line.type.c_str(), line.resource->c_str(), line.detail.c_str()));
  }
  std::sort(text.begin(), text.end());
  return absl::StrJoin(text, "\n");
}

Status ResourceMgr::DoCreate(const string& container_name, TypeIndex type,
                             const string& name, ResourceBase* resource,
                             bool owns_resource) {
  Container* container = [&]() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
    Container** ptr = &containers_[container_name];
    if (*ptr == nullptr) {
      *ptr = new Container;
    }
    return *ptr;
  }();

  // NOTE: Separating out the construction of the map key and value so that the
  // key can contain a StringPiece that borrows from the string in the value.
  ResourceAndName resource_and_name(name);

  StringPiece borrowed_name(*resource_and_name.name);

  if (owns_resource) {
    resource_and_name.resource = core::RefCountPtr<ResourceBase>(resource);
  } else {
    auto cleanup_fn = [this, container, type, borrowed_name]() {
      mutex_lock l(mu_);
      auto iter = container->find({type.hash_code(), borrowed_name});
      if (iter != container->end()) {
        container->erase(iter);
      }
    };
    resource_and_name.resource =
        core::WeakPtr<ResourceBase>(resource, cleanup_fn);
  }

  Container::value_type key_and_value(Key(type.hash_code(), borrowed_name),
                                      std::move(resource_and_name));

  auto st = container->insert(std::move(key_and_value));
  if (st.second) {
    TF_RETURN_IF_ERROR(InsertDebugTypeName(type.hash_code(), type.name()));
    return OkStatus();
  }
  return errors::AlreadyExists("Resource ", container_name, "/", name, "/",
                               type.name());
}

Status ResourceMgr::Lookup(const ResourceHandle& handle,
                           ResourceBase** resource) const {
  tf_shared_lock l(mu_);
  return DoLookup(handle.container(), handle.hash_code(),
                  /*type_name=*/"ResourceBase", handle.name(), resource);
}

Status ResourceMgr::DoLookup(const string& container, TypeIndex type,
                             const string& name,
                             ResourceBase** resource) const {
  return DoLookup(container, type.hash_code(), type.name(), name, resource);
}

Status ResourceMgr::DoLookup(const string& container, uint64 type_hash_code,
                             const string& type_name,
                             const string& resource_name,
                             ResourceBase** resource) const {
  const Container* b = gtl::FindPtrOrNull(containers_, container);
  if (b == nullptr) {
    return errors::NotFound("Container ", container,
                            " does not exist. (Could not find resource: ",
                            container, "/", resource_name, ")");
  }
  auto iter = b->find({type_hash_code, resource_name});
  if (iter == b->end()) {
    return errors::NotFound("Resource ", container, "/", resource_name, "/",
                            type_name, " does not exist.");
  }
  ResourceBase* ptr = iter->second.GetResource().release();
  if (ptr == nullptr) {
    return errors::NotFound("Resource ", container, "/", resource_name, "/",
                            type_name, " has been destroyed.");
  }
  *resource = ptr;
  return OkStatus();
}

Status ResourceMgr::PopResourceAndName(const string& container,
                                       uint64 type_hash_code,
                                       const string& resource_name,
                                       const string& type_name,
                                       ResourceAndName& resource_and_name) {
  mutex_lock l(mu_);
  Container* b = gtl::FindPtrOrNull(containers_, container);
  if (b == nullptr) {
    return errors::NotFound("Container ", container, " does not exist.");
  }
  auto iter = b->find({type_hash_code, resource_name});
  if (iter == b->end()) {
    return errors::NotFound("Resource ", container, "/", resource_name, "/",
                            type_name, " does not exist.");
  }
  std::swap(resource_and_name, iter->second);
  b->erase(iter);
  return OkStatus();
}

Status ResourceMgr::DoDelete(const string& container, uint64 type_hash_code,
                             const string& resource_name,
                             const string& type_name) {
  ResourceAndName resource_and_name;
  TF_RETURN_IF_ERROR(PopResourceAndName(
      container, type_hash_code, resource_name, type_name, resource_and_name));

  if (absl::holds_alternative<core::WeakPtr<ResourceBase>>(
          resource_and_name.resource)) {
    return errors::Internal(
        "Cannot delete an unowned Resource ", container, "/", resource_name,
        "/", type_name, " from ResourceMgr. ",
        "This indicates ref-counting ResourceHandle is exposed to weak "
        "ResourceHandle code paths.");
  }
  return OkStatus();
}

Status ResourceMgr::DoDelete(const string& container, TypeIndex type,
                             const string& resource_name) {
  return DoDelete(container, type.hash_code(), resource_name, type.name());
}

Status ResourceMgr::Delete(const ResourceHandle& handle) {
  return DoDelete(handle.container(), handle.hash_code(), handle.name(),
                  "<unknown>");
}

Status ResourceMgr::Cleanup(const string& container) {
  {
    tf_shared_lock l(mu_);
    if (!gtl::FindOrNull(containers_, container)) {
      // Nothing to cleanup.
      return OkStatus();
    }
  }
  Container* b = nullptr;
  {
    mutex_lock l(mu_);
    auto iter = containers_.find(container);
    if (iter == containers_.end()) {
      // Nothing to cleanup, it's OK (concurrent cleanup).
      return OkStatus();
    }
    b = iter->second;
    containers_.erase(iter);
  }
  CHECK(b != nullptr);
  delete b;
  return OkStatus();
}

static bool IsValidContainerName(StringPiece s) {
  using ::tensorflow::strings::Scanner;
  return Scanner(s)
      .One(Scanner::LETTER_DIGIT_DOT)
      .Any(Scanner::LETTER_DIGIT_DASH_DOT_SLASH)
      .Eos()
      .GetResult();
}

Status ContainerInfo::Init(ResourceMgr* rmgr, const NodeDef& ndef,
                           bool use_node_name_as_default) {
  CHECK(rmgr);
  rmgr_ = rmgr;
  string attr_container;
  TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "container", &attr_container));
  if (!attr_container.empty() && !IsValidContainerName(attr_container)) {
    return errors::InvalidArgument("container contains invalid characters: ",
                                   attr_container);
  }
  string attr_shared_name;
  TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "shared_name", &attr_shared_name));
  if (!attr_shared_name.empty() && (attr_shared_name[0] == '_')) {
    return errors::InvalidArgument("shared_name cannot start with '_':",
                                   attr_shared_name);
  }
  if (!attr_container.empty()) {
    container_ = attr_container;
  } else {
    container_ = rmgr_->default_container();
  }
  if (!attr_shared_name.empty()) {
    name_ = attr_shared_name;
  } else if (use_node_name_as_default) {
    name_ = ndef.name();
  } else {
    resource_is_private_to_kernel_ = true;
    static std::atomic<int64_t> counter(0);
    name_ = strings::StrCat("_", counter.fetch_add(1), "_", ndef.name());
  }
  return OkStatus();
}

string ContainerInfo::DebugString() const {
  return strings::StrCat("[", container(), ",", name(), ",",
                         resource_is_private_to_kernel() ? "private" : "public",
                         "]");
}

const ResourceHandle& HandleFromInput(OpKernelContext* ctx, int input) {
  return ctx->input(input).flat<ResourceHandle>()(0);
}

Status HandleFromInput(OpKernelContext* ctx, StringPiece input,
                       ResourceHandle* handle) {
  const Tensor* tensor;
  TF_RETURN_IF_ERROR(ctx->input(input, &tensor));
  *handle = tensor->flat<ResourceHandle>()(0);
  return OkStatus();
}

Status LookupResource(OpKernelContext* ctx, const ResourceHandle& p,
                      ResourceBase** value) {
  TF_RETURN_IF_ERROR(internal::ValidateDevice(ctx, p));
  if (p.IsRefCounting()) {
    TF_ASSIGN_OR_RETURN(*value, p.GetResource<ResourceBase>());
    (*value)->Ref();
    return OkStatus();
  }
  return ctx->resource_manager()->Lookup(p, value);
}

Status DeleteResource(OpKernelContext* ctx, const ResourceHandle& p) {
  TF_RETURN_IF_ERROR(internal::ValidateDevice(ctx, p));
  if (p.IsRefCounting()) {
    return OkStatus();
  }
  return ctx->resource_manager()->Delete(p);
}

}  //  end namespace tensorflow


text:
import { Injectable } from '@angular/core';
import { Task, Project } from '../models';

@Injectable()
export class ProjectsService {

    private projects: Project[] = [
         <Project>{
            id: 'proj-1',
            name: 'Co-DJ', features: [
                {
                    id: 'feat-1',
                    title: 'Homepage', subtasks: [
                        {
                            id: 'task-1',
                            title: 'Check if user is logged in', subtasks: [
                                { id: 'subtask-1', title: 'Check if logged in with facebook' },
                                { id: 'subtask-2', title: 'Check if logged in with google' },
                                { id: 'subtask-3', title: 'Show available playlists if logged in' }
                            ]
                        },
                        {
                            id: 'task-2',
                            title: 'UI',
                            subtasks: [
                                { id: 'subtask-4', title: 'Show create and join buttons' }
                            ]
                        }
                    ]
                },
                {
                    id: 'feat-2',
                    title: 'Create Playlist', subtasks: [
                        { id: 'task-3', title: 'Playlist settings page' }
                    ]
                }
            ]
        }
    ];

    getAll() {
        return Promise.resolve(this.projects);
    }

    create(name: string) {
        var newProject =<Project>{ name: name, id: 'proj-' + this.projects.length, features: [] };
        this.projects.push(newProject);
        return Promise.resolve(newProject);
    }
}

redpajama_set_name: RedPajamaGithub


text:
A very simple image editor that uses an html canvas to manipulate the images. It currently only has crop, rotate, and undo/redo.

It is wrapped in a simple node.js express app.


text: search_result['2213']=["topic_000000000000054D.html","AgencyDataDto Constructor",""];


text:
using System;
using System.Data.Entity.ModelConfiguration;

namespace TvTamer.Core.Models
{

    public class LoggedEvent
    {
        public int Id { get; set; }
        public string EventType { get; set; }
        public DateTime EventTime { get; set; }
        public string Message { get; set; }

    }

    public class LoggedEventMap : EntityTypeConfiguration<LoggedEvent>
    {

        public LoggedEventMap()
        {
            this.HasKey(t => t.Id);
            this.Property(t => t.EventType).IsRequired().HasMaxLength(15);
            this.Property(t => t.Message).HasMaxLength(255);
            this.Property(t => t.EventTime).IsRequired();
        }

    }
}


text:
using System.Windows.Controls;

namespace TankView.View {
    /// <summary>
    /// Interaction logic for PreviewDataString.xaml
    /// </summary>
    public partial class PreviewDataString : UserControl {
        public PreviewDataString() {
            InitializeComponent();
        }
    }
}


text:
<?php

// *** Make sure the file isn't accessed directly
defined('APPHP_EXEC') or die('Restricted Access');
//--------------------------------------------------------------------------

if($objLogin->IsLoggedInAs('owner','mainadmin')){

	// Start main content
	draw_title_bar(prepare_breadcrumbs(array(_MODULES=>'',_MODULES_MANAGEMENT=>'',ucfirst($action)=>'')));

	//if($objSession->IsMessage('notice')) echo $objSession->GetMessage('notice');
	if($objModules->modulesCount <= 0){
		$msg = draw_important_message(_MODULES_NOT_FOUND, false);
	}
	echo $msg;

	draw_content_start();
	if($mode == 'view'){
		$objModules->DrawModules();
	}else if($mode == 'add'){
		$objModules->DrawAddMode();
	}else if($mode == 'edit'){
		$objModules->DrawEditMode($rid);
	}else if($mode == 'details'){
		$objModules->DrawDetailsMode($rid);
	}
	draw_content_end();

}else{
	draw_title_bar(_ADMIN);
	draw_important_message(_NOT_AUTHORIZED);
}

?>


text:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-card',
  templateUrl: 'card.component.html',
  styleUrls: ['card.component.css']
})
export class CardComponent implements OnInit {

  @Input() cardNumber: number;
  @Output() clickCard = new EventEmitter<number>();

  constructor() {}

  ngOnInit() {}

  chooseCard(element) {
    this.clickCard.emit(element);
  }

}


text:
require 'java'

include_class 'org.sifassociation.testing.IScriptHooks'

import org.springframework.context.ApplicationContext
import org.springframework.context.support.FileSystemXmlApplicationContext

# Loads an XQuery, runs it, and prints the results.
class XQuery
    def run
        # Load the XQuery for an object.
        file = File.open("resources/queries/XQuery/AllStudentPersonals.xq", "r")
        query = file.read
        puts query + "\n\n"

        # Load the eXist collection via Spring!
        ctx = FileSystemXmlApplicationContext.new("SIFCommonsDemo.xml")
        engine = ctx.getBean("US26Collection")

        # Run the query against the collection.
        engine.run(query)

        # Print all of the results.
        begin
            result = engine.getNext()
            puts result
        end while "" != result
    end
end

XQuery.new


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.yiwen.mobike.activity.usercenter.ModifyNickNameActivity">

    <com.yiwen.mobike.views.TabTitleView
        android:id="@+id/title_modify_nick_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:rightText="保存"
        app:rightTvColor="@color/red"
        app:showRightTextView="true"
        app:titleText="昵称"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:background="@color/bg"/>

    <com.yiwen.mobike.views.ClearEditText
        android:id="@+id/et_modify_nick_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:padding="5dip"
        android:layout_margin="10dip"
        android:textCursorDrawable="@color/red"
        android:focusable="true"
        />

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bg"/>
</LinearLayout>


text:
from __future__ import unicode_literals

from operator import attrgetter

from django.test import TestCase

from django.db import models

from .models import Post, Question, Answer

class OrderWithRespectToTests(TestCase):
    def test_basic(self):
        q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?")
        q2 = Question.objects.create(text="What is your name?")

        Answer.objects.create(text="John", question=q1)
        Answer.objects.create(text="Jonno", question=q2)
        Answer.objects.create(text="Paul", question=q1)
        Answer.objects.create(text="Paulo", question=q2)
        Answer.objects.create(text="George", question=q1)
        Answer.objects.create(text="Ringo", question=q1)

        # The answers will always be ordered in the order they were inserted.
        self.assertQuerysetEqual(
            q1.answer_set.all(), [
                "John", "Paul", "George", "Ringo",
            ],
            attrgetter("text"),
        )

        # We can retrieve the answers related to a particular object, in the
        # order they were created, once we have a particular object.
        a1 = Answer.objects.filter(question=q1)[0]
        self.assertEqual(a1.text, "John")
        a2 = a1.get_next_in_order()
        self.assertEqual(a2.text, "Paul")
        a4 = list(Answer.objects.filter(question=q1))[-1]
        self.assertEqual(a4.text, "Ringo")
        self.assertEqual(a4.get_previous_in_order().text, "George")

        # Determining (and setting) the ordering for a particular item is also
        # possible.
        id_list = [o.pk for o in q1.answer_set.all()]
        self.assertEqual(a2.question.get_answer_order(), id_list)

        a5 = Answer.objects.create(text="Number five", question=q1)

        # It doesn't matter which answer we use to check the order, it will
        # always be the same.
        self.assertEqual(
            a2.question.get_answer_order(), a5.question.get_answer_order()
        )

        # The ordering can be altered:
        id_list = [o.pk for o in q1.answer_set.all()]
        x = id_list.pop()
        id_list.insert(-1, x)
        self.assertNotEqual(a5.question.get_answer_order(), id_list)
        a5.question.set_answer_order(id_list)
        self.assertQuerysetEqual(
            q1.answer_set.all(), [
                "John", "Paul", "George", "Number five", "Ringo"
            ],
            attrgetter("text")
        )

    def test_recursive_ordering(self):
        p1 = Post.objects.create(title='1')
        p2 = Post.objects.create(title='2')
        p1_1 = Post.objects.create(title="1.1", parent=p1)
        p1_2 = Post.objects.create(title="1.2", parent=p1)
        Post.objects.create(title="2.1", parent=p2)
        p1_3 = Post.objects.create(title="1.3", parent=p1)
        self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])

    def test_duplicate_order_field(self):

        class Bar(models.Model):
            pass

        class Foo(models.Model):
            bar = models.ForeignKey(Bar)
            order = models.OrderWrt()

            class Meta:
                order_with_respect_to = 'bar'

        count = 0
        for field in Foo._meta.local_fields:
            if isinstance(field, models.OrderWrt):
                count += 1

        self.assertEqual(count, 1)


text:
FactoryGirl.define do
  factory :holiday, class: 'Holiday' do
    user_id 1
    start Date.today.at_beginning_of_week
    self.end (Date.today.at_beginning_of_week + 1)
    length 1
    last_modified Date.today
  end
end


text:
import { ModifiableEntity } from '@framework/Signum.Entities'
import { ColumnOptionsMode, FilterOperation, OrderType, PaginationMode, FindOptions, FilterOption, OrderOption, ColumnOption, Pagination, QueryToken } from '@framework/FindOptions'
import { TypeContext } from '@framework/TypeContext'
import * as Finder from '@framework/Finder'
import { ExpressionOrValue } from './NodeUtils'
import * as NodeUtils from './NodeUtils'
//import { BaseNode } from './Nodes';

export interface FindOptionsExpr {
  queryName?: string;
  parentToken?: string;

  filterOptions?: FilterOptionExpr[];
  includeDefaultFilters?: boolean;
  orderOptions?: OrderOptionExpr[];
  columnOptionsMode?: ExpressionOrValue<ColumnOptionsMode>;
  columnOptions?: ColumnOptionExpr[];
  paginationMode?: PaginationMode;
  elementsPerPage?: ExpressionOrValue<number>;
  currentPage?: ExpressionOrValue<number>;
}

export interface FilterOptionExpr {
  token?: string;
  parsedToken?: QueryToken;
  operation?: ExpressionOrValue<FilterOperation>;
  value: ExpressionOrValue<any>;
  frozen?: ExpressionOrValue<boolean>;
  applicable: ExpressionOrValue<boolean>;
}

export interface OrderOptionExpr {
  token?: string;
  parsedToken?: QueryToken;
  orderType: ExpressionOrValue<OrderType>;
  applicable: ExpressionOrValue<boolean>;
}

export interface ColumnOptionExpr {
  token?: string;
  parsedToken?: QueryToken;
  displayName?: ExpressionOrValue<string>;
  applicable: ExpressionOrValue<boolean>;
}

export function toFindOptions(dn: any/*NodeUtils.DesignerNode<BaseNode>*/, ctx: TypeContext<ModifiableEntity>, foe: FindOptionsExpr): FindOptions {
  return {
    queryName: foe.queryName!,
    filterOptions: [
      ...(foe.filterOptions ? foe.filterOptions
        .filter(fo => NodeUtils.evaluateAndValidate(dn, ctx, fo, f => f.applicable, NodeUtils.isBooleanOrNull) != false)
        .map(fo => ({
          token: fo.token,
          frozen: NodeUtils.evaluateAndValidate(dn, ctx, fo, f => f.frozen, NodeUtils.isBooleanOrNull),
          operation: NodeUtils.evaluateAndValidate(dn, ctx, fo, f => f.operation, v => NodeUtils.isEnumOrNull(v, FilterOperation)),
          value: NodeUtils.evaluate(dn, ctx, fo, f => f.value)
        } as FilterOption)) : []),
    ],

    includeDefaultFilters: foe.includeDefaultFilters,

    orderOptions: foe.orderOptions ?
      foe.orderOptions
        .filter(oo => NodeUtils.evaluateAndValidate(dn, ctx, oo, o => o.applicable, NodeUtils.isBooleanOrNull) != false)
        .map(oo => ({
          token: oo.token,
          orderType: NodeUtils.evaluateAndValidate(dn, ctx, oo, o => o.orderType, v => NodeUtils.isEnumOrNull(v, OrderType))
        } as OrderOption)) : undefined,

    columnOptionsMode: NodeUtils.evaluateAndValidate(dn, ctx, foe, f => f.columnOptionsMode, v => NodeUtils.isEnumOrNull(v, ColumnOptionsMode)),

    columnOptions: foe.columnOptions ?
      foe.columnOptions
        .filter(co => NodeUtils.evaluateAndValidate(dn, ctx, co, c => c.applicable, NodeUtils.isBooleanOrNull) != false)
        .map(co => ({
          token: co.token,
          displayName: NodeUtils.evaluateAndValidate(dn, ctx, co, c => c.displayName, NodeUtils.isStringOrNull)
        } as ColumnOption)) : undefined,

    pagination: NodeUtils.evaluateAndValidate(dn, ctx, foe, f => f.paginationMode, v => NodeUtils.isEnumOrNull(v, PaginationMode)) ? ({
      mode: NodeUtils.evaluateAndValidate(dn, ctx, foe, f => f.paginationMode, v => NodeUtils.isEnumOrNull(v, PaginationMode)),
      currentPage: NodeUtils.evaluateAndValidate(dn, ctx, foe, f => f.currentPage, NodeUtils.isNumberOrNull),
      elementsPerPage: NodeUtils.evaluateAndValidate(dn, ctx, foe, f => f.elementsPerPage, NodeUtils.isNumberOrNull)
    } as Pagination) : undefined,
  }
}


text:
/**
 * This private project is a project which automatizate workflow in medical center AVESTA
 * (http://avesta-center.com) called "MedRegistry". The "MedRegistry" demonstrates my programming
 * skills to * potential employers.
 *

 * Here is short description: ( for more detailed description please read README.md or go to
 * https://github.com/theshamuel/medregistry )
 *

 * Front-end: JS, HTML, CSS (basic simple functionality) Back-end: Spring (Spring Boot, Spring IoC,
 * Spring Data, Spring Test), JWT library, Java8 DB: MongoDB Tools: git,maven,docker.
 *

 * My LinkedIn profile: https://www.linkedin.com/in/alex-gladkikh-767a15115/
 */
package com.theshamuel.medreg.model.user.dao;

import com.theshamuel.medreg.model.user.entity.User;

/**
 * The interface User operations.
 *
 * @author Alex Gladkikh
 */
public interface UserOperations {

    /**
     * Find by login user.
     *
     * @param login the login
     * @return the user
     */
    User findByLogin(String login);
}


text:
@interface RCMainViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
@end


text:
<?php

namespace duncan3dc\DateTests;

use duncan3dc\Dates\Date;
use duncan3dc\Dates\DateTime;
use PHPUnit\Framework\TestCase;

class DateTest extends TestCase
{
    public function testConstructor(): void
    {
        $unix = time();
        $datetime = new DateTime($unix);
        $date = new Date($unix);
        $this->assertSame($datetime->midday(), $date->timestamp());
    }

    public function testNow(): void
    {
        $date = Date::now();
        $this->assertSame(mktime(12, 0, 0, date("n"), date("j"), date("Y")), $date->timestamp());
    }

    public function testParse(): void
    {
        $input = "2008-02-22";
        $result = Date::parse($input)->format("Y-m-d");
        $this->assertSame($input, $result);
    }

    public function testMkdate(): void
    {
        $date = Date::mkdate(2014, 6, 12);
        $this->assertSame(mktime(12, 0, 0, 6, 12, 2014), $date->timestamp());
    }

    public function testWithHours(): void
    {
        $date = Date::mkdate(2016, 2, 20);
        $date = $date->withHours(10);
        $this->assertInstanceOf(DateTime::class, $date);
        $this->assertSame("2016-02-20 10:00:00", $date->format("Y-m-d H:i:s"));
    }

    public function testWithMinutes(): void
    {
        $date = Date::mkdate(2016, 2, 20);
        $date = $date->withMinutes(10);
        $this->assertInstanceOf(DateTime::class, $date);
        $this->assertSame("2016-02-20 12:10:00", $date->format("Y-m-d H:i:s"));
    }

    public function testWithSeconds(): void
    {
        $date = Date::mkdate(2016, 2, 20);
        $date = $date->withSeconds(10);
        $this->assertInstanceOf(DateTime::class, $date);
        $this->assertSame("2016-02-20 12:00:10", $date->format("Y-m-d H:i:s"));
    }
}


text:
FROM gcr.io/google_containers/kubernetes-dashboard-amd64:v1.8.3
MAINTAINER NsLib <mdl2009@vip.qq.com>


text:
package org.apache.http.client.protocol;

import java.io.IOException;

import org.apache.http.annotation.Immutable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.protocol.HttpContext;

/**
 * Generates authentication header for the proxy host, if required,
 * based on the actual state of the HTTP authentication context.
 *
 * @since 4.0
 */
@Immutable
public class RequestProxyAuthentication implements HttpRequestInterceptor {

    private final Log log = LogFactory.getLog(getClass());

    public RequestProxyAuthentication() {
        super();
    }

    public void process(final HttpRequest request, final HttpContext context)
            throws HttpException, IOException {
        if (request == null) {
            throw new IllegalArgumentException("HTTP request may not be null");
        }
        if (context == null) {
            throw new IllegalArgumentException("HTTP context may not be null");
        }

        if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) {
            return;
        }

        // Obtain authentication state
        AuthState authState = (AuthState) context.getAttribute(
                ClientContext.PROXY_AUTH_STATE);
        if (authState == null) {
            return;
        }

        AuthScheme authScheme = authState.getAuthScheme();
        if (authScheme == null) {
            return;
        }

        Credentials creds = authState.getCredentials();
        if (creds == null) {
            this.log.debug("User credentials not available");
            return;
        }
        if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
            try {
                request.addHeader(authScheme.authenticate(creds, request));
            } catch (AuthenticationException ex) {
                if (this.log.isErrorEnabled()) {
                    this.log.error("Proxy authentication error: " + ex.getMessage());
                }
            }
        }
    }

}


text:
            <form (ngSubmit)="okClicked()" #ledgerAccountForm="ngForm">

{{titleLedgerAccount}}

                        <button type="submit" class="sidebar-menu-button okButton"> OK</button>
                        <button type="button" class="sidebar-menu-button" (click)="cancelLedgerAccount()"> Cancel</button>

                            Name
                            <input type="text" [(ngModel)]="ledgerAccount.name" class="form-control" #inputName="ngForm" placeholder="Name" ngControl="ngcName">

                        Type
                        <select [required]="!ledgerAccountTypeDisabled" [hidden]="ledgerAccountTypeDisabled" [disabled]="ledgerAccountTypeDisabled" class="form-control" #cmbLedgerAccountTypes ngControl="ngcLedgerAccountTypes" [(ngModel)]="ledgerAccount.ledgerAccountTypeID">
                            <option *ngFor="let ledgerAccountType of ledgerAccountTypes" [value]="ledgerAccountType.ledgerAccountTypeID">
                                {{ ledgerAccountType.name }}
                            </option>
                        </select>

                        Active
                        <input type="checkbox" [(ngModel)]="ledgerAccount.active" class="form-control" #inputLedgerAccountActive="ngForm" required ngControl="ngcLedgerAccountActive">

Error getting LedgerAccount

            </form>


text:
package p;

public class A {
    public enum E {
         EA("a"),
         EB("b")

         public final String PRESENTABLE_TEXT;

         E(final String presentableText) {
           PRESENTABLE_TEXT = presentableText;
         }
    }
}


text:
class FtpConnection : public BaseConnection
{
	Q_OBJECT
public:
	explicit FtpConnection(QObject *parent = 0);
	void applySettings(QHash<QString, QVariant> &settings);

signals:

public slots:

protected:
	void replyClient(QString msg, bool logged = false);
	void replyClient(int code, QString msg);
	void replyServer(QString msg);
	void replyServer(QString cmd, QString msg);
	//void commandToTargetServer(QString cmd);

private:
	enum TargetServerConnectionState {
		Unconnected = 0,
		HangingUp,
		Connected,
		Failed
	};

	enum FtpCommandType {
		Greetings = 0,
		Auth,
		Pbsz,
		Prot,
		User,
		Pass,
		Port,
		Pasv,
		Eprt,
		Epsv,
		Raw
	};

	enum FtpCommandFlags {
		NoFlags = 1,
		NoForwardResponse = 2,
		ActiveToPassiveTranslation = 4
	};

	struct FtpCommand {
		FtpCommandType type;
		QString str;
		FtpCommandFlags flags;
	};

	void enqueueServerCommand(FtpCommandType cmd, QString arg = QString(), FtpCommandFlags flags = NoFlags);
	void enqueueServerCommand(QString cmd, QString arg);
	void enqueueServerCommand(QString cmd);
	void dispatchServerCommand();
	void dispatchServerCommand(FtpCommandType cmd, QString arg = QString(), FtpCommandFlags flags = NoFlags);
	void dispatchServerCommand(QString cmd, QString arg);
	void dispatchServerCommand(QString cmd);
	QPair<QHostAddress, quint16> decodeHostAndPort(QString msg);
	QPair<QHostAddress, quint16> decodeExtendedHostAndPort(QString msg);
	QString encodeHostAndPort(QHostAddress addr, quint16 port);
	QString encodeExtendedHostAndPort(QHostAddress addr, quint16 port);
	bool engageActiveDataConnection(QHostAddress host, quint16 port);
	bool engagePassiveDataConnection(QHostAddress host, quint16 port, FtpCommandFlags flags = NoFlags);
	bool engagePassiveToActiveDataConnectionTranslation();

	FtpDataTransfer *dataTransfer;
	TargetServerConnectionState targetServerConnectionState;
	QString userName;
	QString password;

	FtpServer::SslMode s_ssl;
	bool s_forceSsl;
	FtpServer::SslMode s_proxySslMode;
	FtpDataTransfer::TransferMode s_proxyMode;
	bool s_proxyActiveMode;
	quint32 s_readBufferSize;

	int r_router;

	QSslCertificate sslCertificate;
	QSslKey sslKey;
	bool useSsl;
	bool useSslOnData;
	QQueue<FtpCommand*> serverCommands;
	bool commandSent;
	bool waitForCommand;
	bool userCmdSent;
	bool loggedOnServer;
	QPair<QHostAddress, quint16> lastPortAddr;

private slots:
	void connectionEstablished();
	void sendGreetings();
	void processCommand();
	void forwardTargetServerReply();
//	void handleDataTransfer(QSslSocket *client);
//	void forwardDataFromTargetServerToClient();
//	void forwardDataFromClientToTargetServer();
//	void disconnectDataConnection();
//	void serverDataConnectionDisconnected();
//	void clientDataConnectionDisconnected();
//	void dataConnectionBytesWritten(qint64 bytes);
	void controlConnectionStateChange(QAbstractSocket::SocketState socketState);
	void controlConnectionEstablished();
	void targetServerConnectionError(QAbstractSocket::SocketError error);
	void targetServerConnectionEncrypted();
	void dataTransferFinished();
	void sslErrorsHandler(const QList<QSslError> & errors);
};

#endif // FTPCONNECTION_H


text:
using System.Collections.Generic;
using System.Text;
using NSubstitute;
using PactNet.Mocks.MockHttpService.Mappers;
using Xunit;

namespace PactNet.Tests.Mocks.MockHttpService.Mappers
{
    public class HttpBodyContentMapperTests
    {
        private IHttpBodyContentMapper GetSubject()
        {
            return new HttpBodyContentMapper();
        }

        [Fact]
        public void Convert1_WithNullBody_ReturnsNull()
        {
            var mapper = GetSubject();

            var result = mapper.Convert(body: null, headers: null);

            Assert.Null(result);
        }

        [Fact]
        public void Convert1_WithBodyAndNullHeaders_ReturnsBodyWithUtf8EncodingAndPlainTextContentType()
        {
            const string body = "This is my content";
            var mapper = GetSubject();

            var result = mapper.Convert(body: body, headers: null);

            Assert.Equal(body, result.Content);
            Assert.Equal(Encoding.UTF8, result.Encoding);
            Assert.Equal("text/plain", result.ContentType);
        }

        [Fact]
        public void Convert1_WithJsonBody_ReturnsJsonBodyWithUtf8EncodingAndApplicationJsonContentType()
        {
            const string contentTypeString = "application/json";
            var body = new
            {
                Test = "tester",
                Test2 = 1
            };
            var headers = new Dictionary<string, string>
            {
                { "Content-Type", contentTypeString }
            };
            const string jsonBody = "{\"Test\":\"tester\",\"Test2\":1}";
            var mapper = GetSubject();

            var result = mapper.Convert(body: body, headers: headers);

            Assert.Equal(jsonBody, result.Content);
            Assert.Equal(Encoding.UTF8, result.Encoding);
            Assert.Equal(contentTypeString, result.ContentType);
        }

        [Fact]
        public void Convert1_WithJsonBodyAndDifferentCasings_ReturnsUnNormalisedCasingJsonBodyWithUtf8EncodingAndApplicationJsonContentType()
        {
            var body = new
            {
                Test = "testeR",
                tesT2 = 1
            };
            var headers = new Dictionary<string, string>
            {
                { "content-type", "Application/Json" }
            };
            const string jsonBody = "{\"Test\":\"testeR\",\"tesT2\":1}";
            var mapper = GetSubject();

            var result = mapper.Convert(body: body, headers: headers);

            Assert.Equal(jsonBody, result.Content);
            Assert.Equal(Encoding.UTF8, result.Encoding);
            Assert.Equal("application/json", result.ContentType);
        }

        [Fact]
        public void Convert1_WithAsciiHtmlBody_CallsEncodingMapperAndReturnsBodyWithAsciiEncodingAndHtmlContentType()
        {
            const string contentTypeString = "text/html";
            const string body = "
This is my content
";
            const string encodingString = "us-ascii";
            var encoding = Encoding.ASCII;
            var headers = new Dictionary<string, string>
            {
                { "Content-Type", contentTypeString + "; charset=" + encodingString }
            };
            var mockEncodingMapper = Substitute.For<IEncodingMapper>();
            mockEncodingMapper.Convert(encodingString).Returns(encoding);

            var mapper = new HttpBodyContentMapper(mockEncodingMapper);

            var result = mapper.Convert(body: body, headers: headers);

            Assert.Equal(body, result.Content);
            Assert.Equal(encoding, result.Encoding);
            Assert.Equal(contentTypeString, result.ContentType);
        }

        [Fact]
        public void Convert2_WithNullContent_ReturnsNull()
        {
            var mapper = GetSubject();

            var result = mapper.Convert(content: null, headers: null);

            Assert.Null(result);
        }

        [Fact]
        public void Convert2_WithBodyAndNullHeaders_ReturnsBodyWithUtf8EncodingAndPlainTextContentType()
        {
            const string content = "This is my content";
            var mapper = GetSubject();

            var result = mapper.Convert(content: Encoding.UTF8.GetBytes(content), headers: null);

            Assert.Equal(content, result.Content);
            Assert.Equal(Encoding.UTF8, result.Encoding);
            Assert.Equal("text/plain", result.ContentType);
        }

        [Fact]
        public void Convert2_WithJsonContentAndDifferentCasings_ReturnsUnNormalisedCasingJsonBodyWithUtf8EncodingAndApplicationJsonContentType()
        {
            var body = new
            {
                Test = "testeR",
                tesT2 = 1
            };
            var headers = new Dictionary<string, string>
            {
                { "content-type", "Application/Json" }
            };
            const string content = "{\"Test\":\"testeR\",\"tesT2\":1}";
            var mapper = GetSubject();

            var result = mapper.Convert(content: Encoding.UTF8.GetBytes(content), headers: headers);

            Assert.Equal(body.Test, (string)result.Body.Test);
            Assert.Equal(body.tesT2, (int)result.Body.tesT2);
            Assert.Equal(Encoding.UTF8, result.Encoding);
            Assert.Equal("application/json", result.ContentType);
        }

        [Fact]
        public void Convert2_WithAsciiHtmlContent_CallsEncodingMapperAndReturnsBodyWithAsciiEncodingAndHtmlContentType()
        {
            const string contentTypeString = "text/html";
            const string content = "
This is my content
";
            const string encodingString = "us-ascii";
            var encoding = Encoding.ASCII;
            var headers = new Dictionary<string, string>
            {
                { "Content-Type", contentTypeString + "; charset=" + encodingString }
            };
            var mockEncodingMapper = Substitute.For<IEncodingMapper>();
            mockEncodingMapper.Convert(encodingString).Returns(encoding);

            var mapper = new HttpBodyContentMapper(mockEncodingMapper);

            var result = mapper.Convert(content: Encoding.UTF8.GetBytes(content), headers: headers);

            Assert.Equal(content, result.Body);
            Assert.Equal(encoding, result.Encoding);
            Assert.Equal(contentTypeString, result.ContentType);
        }

    }
}


text:
/**
 * @file   rpc.h
 * @date   Fri 09 Aug 2013 13:00:56 EST
 *
 * @brief  seL4 CIDL RPC Backend Interface
 *
 * This library provides the backend which the code generated from CIDL - Simple C IDL compiler
 * uses in order to work. This library must deal with basic serialisation / deserialisation,
 * manage basic client state on server side, and manage the communication channel in between.
 * The CIDL generated code expects this library to be there.
 *
 * NOTE: All of the implementations here may _NOT_ themselves send RPCs, with few exception.
 * Remember that if your printf involves an IPC to a server, this means no printf unless you
 * use another IPC buffer. Likewise with malloc.
 */

#ifndef _REFOS_RPC_H_
#define _REFOS_RPC_H_

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

/**
 * Maximum number of tracked objects for a single RPC call. Shouldn't need to be too long unless
 * you have functions which take a lot of arguments.
 */
#define RPC_MAX_TRACKED_OBJS 32

// -------------------------------------------------------------------------------------------------
// ------------------------------------------ IDL Declarations -------------------------------------
// -------------------------------------------------------------------------------------------------

#define _SEL4_
#ifdef _SEL4_
    #include <sel4/sel4.h>
    #define ENDPT seL4_CPtr
    typedef char byte;
    typedef seL4_CPtr cptr;
    typedef seL4_CPtr cslot;
    typedef seL4_CPtr seL4_CSlot;
    typedef seL4_MessageInfo_t msginfo_t;
#else
    #error "Unimplemented backend."
#endif

// -------------------------------------------------------------------------------------------------
// ------------------------------------------- RPC Helper ------------------------------------------
// -------------------------------------------------------------------------------------------------

/**
 * A helper function to allocate & manage the allocated memory for an RPC. Works like cstdlib
 * malloc().
 * @param[in] sz       Size of memory to allocate in bytes.
 * @return             Pointer to allocated memory.
 */
void* rpc_malloc(size_t sz);

/**
 * Free the given object at memory address. Works like cstdlib free().
 * @param[in] addr     The address ti free.
 */
void rpc_free(void *addr);

/**
 * Use the given cslot as the destination slot for cap transfer. If this isn't called explicitly,
 * the provided client/server interface below should automatically call this with a default cslot.
 * @param[in] recv_cslot CSpace slot to use to recieve caps.
 */
void rpc_setup_recv(cslot recv_cslot);

/**
 * Use the given cslot as the destination slot for cap transfer. This version does not assume
 * default cspace.
 * @param[in] recv_cslot CSpace slot to use to recieve caps.
 */
void rpc_setup_recv_cspace(seL4_CPtr cspace, seL4_CPtr recv_cslot, seL4_Word depth);

/**
 * Resets the data pointers (e.g. current IPC MR number and cap number) in the client's send buffer.
 * @param[in] cl       Generic reference to caller client state structure (optional).
 */
void rpc_reset_contents(void *cl);

// -------------------------------------------------------------------------------------------------
// ---------------------------------------------- Client RPC ---------------------------------------
// -------------------------------------------------------------------------------------------------

/**
 * Initialise client state, ready for a new RPC call.
 * @param[in] name_str Name of call being initiated (for easier debugging, may ignore this).
 * @param[in] label    The call enum label which server will use to identify which call.
 */
void rpc_init(const char* name_str, int32_t label);

/**
 * Set a custom destination endpoint. By default the destination endpoint used is the one specified
 * in the interface XML file. To support interfaces which make sense to be served by multiple
 * servers, the IDL param mode='connect_ep' is used. CIDL will see this flag and call this function
 * with the marked parameter.
 * @param[in] dest     Destination server endpoint that the next rpc_call_server will invoke.
 */
void rpc_set_dest(ENDPT dest);

/**
 * Add a new integer type variable to the end of the current global RPC packet.
 * @param[in] v        Value of integer to add.
 */
void rpc_push_uint(uint32_t v);

/**
 * Add a new C string type variable to the end of the current global RPC packet.
 * @param[in] v        String to add.
 */
void rpc_push_str(const char* v);

/**
 * Add a new generic buffer object to the end of the current global RPC packet.
 * @param[in] v        Pointer to buffer obj to add.
 * @param[in] sz       Size of the buffer obj in bytes.
 */
void rpc_push_buf(void* v, size_t sz);

/**
 * Add a new array of generic buffer objects to the end of the current global RPC packet.
 * @param[in] v        Pointer to array of buffer objects to add.
 * @param[in] sz       Size of a single buffer obj in bytes.
 * @param[in] count    Number of objects in v.
 */
void rpc_push_buf_array(void* v, size_t sz, uint32_t count);

/**
 * Add a new capablity to the end of the current global RPC packet.
 * @param[in] v        Capability to add.
 */
void rpc_push_cptr(ENDPT v);

/**
 * Read the next integer type variable from current global RPC packet.
 * @return             Value of next integer.
 */
uint32_t rpc_pop_uint();

/**
 * Read the next C string from current global RPC packet.
 * NOTE: Using a string as output is not safe in standard C function calls, and likewise it is also
 * not a good idea at all for RPC calls, and is prone to buffer overflow.
 * @param[out] v       Pointer to allocated string to read into.
 */
void rpc_pop_str(char* v);

/**
 * Read the next generic buffer object from current global RPC packet.
 * @param[out] v       Pointer to allocated buffer object to read into.
 * @param[in] sz       Size of generic object to read in bytes.
 */
void rpc_pop_buf(void* v, size_t sz);

/**
 * Read the next capability from current global RPC packet. Note that this function may choose to
 * copy out the recieved cap from the recieve slot in this function and leave an empty stub in
 * rpc_copyout_cptr, or alternatively it may just simply return the recieve slot here and then
 * implement copyout in rpc_copyout_cptr. See @ref rpc_copyout_cptr.
 * @return             CSpace pointer to recieved capability.
 */
ENDPT rpc_pop_cptr();

/**
 * Read the next buffer object array from current global RPC packet.
 * @param[out] v       Pointer to allocated buffer object to read into.
 * @param[in] sz       Size of generic object to read in bytes.
 * @param[in] count    Max. number of objects in array (only used for checking).
 */
void rpc_pop_buf_array(void* v, size_t sz, uint32_t count);

/**
 * Invoke the server. The destination endpoint may be automatically determined from the label for
 * simplicity, unless overridden by a call to @ref rpc_custom_dest.
 * @return             0 on success, non-zero otherwise.
 */
int rpc_call_server();

/**
 * Finish up the current client RPC call and release all allocated objects.
 */
void rpc_release();

/**
 * Allocate a new cslot, and then copy out the given recieved capabiliy from the recieve cslot to a
 * new cslot. This function exists to optionally separate @ref rpc_pop_cptr from allocating a new
 * cslot. This function useful in the case where allocating a cslot itself requires an RPC call,
 * as RPC calling from @ref rpc_pop_cptr may result in munging the IPC buffer. This function may need
 * to temporarily copy the given cap to an empty slot, in order to IPC to allocate a new cslot.
 * @param[in] v        CSpace pointer to capability to copy out.
 * @return             CSpace pointer to copied out capability.
 */
ENDPT rpc_copyout_cptr(ENDPT v);

// -------------------------------------------------------------------------------------------------
// ------------------------------------------- Server RPC ------------------------------------------
// -------------------------------------------------------------------------------------------------

/**
 * Helper structure which stores the basic state needed for an RPC server to manage a single RPC
 * client. Note that the rpc_sv server interface here passes generic void* as client struct and
 * does not assume you use this struct, so this struct is provided for convenience and using this
 * struct is optional. The default implementation assumes the void *cl parameters to be
 * a valid rpc_client_state_t* object;
 *
 * A good way to use this structure is to 'inherit' it by putting it as the first element of your
 * own client structure. Then you may pointer case freely between your own client structure and a
 * rpc_client_state_t.
 */
typedef struct rpc_client_state_s {
    msginfo_t minfo;
    void* obj[RPC_MAX_TRACKED_OBJS];
    uint32_t num_obj;

    bool skip_reply;
    ENDPT reply;

    void *userptr;
} rpc_client_state_t;

/**
 * A simple buffer structure. Buffer array (pointer / length combinations in C) are converted to
 * this on server side.
 */
typedef struct rpc_buffer_s {
    void *data;
    uint32_t count;
} rpc_buffer_t;

/**
 * Initialise server's client state, ready for a new RPC call.
 * @param[in] cl       Generic reference to caller client state structure.
 */
void rpc_sv_init(void *cl);

/**
 * Read next integer from recieved RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @return             The next integer in packet.
 */
uint32_t rpc_sv_pop_uint(void *cl);

/**
 * Read next string from recieved RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @return             The allocated and read string.
 */
char* rpc_sv_pop_str(void *cl);

/**
 * Read next buffer object from recieved RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @param[out] v        Allocated buffer obj to read into.
 * @param[in] sz       Size of buffer object in bytes.
 */
void rpc_sv_pop_buf(void *cl, void *v, size_t sz);

/**
 * Read next array of buffer objects from recieved RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @param[in] sz       Size of a single buffer object in bytes.
 * @return             The allocated and read buffer obj array.
 */
rpc_buffer_t rpc_sv_pop_buf_array(void *cl, size_t sz);

/**
 * Read next capability from recieved RPC packet. For an unwrapped capability, the unwrapped badge
 * value is returned from this function. In the case of a transferred cap, it is _NOT_ copied out
 * here (i.e. the value of recv_cslot in given @ref rpc_setup_recv is simply returned. It is up to
 * the server handler to copy out given transferred caps. It is also up to the server handler to
 * know (and check) which caps are unwrapped and which are transferred.
 * @param[in] cl       Generic reference to caller client state structure.
 * @return             The next capability.
 */
ENDPT rpc_sv_pop_cptr(void *cl);

/**
 * Add a new integer variable to the end of the current global RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @param[in] v        String to add.
 */
void rpc_sv_push_uint(void *cl, uint32_t v);

/**
 * Add a new buffer object to the end of the current global RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @param[in] v        Pointer to buffer object to add.
 * @param[in] sz       size of the given buffer object in bytes.
 */
void rpc_sv_push_buf(void *cl, void* v, size_t sz);

/**
 * Add a capability to the end of the current global RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @param[in] v        CPtr to capability to add and transfer.
 */
void rpc_sv_push_cptr(void *cl, ENDPT v);

/**
 * Add an array of objects to the end of the current global RPC packet.
 * @param[in] cl       Generic reference to caller client state structure.
 * @param[in] v        A value rpc_buffer_t containing pointer to buffer and count info.
 * @param[in] sz       size of the a single object in bytes.
 */
void rpc_sv_push_buf_array(void *cl, rpc_buffer_t v, size_t sz);

/**
 * Reply to the client RPC. Depending on whether the reply is immediate or saved-first then replied
 * later, this function should send to the correct corresponding reply endpoint in either case.
 * @param[in] cl       Generic reference to caller client state structure.
 */
void rpc_sv_reply(void* cl);

/**
 * End the current RPC for the given client caller and release all tis allocated objects.
 * @param[in] cl       Generic reference to caller client state structure.
 */
void rpc_sv_release(void *cl);

/**
 * Optionally save the current client RPC reply cap to reply later. A default weak definition is
 * provided, and servers may want to override this. If this function returns True, the generated
 * reply_*() functions are not called and must be invoked manually by the server. Useful
 * for implementing server-side asynchronous syscalls which providing a synchronous syscall
 * interface to clients. You may RPC from this function.
 * @param[in] cl       Generic reference to caller client state structure.
 * @return             False to reply immediately, True if the reply endpoint was saved.
 */
bool rpc_sv_save_reply(void *cl);

/**
 * Retrieve the saved reply endpoint if it has been saved, or 0 otherwise.
 * @param[in] cl       Generic reference to caller client state structure.
 * @return             saved reply endpoint if it was saved, 0 otherwise to reply immediately.
 */
ENDPT rpc_sv_get_reply_endpoint(void *cl);

void rpc_sv_track_obj(void* cl, void* addr);

void rpc_sv_free_tracked_objs(void* cl);

bool rpc_sv_skip_reply(void *cl);

#endif /* _REFOS_RPC_H_ */


text:
swayc_t *output_by_name(const char* name, const struct wlc_point *abs_pos);
swayc_t *swayc_adjacent_output(swayc_t *output, enum movement_direction dir, const struct wlc_point *abs_pos, bool pick_closest);

// Place absolute coordinates for given container into given wlc_point.
void get_absolute_position(swayc_t *container, struct wlc_point *point);

// Place absolute coordinates for the center point of given container into
// given wlc_point.
void get_absolute_center_position(swayc_t *container, struct wlc_point *point);

#endif


text:
/*
    Rewrite Listing 4.4, using the C++ string class instead of char arrays.
*/

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string name;
    string dessert;

    cout << "Enter your name: \n";
    getline(cin, name);

    cout << "Enter your favorite dessert: \n";
    getline(cin, dessert);

    cout << "I have some delicious " << dessert;
    cout << " for you, " << name << ".\n";
    return 0;
}


text:
=============
jonsson.ninja
=============

A blog built with `Pelican <http://getpelican.com/>`_ that resides on
`jonsson.ninja <http://jonsson.ninja/>`.

Author: Daniel Jonsson

License
=======

Whatever code I have written for the site is licensed under the `MIT License
<LICENSE>`_ and the content (blog posts and images) is licensed under the `CC
BY 4.0 <https://creativecommons.org/licenses/by/4.0/>`_.

Set up
======

Install dependencies:

::

    $ pyvenv env
    $ source env/bin/activate
    $ pip install -r requirements.txt

Develop
=======

Start a local web server with:

::

    $ make devserver


text:
[![Build Status](https://travis-ci.org/sn127/dirsuite.svg?branch=master)](https://travis-ci.org/sn127/dirsuite)
[![Coverage Status](https://coveralls.io/repos/github/sn127/dirsuite/badge.svg?branch=master)](https://coveralls.io/github/sn127/dirsuite?branch=master)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/fi.sn127/dirsuite_2.12/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/fi.sn127/dirsuite_2.12)
[![Javadocs](http://javadoc.io/badge/fi.sn127/dirsuite_2.12.svg?color=blue)](http://javadoc.io/doc/fi.sn127/dirsuite_2.12)

# DirSuite test framework and add-on for ScalaTest

DirSuite add-on to ScalaTest. DirSuite can run (huge) collection of tests which are defined on filesystem.
Arguments, inputs and expected reference output files are defined by test directory.

## Documentation

 * [docs/dirsuite.md](./docs/dirsuite.md) has general information about dirsuite and how to use it
 * [docs/howto.md](./docs/howto.md) has links and explanation to example project and it's test cases.
 * Example test setup with DirSuite:
   * [tests](./examples/tests/) Example test corpus
   * [DirSuiteDemo](./examples/src/test/scala/DirSuiteDemo.scala) Demo setup against example test corpus.
 * [Tackler Project](https://github.com/sn127/tackler) has extensive set of tests based on DirSuite
   * [Tackler's dirsuite tests](https://github.com/sn127/tackler/tree/stable/tests)
   * [Tackler's dirsuite clean up setup](https://github.com/sn127/tackler/blob/stable/project/TacklerTests.scala)

## Releases

Release artifacts are published on the maven
[Central Repository](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22fi.sn127%22).

Library configuration for sbt:

    libraryDependencies += "fi.sn127" %% "dirsuite" % "0.7.0"

For release information and version history details, see [CHANGELOG](./CHANGELOG.md). For Upgrade instructions,
see [UPGRADE](./UPGRADE.md) .

## Contributing to DirSuite

Contributions to the project are most welcome. Please see
[CONTRIBUTING](./CONTRIBUTING.md) how you could help.

Your pull requests can be merged only if you can certify
the [Developer Certificate of Origin (DCO), Version 1.1](./DCO).
To certify DCO (e.g. sign-off your commit), you must add
a `Signed-off-by` line to **every**  git commit message
(e.g. `git commit -s`):

    Signed-off-by: github-account <your.real@email.address>

If you set your `user.name` and `user.email` in git configs,
then git will include that line for you with `git commit -s`.
These settings can be done per repository basis,
so they don't have be global settings in your system.

Please make sure that you sign-off all your PR's commits.

## Credits

See [THANKS](./THANKS.md) for full list of credits. Obviously
without [ScalaTest](http://www.scalatest.org/) this project
would not exists.

## License

    Copyright 2016-2017 SN127.fi Contributors

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
define(function(){
    /**
     * Clamps value inside range.
     */
    /**
     * Description
     * @method clamp
     * @param {} val
     * @param {} min
     * @param {} max
     * @return ConditionalExpression
     */
    function clamp(val, min, max){
        return val < min? min : (val > max? max : val);
    }
    return clamp;
});


text:
package com.yahoo.dtf.util;

public class NumberUtil {

    private static String numbers = "0123456789";

    private static boolean[] NUMBERS = new boolean[256];

    static {
        for (int i = 0; i < NUMBERS.length; i++) {
            NUMBERS[i] = numbers.indexOf((char)i) != -1;
        }
    }

    /**
     * Best way to detect that the string being passed is a long value, the
     * NumberUtilSuite compares using regular expressions and new Long(value)
     * against this method and both lose by more than 5x in terms of
     * performance.
     *
     * @param string
     * @return
     */
    public static boolean isLong(String string) {
        for(int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);

            if ( c > NUMBERS.length || !NUMBERS[c] )
                return false;
        }

        return (string.length() != 0);
    }

    /**
     * Best way to detect that the string being passed is a double value, the
     * NumberUtilSuite compares using regular expressions and new Double(value)
     * against this method and both lose by more than 5x in terms of
     * performance.
     *
     * @param string
     * @return
     */
    public static boolean isDouble(String string) {
        for(int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            if ( c > NUMBERS.length || (!NUMBERS[c] && c != '.') )
                return false;
        }

        return (string.length() != 0);
    }
}


text:
package com.ojn.gexf4j.core.data;

import java.util.List;

import com.ojn.gexf4j.core.Mode;
import com.ojn.gexf4j.core.dynamic.Dynamic;

public interface AttributeList extends List<Attribute>, Dynamic<AttributeList> {

	AttributeClass getAttributeClass();

	Mode getMode();
	AttributeList setMode(Mode mode);

	Attribute createAttribute(AttributeType type, String title);
	Attribute createAttribute(String id, AttributeType type, String title);

	AttributeList addAttribute(AttributeType type, String title);
	AttributeList addAttribute(String id, AttributeType type, String title);
}


text:
package org.apache.spark.sql.execution.datasources.jdbc

import scala.collection.mutable.ArrayBuffer

import org.apache.spark.internal.Logging
import org.apache.spark.Partition
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{DataFrame, Row, SaveMode, SparkSession, SQLContext}
import org.apache.spark.sql.jdbc.JdbcDialects
import org.apache.spark.sql.sources._
import org.apache.spark.sql.types.StructType

/**
 * Instructions on how to partition the table among workers.
 */
private[sql] case class JDBCPartitioningInfo(
    column: String,
    lowerBound: Long,
    upperBound: Long,
    numPartitions: Int)

private[sql] object JDBCRelation extends Logging {
  /**
   * Given a partitioning schematic (a column of integral type, a number of
   * partitions, and upper and lower bounds on the column's value), generate
   * WHERE clauses for each partition so that each row in the table appears
   * exactly once.  The parameters minValue and maxValue are advisory in that
   * incorrect values may cause the partitioning to be poor, but no data
   * will fail to be represented.
   *
   * Null value predicate is added to the first partition where clause to include
   * the rows with null value for the partitions column.
   *
   * @param partitioning partition information to generate the where clause for each partition
   * @return an array of partitions with where clause for each partition
   */
  def columnPartition(partitioning: JDBCPartitioningInfo): Array[Partition] = {
    if (partitioning == null || partitioning.numPartitions <= 1 ||
      partitioning.lowerBound == partitioning.upperBound) {
      return Array[Partition](JDBCPartition(null, 0))
    }

    val lowerBound = partitioning.lowerBound
    val upperBound = partitioning.upperBound
    require (lowerBound <= upperBound,
      "Operation not allowed: the lower bound of partitioning column is larger than the upper " +
      s"bound. Lower bound: $lowerBound; Upper bound: $upperBound")

    val numPartitions =
      if ((upperBound - lowerBound) >= partitioning.numPartitions) {
        partitioning.numPartitions
      } else {
        logWarning("The number of partitions is reduced because the specified number of " +
          "partitions is less than the difference between upper bound and lower bound. " +
          s"Updated number of partitions: ${upperBound - lowerBound}; Input number of " +
          s"partitions: ${partitioning.numPartitions}; Lower bound: $lowerBound; " +
          s"Upper bound: $upperBound.")
        upperBound - lowerBound
      }
    // Overflow and silliness can happen if you subtract then divide.
    // Here we get a little roundoff, but that's (hopefully) OK.
    val stride: Long = upperBound / numPartitions - lowerBound / numPartitions
    val column = partitioning.column
    var i: Int = 0
    var currentValue: Long = lowerBound
    var ans = new ArrayBuffer[Partition]()
    while (i < numPartitions) {
      val lBound = if (i != 0) s"$column >= $currentValue" else null
      currentValue += stride
      val uBound = if (i != numPartitions - 1) s"$column < $currentValue" else null
      val whereClause =
        if (uBound == null) {
          lBound
        } else if (lBound == null) {
          s"$uBound or $column is null"
        } else {
          s"$lBound AND $uBound"
        }
      ans += JDBCPartition(whereClause, i)
      i = i + 1
    }
    ans.toArray
  }
}

private[sql] case class JDBCRelation(
    parts: Array[Partition], jdbcOptions: JDBCOptions)(@transient val sparkSession: SparkSession)
  extends BaseRelation
  with PrunedFilteredScan
  with InsertableRelation {

  override def sqlContext: SQLContext = sparkSession.sqlContext

  override val needConversion: Boolean = false

  override val schema: StructType = JDBCRDD.resolveTable(jdbcOptions)

  // Check if JDBCRDD.compileFilter can accept input filters
  override def unhandledFilters(filters: Array[Filter]): Array[Filter] = {
    filters.filter(JDBCRDD.compileFilter(_, JdbcDialects.get(jdbcOptions.url)).isEmpty)
  }

  override def buildScan(requiredColumns: Array[String], filters: Array[Filter]): RDD[Row] = {
    // Rely on a type erasure hack to pass RDD[InternalRow] back as RDD[Row]
    JDBCRDD.scanTable(
      sparkSession.sparkContext,
      schema,
      requiredColumns,
      filters,
      parts,
      jdbcOptions).asInstanceOf[RDD[Row]]
  }

  override def insert(data: DataFrame, overwrite: Boolean): Unit = {
    import scala.collection.JavaConverters._

    val options = jdbcOptions.asProperties.asScala +
      ("url" -> jdbcOptions.url, "dbtable" -> jdbcOptions.table)
    val mode = if (overwrite) SaveMode.Overwrite else SaveMode.Append

    new JdbcRelationProvider().createRelation(
      data.sparkSession.sqlContext, mode, options.toMap, data)
  }

  override def toString: String = {
    val partitioningInfo = if (parts.nonEmpty) s" [numPartitions=${parts.length}]" else ""
    // credentials should not be included in the plan output, table information is sufficient.
    s"JDBCRelation(${jdbcOptions.table})" + partitioningInfo
  }
}


text:
Super simple contact submission form app

I built this app for my personal website, and there isn't much to it, but it
does send through the Gmail API and enforces recaptcha. Let me know if this is
useful to you. Thanks!

### Setup

On the google developers console (https://console.developers.google.com):

1. Enable the Gmail API
2. Add an OAuth2 client with an application type of 'Other'
3. Click the 'Download JSON' button
4. Rename the file 'client_secret.json' and add it to your project
5. On your local machine (somewhere that can load a web page), run:

```
python authorize.py
```

6. Setup recaptcha through https://www.google.com/recaptcha/. Make note of your key and secret
7. Update 'config.json' with your information, including recaptcha secret
8. Setup virtualenv and install dependencies:

```
virtualenv venv
. venv/bin/activate
pip install -r requirements.txt
```

9. Run the app

```
python app.py
```

10. Deploy!


text:
.mblSlider {
  background-image: url(compat/slider-h-bg.png);
  background-repeat: repeat-x;
}
.mblSliderProgressBar {
  background-image: url(compat/slider-h-bar-bg.png);
  background-repeat: repeat-x;
}
.mblSliderHandle {
  background-image: url(compat/slider-handle-bg.png);
}
.mblSliderV {
  background-color: #e2e2e2;
  background-image: none;
}
.mblSliderV .mblSliderProgressBar {
  background-color: Highlight;
  background-image: none;
}
.dj_gecko .mblSlider {
  background-image: none;
  -moz-user-select: none;
  -moz-box-sizing: content-box;
}
.dj_gecko .mblSliderProgressBar {
  background-image: none;
}
.dj_gecko .mblSliderHandle {
  background-image: none;
}
.dj_ff3 .mblSlider {
  -moz-border-radius: 0;
}
.dj_ff3 .mblSliderProgressBar {
  -moz-border-radius: 0;
}
.dj_ff3 .mblSliderHandle {
  -moz-border-radius: 0;
}


text:
from django.conf.urls import url
from django.views.generic import TemplateView as Tv
import django_cas_ng.views
import webapp.views.base as v

urlpatterns = [
    # index

    url(r'^$', v.index, name='index'),

    # static pages

    url(r'^help/$', Tv.as_view(template_name='webapp/pages/help.html'), name='help'),
    url(r'^terms/$', v.terms, name='terms'),
    url(r'^feedback/$', v.feedback, name='feedback'),

    # tasks

    url(r'^tasks/$', v.tasks, name='tasks'),
    url(r'^task/(?P<task_id>[0-9]+)/$', v.task, name='task'),
    url(r'^task/(?P<task_id>[0-9]+)/submit/$', v.task_submit, name='submit_task'),
    url(r'^task/submission/status/$', v.submission_status, name='check_submission_status'),
    url(r'^task/report/(?P<submission_id>[^/]+)/$', v.submission_report, name='view_report'),

    # accounts
    url(r'^accounts/login/$', v.choose_login_method, name='base_login'),

    url(r'^accounts/internal/$', v.choose_internal_login, name='internal_choose'),
    url(r'^accounts/internal/login/$', v.internal_login, name='internal_login'),
    url(r'^accounts/internal/logout/$', v.internal_logout, name='internal_logout'),
    url(r'^accounts/internal/forget/$', v.internal_forget, name='internal_forget'),
    url(r'^accounts/internal/forget/(?P<signed_data>[^/]+)/$', v.internal_forget_link, name='internal_forget_link'),
    url(r'^accounts/internal/register/$', v.internal_register, name='internal_register'),

    url(r'^accounts/cas/login/$', django_cas_ng.views.login, name='cas_ng_login'),
    url(r'^accounts/cas/logout/$', django_cas_ng.views.logout, name='cas_ng_logout'),
    url(r'^accounts/cas/callback/$', django_cas_ng.views.callback, name='cas_ng_proxy_callback'),

    # user

    url(r'^user/profile/$', v.user_profile, name='user_profile'),
    url(r'^user/reports/$', v.user_reports, name='user_reports'),

    # other

    url(r'^invitation/(?P<access_token>[^/]+)/$', v.access_invite_link, name='access_invite_link'),

    url(r'^package/(?P<task_data>[^/]+)/(?P<package_name>[^/]+)$',
        v.download_package, name='package_download'),

    url(r'^csp-report/$', v.handle_csp_violation, name='handle_csp_violation')
]


text:
package org.apache.kafka.streams.processor.internals;

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.clients.producer.internals.DefaultPartitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.MetricName;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.header.internals.RecordHeader;
import org.apache.kafka.common.header.internals.RecordHeaders;
import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.metrics.Sensor;
import org.apache.kafka.common.metrics.stats.WindowedSum;
import org.apache.kafka.common.serialization.ByteArraySerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.streams.errors.AlwaysContinueProductionExceptionHandler;
import org.apache.kafka.streams.errors.DefaultProductionExceptionHandler;
import org.apache.kafka.streams.errors.StreamsException;
import org.apache.kafka.streams.processor.StreamPartitioner;
import org.apache.kafka.streams.processor.internals.testutil.LogCaptureAppender;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class RecordCollectorTest {

    private final LogContext logContext = new LogContext("test ");

    private final List<PartitionInfo> infos = Arrays.asList(
        new PartitionInfo("topic1", 0, Node.noNode(), new Node[0], new Node[0]),
        new PartitionInfo("topic1", 1, Node.noNode(), new Node[0], new Node[0]),
        new PartitionInfo("topic1", 2, Node.noNode(), new Node[0], new Node[0])
    );

    private final Cluster cluster = new Cluster("cluster", Collections.singletonList(Node.noNode()), infos,
        Collections.emptySet(), Collections.emptySet());

    private final ByteArraySerializer byteArraySerializer = new ByteArraySerializer();
    private final StringSerializer stringSerializer = new StringSerializer();

    private final StreamPartitioner<String, Object> streamPartitioner = (topic, key, value, numPartitions) -> {
        return Integer.parseInt(key) % numPartitions;
    };

    @Test
    public void testSpecificPartition() {

        final RecordCollectorImpl collector = new RecordCollectorImpl(
            "RecordCollectorTest-TestSpecificPartition",
            new LogContext("RecordCollectorTest-TestSpecificPartition "),
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer<>(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer));

        final Headers headers = new RecordHeaders(new Header[]{new RecordHeader("key", "value".getBytes())});

        collector.send("topic1", "999", "0", null, 0, null, stringSerializer, stringSerializer);
        collector.send("topic1", "999", "0", null, 0, null, stringSerializer, stringSerializer);
        collector.send("topic1", "999", "0", null, 0, null, stringSerializer, stringSerializer);

        collector.send("topic1", "999", "0", headers, 1, null, stringSerializer, stringSerializer);
        collector.send("topic1", "999", "0", headers, 1, null, stringSerializer, stringSerializer);

        collector.send("topic1", "999", "0", headers, 2, null, stringSerializer, stringSerializer);

        final Map<TopicPartition, Long> offsets = collector.offsets();

        assertEquals((Long) 2L, offsets.get(new TopicPartition("topic1", 0)));
        assertEquals((Long) 1L, offsets.get(new TopicPartition("topic1", 1)));
        assertEquals((Long) 0L, offsets.get(new TopicPartition("topic1", 2)));

        // ignore StreamPartitioner
        collector.send("topic1", "999", "0", null, 0, null, stringSerializer, stringSerializer);
        collector.send("topic1", "999", "0", null, 1, null, stringSerializer, stringSerializer);
        collector.send("topic1", "999", "0", headers, 2, null, stringSerializer, stringSerializer);

        assertEquals((Long) 3L, offsets.get(new TopicPartition("topic1", 0)));
        assertEquals((Long) 2L, offsets.get(new TopicPartition("topic1", 1)));
        assertEquals((Long) 1L, offsets.get(new TopicPartition("topic1", 2)));
    }

    @Test
    public void testStreamPartitioner() {

        final RecordCollectorImpl collector = new RecordCollectorImpl(
            "RecordCollectorTest-TestStreamPartitioner",
            new LogContext("RecordCollectorTest-TestStreamPartitioner "),
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer<>(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer));

        final Headers headers = new RecordHeaders(new Header[]{new RecordHeader("key", "value".getBytes())});

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
        collector.send("topic1", "9", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
        collector.send("topic1", "27", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
        collector.send("topic1", "81", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
        collector.send("topic1", "243", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        collector.send("topic1", "28", "0", headers, null, stringSerializer, stringSerializer, streamPartitioner);
        collector.send("topic1", "82", "0", headers, null, stringSerializer, stringSerializer, streamPartitioner);
        collector.send("topic1", "244", "0", headers, null, stringSerializer, stringSerializer, streamPartitioner);

        collector.send("topic1", "245", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        final Map<TopicPartition, Long> offsets = collector.offsets();

        assertEquals((Long) 4L, offsets.get(new TopicPartition("topic1", 0)));
        assertEquals((Long) 2L, offsets.get(new TopicPartition("topic1", 1)));
        assertEquals((Long) 0L, offsets.get(new TopicPartition("topic1", 2)));
    }

    @Test
    public void shouldNotAllowOffsetsToBeUpdatedExternally() {
        final String topic = "topic1";
        final TopicPartition topicPartition = new TopicPartition(topic, 0);

        final RecordCollectorImpl collector = new RecordCollectorImpl(
            "RecordCollectorTest-TestSpecificPartition",
            new LogContext("RecordCollectorTest-TestSpecificPartition "),
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer<>(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer));

        collector.send(topic, "999", "0", null, 0, null, stringSerializer, stringSerializer);
        collector.send(topic, "999", "0", null, 0, null, stringSerializer, stringSerializer);
        collector.send(topic, "999", "0", null, 0, null, stringSerializer, stringSerializer);

        final Map<TopicPartition, Long> offsets = collector.offsets();

        assertThat(offsets.get(topicPartition), equalTo(2L));
        assertThrows(UnsupportedOperationException.class, () -> offsets.put(new TopicPartition(topic, 0), 50L));

        assertThat(collector.offsets().get(topicPartition), equalTo(2L));
    }

    @SuppressWarnings("unchecked")
    @Test(expected = StreamsException.class)
    public void shouldThrowStreamsExceptionOnAnyExceptionButProducerFencedException() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                throw new KafkaException();
            }
        });

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldThrowStreamsExceptionOnSubsequentCallIfASendFailsWithDefaultExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                callback.onCompletion(null, new Exception());
                return null;
            }
        });

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        try {
            collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
            fail("Should have thrown StreamsException");
        } catch (final StreamsException expected) { /* ok */ }
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldNotThrowStreamsExceptionOnSubsequentCallIfASendFailsWithContinueExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new AlwaysContinueProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                callback.onCompletion(null, new Exception());
                return null;
            }
        });

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldRecordSkippedMetricAndLogWarningIfSendFailsWithContinueExceptionHandler() {
        final Metrics metrics = new Metrics();
        final Sensor sensor = metrics.sensor("dropped-records");
        final LogCaptureAppender logCaptureAppender = LogCaptureAppender.createAndRegister();
        final MetricName metricName = new MetricName("name", "group", "description", Collections.emptyMap());
        sensor.add(metricName, new WindowedSum());
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new AlwaysContinueProductionExceptionHandler(),
            metrics.sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                callback.onCompletion(null, new Exception());
                return null;
            }
        });
        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
        assertEquals(1.0, metrics.metrics().get(metricName).metricValue());
        assertTrue(logCaptureAppender.getMessages().contains("test Error sending records topic=[topic1] and partition=[0]; The exception handler chose to CONTINUE processing in spite of this error. Enable TRACE logging to view failed messages key and value."));
        LogCaptureAppender.unregister(logCaptureAppender);
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldThrowStreamsExceptionOnFlushIfASendFailedWithDefaultExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                callback.onCompletion(null, new Exception());
                return null;
            }
        });

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        try {
            collector.flush();
            fail("Should have thrown StreamsException");
        } catch (final StreamsException expected) { /* ok */ }
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldNotThrowStreamsExceptionOnFlushIfASendFailedWithContinueExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new AlwaysContinueProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                callback.onCompletion(null, new Exception());
                return null;
            }
        });

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        collector.flush();
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldThrowStreamsExceptionOnCloseIfASendFailedWithDefaultExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                callback.onCompletion(null, new Exception());
                return null;
            }
        });

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        try {
            collector.close();
            fail("Should have thrown StreamsException");
        } catch (final StreamsException expected) { /* ok */ }
    }

    @SuppressWarnings("unchecked")
    @Test
    public void shouldNotThrowStreamsExceptionOnCloseIfASendFailedWithContinueExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new AlwaysContinueProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public synchronized Future<RecordMetadata> send(final ProducerRecord record, final Callback callback) {
                callback.onCompletion(null, new Exception());
                return null;
            }
        });

        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);

        collector.close();
    }

    @SuppressWarnings("unchecked")
    @Test(expected = StreamsException.class)
    public void shouldThrowIfTopicIsUnknownWithDefaultExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public List<PartitionInfo> partitionsFor(final String topic) {
                return Collections.emptyList();
            }

        });
        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
    }

    @SuppressWarnings("unchecked")
    @Test(expected = StreamsException.class)
    public void shouldThrowIfTopicIsUnknownWithContinueExceptionHandler() {
        final RecordCollector collector = new RecordCollectorImpl(
            "test",
            logContext,
            new AlwaysContinueProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        collector.init(new MockProducer(cluster, true, new DefaultPartitioner(), byteArraySerializer, byteArraySerializer) {
            @Override
            public List<PartitionInfo> partitionsFor(final String topic) {
                return Collections.emptyList();
            }

        });
        collector.send("topic1", "3", "0", null, null, stringSerializer, stringSerializer, streamPartitioner);
    }

    @Test
    public void testRecordHeaderPassThroughSerializer() {
        final CustomStringSerializer keySerializer = new CustomStringSerializer();
        final CustomStringSerializer valueSerializer = new CustomStringSerializer();
        keySerializer.configure(Collections.emptyMap(), true);

        final RecordCollectorImpl collector = new RecordCollectorImpl(
            "test",
            logContext,
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );
        final MockProducer<byte[], byte[]> mockProducer = new MockProducer<>(cluster, true, new DefaultPartitioner(),
                byteArraySerializer, byteArraySerializer);
        collector.init(mockProducer);

        collector.send("topic1", "3", "0", new RecordHeaders(), null, keySerializer, valueSerializer, streamPartitioner);

        final List<ProducerRecord<byte[], byte[]>> recordHistory = mockProducer.history();
        for (final ProducerRecord<byte[], byte[]> sentRecord : recordHistory) {
            final Headers headers = sentRecord.headers();
            assertEquals(2, headers.toArray().length);
            assertEquals(new RecordHeader("key", "key".getBytes()), headers.lastHeader("key"));
            assertEquals(new RecordHeader("value", "value".getBytes()), headers.lastHeader("value"));
        }
    }

    @Test
    public void testShouldNotThrowNPEOnCloseIfProducerIsNotInitialized() {
        final RecordCollectorImpl collector = new RecordCollectorImpl(
            "NoNPE",
            logContext,
            new DefaultProductionExceptionHandler(),
            new Metrics().sensor("dropped-records")
        );

        collector.close();
    }

    private static class CustomStringSerializer extends StringSerializer {

        private boolean isKey;

        private CustomStringSerializer() {
        }

        @Override
        public void configure(final Map<String, ?> configs, final boolean isKey) {
            this.isKey = isKey;
            super.configure(configs, isKey);
        }

        @Override
        public byte[] serialize(final String topic, final Headers headers, final String data) {
            if (isKey) {
                headers.add(new RecordHeader("key", "key".getBytes()));
            } else {
                headers.add(new RecordHeader("value", "value".getBytes()));
            }
            return serialize(topic, data);
        }
    }
}


text:
using System;
using System.ComponentModel.DataAnnotations;

namespace AppCampus.SignboardApi.Models.QueryModels
{
    /// <summary>
    /// The Approva; input model.
    /// </summary>
    public class ApprovalInputModel
    {
        /// <summary>
        /// The CompanyId of the signboard
        /// </summary>
        [Required]
        public Guid CompanyId { get; set; }

        /// <summary>
        /// The Comment of the signboard.
        /// It is nullable
        /// </summary>
        public string Comment { get; set; }
    }
}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>reveal.js - HTML5 File API</title>

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/moon.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

h1 - h3 Tags

h1- Tag  Klein und Großschreibung äöüß

h2- Tag  Klein und Großschreibung äöüß

h3- Tag  Klein und Großschreibung äöüß

Paragraph Text  Klein und Großschreibung äöüß

					Ohne- Tag  Klein und Grossschreibung äöüß

Alles in theme moon

HTML5 File API

HTML5 stellt  leistungsstarke APIs für die Interaktion mit binären Daten und dem lokalen Dateisystem der Nutzer bereit. Die File APIs erlauben es Webanwendungen unter anderem, Dateien (a)synchron zu lesen, beliebige Blobs zu erstellen, Dateien an einen temporären Speicherort zu schreiben, Dateiverzeichnisse zu lesen, Dateien per Drag & Drop vom Desktop in den Browser zu verschieben und binäre Daten  hochzuladen.

Das API lässt sich  unterteilen in:

Dateien lesen und bearbeiten

Erstellen und schreiben

Verzeichnisse und Dateisystemzugriff

File API Schnittstellen zum Zugriff auf Dateien :

 File  - Stellt schreibgeschützte Informationen wie Name, Dateigröße, Mimetyp und einen Verweis auf den Dateihandle bereit.

 FileList  -  eine arrayartige Folge von File-Objekten als Rückgabe des HTML5 "input type="file" multiple" Tags</span

 Blob  - Rohdaten einer Datei, zum Unterteilen in Bytebereiche</span

Dateien lesen:

FileReader

 Bei Verwendung in Verbindung mit den obigen Datenstrukturen kann die FileReader-Schnittstelle dazu genutzt werden, eine Datei über die vertraute JavaScript-Ereignisbehandlung asynchron zu lesen. Dadurch können Sie den Fortschritt eines Lesevorgangs überwachen, Fehler ermitteln und feststellen, wann ein Ladevorgang abgeschlossen ist. Die APIs ähneln in vielerlei Hinsicht dem XMLHttpRequest-Ereignismodell.

Erstellen und schreiben:

BlobBuilder

 FileWriter

HTML File API

Verzeichnisse und Dateisystemzugriff:

DirectoryReader

FileEntry/DirectoryEntry

LocalFileSystem

Header h2

Top1

						Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo
						ligula eget dolor. Aenean massa.

Top2

						Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo
						ligula eget dolor. Aenean massa.

Top3

						Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo
						ligula eget dolor. Aenean massa.

Header h2

Top1

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo
						ligula eget dolor. Aenean massa.

Top2

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo
						ligula eget dolor. Aenean massa.

Top3

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo
						ligula eget dolor. Aenean massa.

fileReader Demo HTML Part:

Demo Imagedatei Reader mit HTML5 und Filesystem API

      Bilddatei auswählen:
      <input type="file" id="fileInput">

fileReader Demo javascript Part:

window.onload = function() {

var fileInput = document.getElementById('fileInput');
var bildfenster = document.getElementById('picture_area');

fileInput.addEventListener('change', function(e) {
	var file = fileInput.files[0];
	var imageType = /image.*/;

	if (file.type.match(imageType)) {
		var reader = new FileReader();
		reader.onload = function(e) {
			bildfenster.innerHTML = "";
			var img = new Image();
			img.src = reader.result;
			bildfenster.appendChild(img);
		}
		reader.readAsDataURL(file);
	} else {
		bildfenster.innerHTML = "File not supported!"
	}
});

}

					filereader Demo:

      Bilddatei auswählen:
      <input type="file" id="fileInput">

<!