text:
<?php

namespace Oro\Component\Layout\Tests\Unit\Loader\Generator\Extension;

use CG\Generator\PhpClass;
use CG\Generator\PhpMethod;
use CG\Core\DefaultGeneratorStrategy;

use Oro\Component\Layout\Loader\Generator\VisitContext;
use Oro\Component\Layout\Loader\Generator\Extension\ImportLayoutUpdateVisitor;

class ImportLayoutUpdateVisitorTest extends \PHPUnit_Framework_TestCase
{
    // @codingStandardsIgnoreStart
    public function testVisit()
    {

        $condition = new ImportLayoutUpdateVisitor();
        $phpClass = PhpClass::create('ImportedLayoutUpdate');
        $visitContext = new VisitContext($phpClass);

        $method = PhpMethod::create('testMethod');

        $condition->startVisit($visitContext);
        $visitContext->getUpdateMethodWriter()->writeln('echo 123;');
        $condition->endVisit($visitContext);

        $method->setBody($visitContext->getUpdateMethodWriter()->getContent());
        $phpClass->setMethod($method);
        $strategy = new DefaultGeneratorStrategy();
        $this->assertSame(
<<<CLASS
use Oro\Component\Layout\ImportLayoutManipulator;

class ImportedLayoutUpdate implements \Oro\Component\Layout\LayoutUpdateImportInterface, \Oro\Component\Layout\IsApplicableLayoutUpdateInterface
{
    private \$parentLayoutUpdate;
    private \$import;

    public function testMethod()
    {
        if (null === \$this->import) {
            throw new \RuntimeException('Missing import configuration for layout update');
        }

        if (\$this->parentLayoutUpdate instanceof Oro\Component\Layout\IsApplicableLayoutUpdateInterface
            && !\$this->parentLayoutUpdate->isApplicable(\$item->getContext())) {
            return;
        }

        \$layoutManipulator  = new ImportLayoutManipulator(\$layoutManipulator, \$this->import);
        echo 123;
    }

    public function setParentUpdate(\Oro\Component\Layout\ImportsAwareLayoutUpdateInterface \$parentLayoutUpdate)
    {
        \$this->parentLayoutUpdate = \$parentLayoutUpdate;
    }

    public function setImport(\Oro\Component\Layout\Model\LayoutUpdateImport \$import)
    {
        \$this->import = \$import;
    }

    public function isApplicable(\Oro\Component\Layout\ContextInterface \$context)
    {
        return true;
    }

    public function getImport()
    {
        return \$this->import;
    }
}
CLASS
        ,
        $strategy->generate($visitContext->getClass()));
    }
    //codingStandardsIgnoreEnd
}


text:
The next step is to create the models as we discussed in the introduction. In Frappé, models are called **DocTypes**. You can create new DocTypes from the Desk UI. **DocTypes** are made of fields called **DocField** and role based permissions are integrated into the models, these are called **DocPerms**.

When a DocType is saved, a new table is created in the database. This table is named as `tab[doctype]`.

When you create a **DocType** a new folder is created in the **Module** and a model JSON file and a controller template in Python are automatically created. When you update the DocType, the JSON model file is updated and whenever `bench migrate` is executed, it is synced with the database. This makes it easy to propagate schema changes and migrate.

### Developer Mode

To create models, you must set `developer_mode` as 1 in the `site_config.json` file located in /sites/library and execute command `bench clear-cache` or use the user menu in UI and click on "Reload" for the changes to take effect. You should now see the "Developer" app on your desk

	{
	 "db_name": "bcad64afbf",
	 "db_password": "v3qHDeVKvWVi7s97",
	 "developer_mode": 1
	}

{next}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<refentry xml:id="function.mysqli-execute" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>mysqli_execute</refname>
  <refpurpose>Alias for <function>mysqli_stmt_execute</function></refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <para>
   This function is an alias of <function>mysqli_stmt_execute</function>.
  </para>
 </refsect1>

 <refsect1 role="notes">
  &reftitle.notes;
  <note>
   <para>
    <function>mysqli_execute</function> is deprecated and will be removed.
   </para>
  </note>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>mysqli_stmt_execute</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, QueryList, ViewChildren } from '@angular/core';
import { asapScheduler as asap, combineLatest, Subject } from 'rxjs';
import { startWith, subscribeOn, takeUntil } from 'rxjs/operators';

import { ScrollService } from 'app/shared/scroll.service';
import { TocItem, TocService } from 'app/shared/toc.service';

type TocType = 'None' | 'Floating' | 'EmbeddedSimple' | 'EmbeddedExpandable';

@Component({
  selector: 'aio-toc',
  template: `

Contents

    <button
      *ngIf="type === 'EmbeddedExpandable'"
      type="button"
      (click)="toggle(false)"
      class="toc-heading embedded secondary"
      title="Expand/collapse contents"
      aria-label="Expand/collapse contents"
      [attr.aria-pressed]="!isCollapsed"
    >
      Contents
      <mat-icon class="rotating-icon" svgIcon="keyboard_arrow_right" [class.collapsed]="isCollapsed"></mat-icon>
    </button>

      <ng-container *ngFor="let toc of tocList; let i = index">

= primaryMax"
          [class.active]="i === activeIndex"
        >

      </ng-container>

    <button
      *ngIf="type === 'EmbeddedExpandable'"
      type="button"
      (click)="toggle()"
      class="toc-more-items embedded material-icons"
      [class.collapsed]="isCollapsed"
      title="Expand/collapse contents"
      aria-label="Expand/collapse contents"
      [attr.aria-pressed]="!isCollapsed"
    ></button>

 `,
  styles: [],
})
export class TocComponent implements OnInit, AfterViewInit, OnDestroy {
  activeIndex: number | null = null;
  type: TocType = 'None';
  isCollapsed = true;
  isEmbedded = false;
  @ViewChildren('tocItem') private items: QueryList<ElementRef>;
  private onDestroy = new Subject();
  primaryMax = 4;
  tocList: TocItem[];

  constructor(private scrollService: ScrollService, elementRef: ElementRef, private tocService: TocService) {
    this.isEmbedded = elementRef.nativeElement.className.indexOf('embedded') !== -1;
  }

  ngOnInit() {
    this.tocService.tocList.pipe(takeUntil(this.onDestroy)).subscribe((tocList) => {
      this.tocList = tocList;
      const itemCount = count(this.tocList, (item) => item.level !== 'h1');

      this.type =
        itemCount > 0 ? (this.isEmbedded ? (itemCount > this.primaryMax ? 'EmbeddedExpandable' : 'EmbeddedSimple') : 'Floating') : 'None';
    });
  }

  ngAfterViewInit() {
    if (!this.isEmbedded) {
      // We use the `asap` scheduler because updates to `activeItemIndex` are triggered by DOM changes,
      // which, in turn, are caused by the rendering that happened due to a ChangeDetection.
      // Without asap, we would be updating the model while still in a ChangeDetection handler, which is disallowed by Angular.
      combineLatest(this.tocService.activeItemIndex.pipe(subscribeOn(asap)), this.items.changes.pipe(startWith(this.items)))
        .pipe(takeUntil(this.onDestroy))
        .subscribe(([index, items]) => {
          this.activeIndex = index;
          if (index === null || index >= items.length) {
            return;
          }

          const e = items.toArray()[index].nativeElement;
          const p = e.offsetParent;

          const eRect = e.getBoundingClientRect();
          const pRect = p.getBoundingClientRect();

          const isInViewport = eRect.top >= pRect.top && eRect.bottom <= pRect.bottom;

          if (!isInViewport) {
            p.scrollTop += eRect.top - pRect.top - p.clientHeight / 2;
          }
        });
    }
  }

  ngOnDestroy() {
    this.onDestroy.next(null);
  }

  toggle(canScroll = true) {
    this.isCollapsed = !this.isCollapsed;
    if (canScroll && this.isCollapsed) {
      this.toTop();
    }
  }

  toTop() {
    this.scrollService.scrollToTop();
  }
}

function count<T>(array: T[], fn: (item: T) => boolean) {
  return array.reduce((result, item) => (fn(item) ? result + 1 : result), 0);
}


text:
package com.thejohnfreeman.lazy;

import java.util.ArrayDeque;
import java.util.Iterator;

/**
 * An iterative algorithm for forcing a directed acyclic graph of lazy values.
 */
public final class Force
{
    /** Just a namespace, so no constructor. */
    private Force() {}

    /**
     * When forced, a long chain of lazy values can cause a stack overflow.
     * This method forces a value iteratively.
     *
     * @param <T> the type of the value
     * @param value the lazy value
     * @return the forced value
     * @throws IllegalStateException
     *     if any value in the dependency graph cannot be evaluated
     */
    public static <T> T force(final Lazy<T> value)
        throws IllegalStateException
    {
        final ArrayDeque<Context> values = new ArrayDeque<>();
        values.push(new Context(value));

        while (!values.isEmpty()) {
            forceTop(values);
        }

        return value.getValue();
    }

    /**
     * If the top value is ready, force it; otherwise, push one of its unforced
     * dependencies. This is a separate function to make use of `return` as a
     * multi-level `break`. This particular case does not fit the labeled break
     * pattern for Java.
     */
    private static void forceTop(final ArrayDeque<Context> values) {
        final Context context = values.getFirst();
        if (!context.value.isForced()) {
            for (final Lazy<?> dependency : context) {
                if (!dependency.isForced()) {
                    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
                    final Context ctx = new Context(dependency);
                    values.push(ctx);
                    return;
                }
            }
            context.value.forceThis();
        }
        values.pop();
    }

    /**
     * A context is a lazy value and an iterator through its dependencies. Once
     * all of the dependencies have been forced, the value is forced.
     */
    private static class Context
        implements Iterable<Lazy<?>>, Iterator<Lazy<?>>
    {
        public final Lazy<?> value;
        private Iterator<? extends Lazy<?>> _iterator;

        public Context(final Lazy<?> value) {
            this.value = value;
        }

        @Override
        public Iterator<Lazy<?>> iterator() {
            if (_iterator == null) {
                _iterator = value.getDependencies().iterator();
            }
            return this;
        }

        @Override
        public boolean hasNext() {
            return _iterator.hasNext();
        }

        @Override
        public Lazy<?> next() {
            return _iterator.next();
        }
    }
}


text:
package io.neba.core.resourcemodels.mapping.testmodels;

import io.neba.api.annotations.This;

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author Olaf Otto
 */
@Retention(RUNTIME)
@This
public @interface CustomAnnotationWithThisMetaAnnotation {
}


text:
import java.util.concurrent.SynchronousQueue;

public class TestSynchronousQueue {

	public static void main(String[] args) {
		final SynchronousQueue<Integer> queue = new SynchronousQueue<Integer>();
		final long events = 100000000;

		Thread reader = new Thread(){
			public void run() {
				int i = 0;
				try{
					while(i++ < events){
						queue.take();
					}
				}catch(Exception e){
					e.printStackTrace();
				}

			};
		};

		Thread writer = new Thread(){
			public void run() {
				int i = 0;
				while(i++ < events){
					try{
						queue.put(i);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
		};

		long start = System.currentTimeMillis();
		reader.start();
		writer.start();
		System.out.println("Took " + (System.currentTimeMillis() - start) + " ms to process " + events + " data");
	}

}


text:
<?php
namespace Luwake\Router;

use Luwake\Request;
use Luwake\Response;
use PetrGrishin\Pipe\Pipe;
use Luwake\Router;

class Layer
{
    private $path = null;

    private $options = [];

    private $handle = null;

    /**
     * @var Router
     */
    public $router = null;

    /**
     * @var Route
     */
    public $route = null;

    public $method = null;

    public function __construct($path, $options = [], $fn)
    {
        $this->path = $path;

        $this->options = $options;

        $this->handle = $fn;
    }

    public function handle(Request $req, Response $res, $next)
    {
        if ($this->method == null || $this->method == strtolower($req->method)) {
            $path = $this->path;

            if($path == '*' || $path == '/'){
                return $this->process($req, $res, $next);
            }

            if ($this->router) {
                $path = $this->router->resolve($this->path);
            }

            if ($this->route) {
                $path = $this->route->resolve($this->path);
            }

            $keys = [];
            $regexp = \PathToRegexp::convert($path, $keys);
            if ($keys) {
                $matches = \PathToRegexp::match($regexp, $req->path);
                if ($matches) {
                    $params = array_slice($matches, 1);
                    foreach ($keys as $i=>$key){
                        $params[$key['name']] = $params[$i];
                    }
                    $req->params = $params;
                    return $this->process($req, $res, $next);
                }
            } else {
                if (strpos($req->path, $path) === 0) {
                    return $this->process($req, $res, $next);
                }
            }
        }
        return $next($req, $res);
    }

    public function process(Request $req, Response $res, $next)
    {
        return Pipe::create($req, $res)->through($this->handle)->then($next);
    }

    public function __invoke(Request $req, Response $res, $next)
    {
        return $this->handle($req, $res, $next);
    }
}


text:
@implementation UIView (SAMViewCategory)

#pragma mark - getter setter

- (void)setSam_x:(CGFloat)sam_x
{
    CGRect rect = self.frame ;
    rect.origin.x = sam_x;
    self.frame = rect;
}
- (CGFloat)sam_x
{
    return self.frame.origin.x;
}

- (void)setSam_y:(CGFloat)sam_y
{
    CGRect rect = self.frame ;
    rect.origin.y = sam_y;
    self.frame = rect;
}
- (CGFloat)sam_y
{
    return self.frame.origin.y;
}

- (void)setSam_width:(CGFloat)sam_width
{
    CGRect rect = self.frame;
    rect.size.width = sam_width;
    self.frame = rect;
}
- (CGFloat)sam_width
{
    return self.frame.size.width;
}

- (void)setSam_height:(CGFloat)sam_height
{
    CGRect rect = self.frame;
    rect.size.height = sam_height;
    self.frame = rect;
}
- (CGFloat)sam_height
{
    return self.frame.size.height;
}

- (void)setSam_top:(CGFloat)sam_top
{
    self.frame = CGRectMake(self.sam_left, sam_top, self.sam_width, self.sam_height);
}
- (CGFloat)sam_top
{
    return self.frame.origin.y;
}

- (void)setSam_left:(CGFloat)sam_left
{
    self.frame = CGRectMake(sam_left, self.sam_top, self.sam_width, self.sam_height);
}
- (CGFloat)sam_left
{
    return self.frame.origin.x;
}

- (void)setSam_bottom:(CGFloat)sam_bottom
{
    self.frame = CGRectMake(self.sam_left, sam_bottom - self.sam_height, self.sam_width, self.sam_height);
}
- (CGFloat)sam_bottom
{
    return self.frame.size.height + self.frame.origin.y;
}

- (void)setSam_right:(CGFloat)sam_right
{
    self.frame = CGRectMake(sam_right - self.sam_width, self.sam_top, self.sam_width, self.sam_height);
}
- (CGFloat)sam_right
{
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setSam_center_x:(CGFloat)sam_center_x
{
    CGPoint center = self.center;
    center.x = sam_center_x;
    self.center = center;
}
- (CGFloat)sam_center_x
{
    return self.center.x;
}

- (void)setSam_center_y:(CGFloat)sam_center_y
{
    CGPoint center = self.center;
    center.y = sam_center_y;
    self.center = center;
}
- (CGFloat)sam_center_y
{
    return self.center.y;
}

- (void)setSam_size:(CGSize)sam_size
{
    CGRect rect = self.frame;
    rect.size = sam_size;
    self.frame = rect;
}
- (CGSize)sam_size
{
    return self.frame.size;
}

- (void)setSam_origin:(CGPoint)sam_origin
{
    CGRect rect = self.frame;
    rect.origin = sam_origin;
    self.frame = rect;
}
- (CGPoint)sam_origin
{
    return self.frame.origin;
}

- (void)setSam_cornerRadius:(CGFloat)sam_cornerRadius
{
    [self.layer setCornerRadius:sam_cornerRadius];
    [self.layer setMasksToBounds:YES];
}
- (CGFloat)sam_cornerRadius
{
    return self.layer.cornerRadius;
}

- (void)setSam_borderColor:(UIColor *)sam_borderColor
{
    [self.layer setBorderColor:sam_borderColor.CGColor];
}
- (UIColor *)sam_borderColor
{
    return [UIColor colorWithCGColor:self.layer.borderColor];
}

- (void)setSam_borderWidth:(CGFloat)sam_borderWidth
{
    [self.layer setBorderWidth:sam_borderWidth];
}
- (CGFloat)sam_borderWidth
{
    return self.layer.borderWidth;
}

@end


text:
package com.lixavier.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.lixavier.constant.Constants;
import com.lixavier.model.TbAdmin;
import com.lixavier.resp.Result;
import com.lixavier.resp.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Component("adminInterceptor")
public class AdminInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private List<String> excludedUrls;

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        try {
            // 打印日志
            logger.info("requestUri:" + request.getRequestURI());
            logger.info("contextPath:" + request.getContextPath());
            logger.info("parameterNames:" + JSON.toJSONString(request.getParameterMap()));

            if(request.getRequestURI().contains("/STATIC") || request.getRequestURI().contains(Constants.URL_PREFIX + "ajax")) {
                return true;
            }

            for (String u : excludedUrls) {
                if(request.getRequestURI().equals(u)) {
                    return true;
                }
            }
            TbAdmin tbAdmin = (TbAdmin) request.getSession().getAttribute(Constants.USER_SESSION);
            if(null != tbAdmin) {
                return true;
            }
            request.getRequestDispatcher(Constants.URL_PREFIX + "login").forward(request, response);
            return false;
        } catch (Exception e) {
            returnErrorJson(response, JSON.toJSONString(Result.newError(ResultCode.SYS_ERROR)));
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    private void returnErrorJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            logger.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}


text:
using namespace swift;

struct OverrideSection {
  uintptr_t version;
#define OVERRIDE(name, ret, attrs, ccAttrs, namespace, typedArgs, namedArgs) \
  Override_ ## name name;
#include "../../public/runtime/CompatibilityOverride.def"
};

OverrideSection Swift51Overrides
__attribute__((used, section("__DATA,__swift51_hooks"))) = {
  .version = 0,
  .conformsToSwiftProtocol = swift51override_conformsToSwiftProtocol,
};

// Allow this library to get force-loaded by autolinking
__attribute__((weak, visibility("hidden")))
extern "C"
char _swift_FORCE_LOAD_$_swiftCompatibility51 = 0;


text:
package distsql

import (
	"math"

	"github.com/pingcap/errors"
	"github.com/pingcap/parser/mysql"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/sessionctx/stmtctx"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/statistics"
	"github.com/pingcap/tidb/tablecodec"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/codec"
	"github.com/pingcap/tidb/util/ranger"
	"github.com/pingcap/tipb/go-tipb"
)

// RequestBuilder is used to build a "kv.Request".
// It is called before we issue a kv request by "Select".
type RequestBuilder struct {
	kv.Request
	err error
}

// Build builds a "kv.Request".
func (builder *RequestBuilder) Build() (*kv.Request, error) {
	return &builder.Request, errors.Trace(builder.err)
}

// SetTableRanges sets "KeyRanges" for "kv.Request" by converting "tableRanges"
// to "KeyRanges" firstly.
func (builder *RequestBuilder) SetTableRanges(tid int64, tableRanges []*ranger.Range, fb *statistics.QueryFeedback) *RequestBuilder {
	if builder.err != nil {
		return builder
	}
	builder.Request.KeyRanges = TableRangesToKVRanges(tid, tableRanges, fb)
	return builder
}

// SetIndexRanges sets "KeyRanges" for "kv.Request" by converting index range
// "ranges" to "KeyRanges" firstly.
func (builder *RequestBuilder) SetIndexRanges(sc *stmtctx.StatementContext, tid, idxID int64, ranges []*ranger.Range) *RequestBuilder {
	if builder.err != nil {
		return builder
	}
	builder.Request.KeyRanges, builder.err = IndexRangesToKVRanges(sc, tid, idxID, ranges, nil)
	return builder
}

// SetTableHandles sets "KeyRanges" for "kv.Request" by converting table handles
// "handles" to "KeyRanges" firstly.
func (builder *RequestBuilder) SetTableHandles(tid int64, handles []int64) *RequestBuilder {
	builder.Request.KeyRanges = TableHandlesToKVRanges(tid, handles)
	return builder
}

// SetDAGRequest sets the request type to "ReqTypeDAG" and construct request data.
func (builder *RequestBuilder) SetDAGRequest(dag *tipb.DAGRequest) *RequestBuilder {
	if builder.err != nil {
		return builder
	}

	builder.Request.Tp = kv.ReqTypeDAG
	builder.Request.StartTs = dag.StartTs
	builder.Request.Data, builder.err = dag.Marshal()
	return builder
}

// SetAnalyzeRequest sets the request type to "ReqTypeAnalyze" and cosntruct request data.
func (builder *RequestBuilder) SetAnalyzeRequest(ana *tipb.AnalyzeReq) *RequestBuilder {
	if builder.err != nil {
		return builder
	}

	builder.Request.Tp = kv.ReqTypeAnalyze
	builder.Request.StartTs = ana.StartTs
	builder.Request.Data, builder.err = ana.Marshal()
	builder.Request.NotFillCache = true
	builder.Request.IsolationLevel = kv.RC
	builder.Request.Priority = kv.PriorityLow
	return builder
}

// SetChecksumRequest sets the request type to "ReqTypeChecksum" and construct request data.
func (builder *RequestBuilder) SetChecksumRequest(checksum *tipb.ChecksumRequest) *RequestBuilder {
	if builder.err != nil {
		return builder
	}

	builder.Request.Tp = kv.ReqTypeChecksum
	builder.Request.StartTs = checksum.StartTs
	builder.Request.Data, builder.err = checksum.Marshal()
	builder.Request.NotFillCache = true
	return builder
}

// SetKeyRanges sets "KeyRanges" for "kv.Request".
func (builder *RequestBuilder) SetKeyRanges(keyRanges []kv.KeyRange) *RequestBuilder {
	builder.Request.KeyRanges = keyRanges
	return builder
}

// SetDesc sets "Desc" for "kv.Request".
func (builder *RequestBuilder) SetDesc(desc bool) *RequestBuilder {
	builder.Request.Desc = desc
	return builder
}

// SetKeepOrder sets "KeepOrder" for "kv.Request".
func (builder *RequestBuilder) SetKeepOrder(order bool) *RequestBuilder {
	builder.Request.KeepOrder = order
	return builder
}

func (builder *RequestBuilder) getIsolationLevel() kv.IsoLevel {
	switch builder.Tp {
	case kv.ReqTypeAnalyze:
		return kv.RC
	}
	return kv.SI
}

func (builder *RequestBuilder) getKVPriority(sv *variable.SessionVars) int {
	switch sv.StmtCtx.Priority {
	case mysql.NoPriority, mysql.DelayedPriority:
		return kv.PriorityNormal
	case mysql.LowPriority:
		return kv.PriorityLow
	case mysql.HighPriority:
		return kv.PriorityHigh
	}
	return kv.PriorityNormal
}

// SetFromSessionVars sets the following fields for "kv.Request" from session variables:
// "Concurrency", "IsolationLevel", "NotFillCache".
func (builder *RequestBuilder) SetFromSessionVars(sv *variable.SessionVars) *RequestBuilder {
	builder.Request.Concurrency = sv.DistSQLScanConcurrency
	builder.Request.IsolationLevel = builder.getIsolationLevel()
	builder.Request.NotFillCache = sv.StmtCtx.NotFillCache
	builder.Request.Priority = builder.getKVPriority(sv)
	return builder
}

// SetStreaming sets "Streaming" flag for "kv.Request".
func (builder *RequestBuilder) SetStreaming(streaming bool) *RequestBuilder {
	builder.Request.Streaming = streaming
	return builder
}

// SetConcurrency sets "Concurrency" for "kv.Request".
func (builder *RequestBuilder) SetConcurrency(concurrency int) *RequestBuilder {
	builder.Request.Concurrency = concurrency
	return builder
}

// TableRangesToKVRanges converts table ranges to "KeyRange".
func TableRangesToKVRanges(tid int64, ranges []*ranger.Range, fb *statistics.QueryFeedback) []kv.KeyRange {
	if fb == nil || fb.Hist() == nil {
		return tableRangesToKVRangesWithoutSplit(tid, ranges)
	}
	ranges = fb.Hist().SplitRange(ranges)
	krs := make([]kv.KeyRange, 0, len(ranges))
	feedbackRanges := make([]*ranger.Range, 0, len(ranges))
	for _, ran := range ranges {
		low := codec.EncodeInt(nil, ran.LowVal[0].GetInt64())
		high := codec.EncodeInt(nil, ran.HighVal[0].GetInt64())
		if ran.LowExclude {
			low = []byte(kv.Key(low).PrefixNext())
		}
		// If this range is split by histogram, then the high val will equal to one bucket's upper bound,
		// since we need to guarantee each range falls inside the exactly one bucket, `PerfixNext` will make the
		// high value greater than upper bound, so we store the range here.
		r := &ranger.Range{LowVal: []types.Datum{types.NewBytesDatum(low)},
			HighVal: []types.Datum{types.NewBytesDatum(high)}}
		feedbackRanges = append(feedbackRanges, r)

		if !ran.HighExclude {
			high = []byte(kv.Key(high).PrefixNext())
		}
		startKey := tablecodec.EncodeRowKey(tid, low)
		endKey := tablecodec.EncodeRowKey(tid, high)
		krs = append(krs, kv.KeyRange{StartKey: startKey, EndKey: endKey})
	}
	fb.StoreRanges(feedbackRanges)
	return krs
}

func tableRangesToKVRangesWithoutSplit(tid int64, ranges []*ranger.Range) []kv.KeyRange {
	krs := make([]kv.KeyRange, 0, len(ranges))
	for _, ran := range ranges {
		low, high := encodeHandleKey(ran)
		startKey := tablecodec.EncodeRowKey(tid, low)
		endKey := tablecodec.EncodeRowKey(tid, high)
		krs = append(krs, kv.KeyRange{StartKey: startKey, EndKey: endKey})
	}
	return krs
}

func encodeHandleKey(ran *ranger.Range) ([]byte, []byte) {
	low := codec.EncodeInt(nil, ran.LowVal[0].GetInt64())
	high := codec.EncodeInt(nil, ran.HighVal[0].GetInt64())
	if ran.LowExclude {
		low = []byte(kv.Key(low).PrefixNext())
	}
	if !ran.HighExclude {
		high = []byte(kv.Key(high).PrefixNext())
	}
	return low, high
}

// TableHandlesToKVRanges converts sorted handle to kv ranges.
// For continuous handles, we should merge them to a single key range.
func TableHandlesToKVRanges(tid int64, handles []int64) []kv.KeyRange {
	krs := make([]kv.KeyRange, 0, len(handles))
	i := 0
	for i < len(handles) {
		j := i + 1
		for ; j < len(handles) && handles[j-1] != math.MaxInt64; j++ {
			if handles[j] != handles[j-1]+1 {
				break
			}
		}
		low := codec.EncodeInt(nil, handles[i])
		high := codec.EncodeInt(nil, handles[j-1])
		high = []byte(kv.Key(high).PrefixNext())
		startKey := tablecodec.EncodeRowKey(tid, low)
		endKey := tablecodec.EncodeRowKey(tid, high)
		krs = append(krs, kv.KeyRange{StartKey: startKey, EndKey: endKey})
		i = j
	}
	return krs
}

// IndexRangesToKVRanges converts index ranges to "KeyRange".
func IndexRangesToKVRanges(sc *stmtctx.StatementContext, tid, idxID int64, ranges []*ranger.Range, fb *statistics.QueryFeedback) ([]kv.KeyRange, error) {
	if fb == nil || fb.Hist() == nil {
		return indexRangesToKVWithoutSplit(sc, tid, idxID, ranges)
	}
	feedbackRanges := make([]*ranger.Range, 0, len(ranges))
	for _, ran := range ranges {
		low, high, err := encodeIndexKey(sc, ran)
		if err != nil {
			return nil, errors.Trace(err)
		}
		feedbackRanges = append(feedbackRanges, &ranger.Range{LowVal: []types.Datum{types.NewBytesDatum(low)},
			HighVal: []types.Datum{types.NewBytesDatum(high)}, LowExclude: false, HighExclude: true})
	}
	feedbackRanges = fb.Hist().SplitRange(feedbackRanges)
	krs := make([]kv.KeyRange, 0, len(feedbackRanges))
	for _, ran := range feedbackRanges {
		low, high := ran.LowVal[0].GetBytes(), ran.HighVal[0].GetBytes()
		if ran.LowExclude {
			low = kv.Key(low).PrefixNext()
		}
		ran.LowVal[0].SetBytes(low)
		// If this range is split by histogram, then the high val will equal to one bucket's upper bound,
		// since we need to guarantee each range falls inside the exactly one bucket, `PerfixNext` will make the
		// high value greater than upper bound, so we store the high value here.
		ran.HighVal[0].SetBytes(high)
		if !ran.HighExclude {
			high = kv.Key(high).PrefixNext()
		}
		startKey := tablecodec.EncodeIndexSeekKey(tid, idxID, low)
		endKey := tablecodec.EncodeIndexSeekKey(tid, idxID, high)
		krs = append(krs, kv.KeyRange{StartKey: startKey, EndKey: endKey})
	}
	fb.StoreRanges(feedbackRanges)
	return krs, nil
}

func indexRangesToKVWithoutSplit(sc *stmtctx.StatementContext, tid, idxID int64, ranges []*ranger.Range) ([]kv.KeyRange, error) {
	krs := make([]kv.KeyRange, 0, len(ranges))
	for _, ran := range ranges {
		low, high, err := encodeIndexKey(sc, ran)
		if err != nil {
			return nil, errors.Trace(err)
		}
		startKey := tablecodec.EncodeIndexSeekKey(tid, idxID, low)
		endKey := tablecodec.EncodeIndexSeekKey(tid, idxID, high)
		krs = append(krs, kv.KeyRange{StartKey: startKey, EndKey: endKey})
	}
	return krs, nil
}

func encodeIndexKey(sc *stmtctx.StatementContext, ran *ranger.Range) ([]byte, []byte, error) {
	low, err := codec.EncodeKey(sc, nil, ran.LowVal...)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	if ran.LowExclude {
		low = []byte(kv.Key(low).PrefixNext())
	}
	high, err := codec.EncodeKey(sc, nil, ran.HighVal...)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	if !ran.HighExclude {
		high = []byte(kv.Key(high).PrefixNext())
	}

	var hasNull bool
	for _, highVal := range ran.HighVal {
		if highVal.IsNull() {
			hasNull = true
			break
		}
	}

	if hasNull {
		// Append 0 to make unique-key range [null, null] to be a scan rather than point-get.
		high = []byte(kv.Key(high).Next())
	}
	return low, high, nil
}


text:
namespace RadicalResearch.Net.Dns
{
    using System.Net;

    public class AResourceRecord : ResourceRecordBase
    {
        private readonly IPAddress ipAddress;

        public AResourceRecord(DnsQuery query, uint timeToLive, IPAddress ipAddress)
            :base(query, timeToLive)
        {
            this.ipAddress = ipAddress;
        }

        public override RecordType Type
        {
            get
            {
                return RecordType.A;
            }
        }

        public IPAddress IpAddress
        {
            get
            {
                return ipAddress;
            }
        }

        public override byte[] GetData(DnsNameWriter dnsNameWriter)
        {
            return this.ipAddress.GetAddressBytes();
        }
    }
}


text:
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;

namespace FEI.GhostDocHelper
{
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using EnvDTE;
    using System.Linq;
    using Microsoft.VisualStudio.PlatformUI;

    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the
    /// IVsPackage interface and uses the registration attributes defined in the framework to
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the information needed to show this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    // This attribute is needed to let the shell know that this package exposes some menus.
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(GuidList.guidGhostDocHelperPkgString)]
    public sealed class GhostDocHelperPackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require
        /// any Visual Studio service because at this point the package object is created but
        /// not sited yet inside Visual Studio environment. The place to do all the other
        /// initialization is the Initialize method.
        /// </summary>
        public GhostDocHelperPackage()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }

        /////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if ( null != mcs )
            {
                // Create the command for the menu item.
                CommandID menuCommandID = new CommandID(GuidList.guidGhostDocHelperCmdSet, (int)PkgCmdIDList.cmdidDocumentFile);
                MenuCommand menuItem = new MenuCommand(MenuItemCallback, menuCommandID );
                mcs.AddCommand(menuItem);

                // Create the command for the menu item.
                CommandID projectCommandID = new CommandID(GuidList.guidGhostDocPackageProjectCmdSet, (int)PkgCmdIDList.cmdidProjectDocumentThis);
                MenuCommand projectItem = new MenuCommand(MenuItemCallback, projectCommandID);
                mcs.AddCommand(projectItem);

                // Create the command for the menu item.
                CommandID folderCommandID = new CommandID(GuidList.guidGhostDocPackageFolderCmdSet, (int)PkgCmdIDList.cmdidFolderDocumentThis);
                MenuCommand folderItem = new MenuCommand(MenuItemCallback, folderCommandID);
                mcs.AddCommand(folderItem);
            }
        }
        #endregion

        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            var selectionMonitor = (IVsMonitorSelection)GetService(typeof(SVsShellMonitorSelection));

            IntPtr ppHier;
            UInt32 itemid;
            IVsMultiItemSelect multiItemSelect;
            IntPtr ppSC;

            if (
                ErrorHandler.Succeeded(selectionMonitor.GetCurrentSelection(out ppHier, out itemid, out multiItemSelect,
                                                                            out ppSC)))
            {
                if (itemid == VSConstants.VSITEMID_SELECTION)
                {
                    // Multiple selection, do something with all the selected items
                }
                else
                {
                    var hierarchy = Marshal.GetObjectForIUnknown(ppHier) as IVsHierarchy;
                    var projectItem = GetProjectItem(hierarchy, itemid);
                    if (projectItem != null)
                    {
                        if (projectItem.Name.EndsWith(".cs") || projectItem.Name.EndsWith(".vb"))
                        {
                            DocumentFile(projectItem);
                        }
                        else
                        {
                            RecurseItems(projectItem.ProjectItems);
                        }
                    }
                    else
                    {
                        var project = GetProject(hierarchy);
                        if (project != null)
                        {
                            RecurseItems(project.ProjectItems);
                        }
                    }
                }
            }
        }

        private void RecurseItems(ProjectItems projectItems)
        {
            foreach (ProjectItem item in projectItems)
            {
                if (item.Name.EndsWith(".cs") || item.Name.EndsWith(".vb"))
                {
                    DocumentFile(item);
                }
                else
                {
                    RecurseItems(item.ProjectItems);
                }
            }
        }

        private void DocumentFile ( ProjectItem projectItem )
        {

            TextDocument document = null;

            foreach ( CodeElement codeElement in GetCodeElements ( projectItem.FileCodeModel ) )
            {
                if ( document == null )
                {
                    projectItem.Open();
                    if (projectItem.Document != null)
                    {
                        projectItem.Document.Activate();
                    }
                    document = projectItem.Document.Object ( "TextDocument" ) as TextDocument;
                    if ( document == null )
                    {
                        break;
                    }
                }
                document.Selection.GotoLine ( codeElement.StartPoint.Line, true );
                document.Selection.MoveToPoint ( document.CreateEditPoint ( document.Selection.ActivePoint ), true );
                projectItem.DTE.ExecuteCommand ( "Tools.SubMain.GhostDoc.DocumentThis" );
            }
        }

        private IEnumerable<CodeElement> GetCodeElements ( FileCodeModel fileCodeModel )
        {
            var namespaceCodeElement = fileCodeModel.CodeElements.OfType<CodeElement> ().FirstOrDefault ( ce => ce.Kind == vsCMElement.vsCMElementNamespace );
            if ( namespaceCodeElement != null )
            {
                var codeElements = new List<CodeElement> ();
                foreach ( CodeElement codeElement in namespaceCodeElement.Children )
                {
                    if ( codeElement.Kind == vsCMElement.vsCMElementClass || codeElement.Kind == vsCMElement.vsCMElementEnum || codeElement.Kind == vsCMElement.vsCMElementInterface )
                    {
                        codeElements.Add ( codeElement );
                        codeElements.AddRange ( codeElement.Children.OfType<CodeElement> () );
                    }
                }
                return codeElements;
            }
            return Enumerable.Empty<CodeElement> ();
        }

        public ProjectItem GetProjectItem(IVsHierarchy hierarchy, UInt32 prjItemId)
        {
            object prjItemObject = null;
            if (
                ErrorHandler.Succeeded(hierarchy.GetProperty(prjItemId, (int)__VSHPROPID.VSHPROPID_ExtObject,
                                                             out prjItemObject)))
            {
                return prjItemObject as ProjectItem;
            }
            return null;
        }

        public Project GetProject(IVsHierarchy hierarchy)
        {
            object project;

            if (ErrorHandler.Succeeded
                (hierarchy.GetProperty(
                    VSConstants.VSITEMID_ROOT,
                    (int)__VSHPROPID.VSHPROPID_ExtObject,
                    out project)))
            {
                return (project as Project);
            }
            return null;
        }

    }
}


text:
package io.cattle.platform.process.instance;

import io.cattle.platform.core.constants.StoragePoolConstants;
import io.cattle.platform.core.constants.VolumeConstants;
import io.cattle.platform.core.dao.StoragePoolDao;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.core.model.Volume;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPreListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.object.meta.ObjectMetaDataManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;

@Named
public class VolumePreCreate extends AbstractObjectProcessLogic implements ProcessPreListener {

    @Inject
    StoragePoolDao storagePoolDao;

    @Override
    public String[] getProcessNames() {
        return new String[] { "volume.create" };
    }

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        Volume v = (Volume)state.getResource();
        String driver = DataAccessor.fieldString(v, VolumeConstants.FIELD_VOLUME_DRIVER);
        if (StringUtils.isEmpty(driver) || VolumeConstants.LOCAL_DRIVER.equals(driver)) {
            return null;
        }

        List<? extends StoragePool> pools = storagePoolDao.findStoragePoolByDriverName(v.getAccountId(), driver);
        if (pools.size() == 0) {
            return null;
        }
        StoragePool sp = pools.get(0);

        Map<String, Object> data = new HashMap<>();
        List<String> volumeCap = DataAccessor.fieldStringList(sp, StoragePoolConstants.FIELD_VOLUME_CAPABILITIES);
        if (volumeCap != null && volumeCap.size() > 0) {
            data.put(ObjectMetaDataManager.CAPABILITIES_FIELD, volumeCap);
        }

        return new HandlerResult(data);
    }
}


text:
using RouletteWheels
using Base.Test

const algos = [LinearWalk, BisectingSearch, StochasticAcceptance]

###############################################################################
# First, I'll use an intuitive test. I tally 1,000 samples over frequencies
# [5,4,3,2,1]. The tallies should be descending.
###############################################################################

const freqs = [5,4,3,2,1]
const props = freqs / sum(freqs)

function test_descending(tallies)
    sliding_windows = zip(tallies[1:end-1], tallies[2:end])
    @test all(pair -> pair[1] > pair[2], sliding_windows)
end

for algo in algos
    test_descending(rand_tally(algo(freqs), 1000))
    test_descending(rand_tally(algo(props), 1000))
end

###############################################################################
# Now, I'll test sampling following growth. Remember, to call `normalize!`
# prior to sampling, following a `push!`. I should add a statistical test
# for distribution comparisons.
###############################################################################

function test_ascending(tallies)
    sliding_windows = zip(tallies[1:end-1], tallies[2:end])
    @test all(pair -> pair[1] < pair[2], sliding_windows)
end

xs = collect(1:5)

for algo in algos
    selector = algo(xs)
    test_ascending(rand_tally(selector, 1000))

    # Cheap test of iterator interface conformity.
    @test collect(selector) == xs

    # push! then normalize.
    push!(selector, 1)
    @test length(selector) == 6
    normalize!(selector)

    tally = rand_tally(selector, 300000)
    test_ascending(tally[1:5])
    @test tally[6] < tally[2]
end


text:
layout: page
header: no
#
# Content
#
title: "The reliability and validity of passive leg raise and fluid bolus to assess fluid responsiveness in spontaneously breathing emergency department patients."
subheadline: "2014"
teaser: "Duus N, Shogilev DJ, Skibsted S, Zijlstra HW, Fish E, Oren-Grinberg A, Lior Y, Novack V, Talmor D, Kirkegaard H, Shapiro NI."
externalURL: "https://www.ncbi.nlm.nih.gov/pubmed/25262530"
categories: [Publications]
tags: [Emergency Medicine, Pulmonology]
---


text:
/* eslint no-console: "off" */
const noflo = require('noflo');
const debugAction = require('debug')('noflo-ui:action');
const debugActionFull = require('debug')('noflo-ui:action:full');
const debugError = require('debug')('noflo-ui:error');

const sendEvent = (label, a, c) => {
  let action = a;
  let category = c;
  if (action == null) { action = 'click'; }
  if (category == null) { category = 'menu'; }
  if (typeof window.ga !== 'function') { return; }
  window.ga('send', 'event', category, action, label);
};

const registerPageView = (h) => {
  let hash = h;
  if (typeof window.ga !== 'function') { return; }
  if (!hash) { return; }
  if (hash.indexOf('?') !== -1) {
    // Don't send connection details
    [hash] = hash.split('?');
  }
  window.ga('set', 'page', `${window.location.pathname}${window.location.search}#${hash}`);
  window.ga('send', 'pageview');
};

exports.getComponent = () => {
  const c = new noflo.Component();
  c.icon = 'file-text';
  c.inPorts.add('in',
    { datatype: 'all' });
  c.outPorts.add('pass',
    { datatype: 'all' });

  return c.process((input, output) => {
    const data = input.getData('in');
    const { action } = data;
    debugAction(action);
    debugActionFull(action, data.payload);

    if (action.match(/:error$/)) {
      debugError(data.payload);
    }

    switch (action) {
      case 'application:hash':
        registerPageView(data.payload);
        break;
      case 'user:login':
        sendEvent('userLogin');
        break;
      case 'user:logout':
        sendEvent('userLogout');
        break;
      case 'github:open':
        sendEvent('pullGithub', 'navigation', 'url');
        break;
      case 'gist:open':
        sendEvent('pullGist', 'navigation', 'url');
        break;
      case 'main:open':
        sendEvent('openHome', 'navigation', 'url');
        break;
      case 'runtime:start':
        sendEvent('startRuntime', 'click', 'button');
        break;
      case 'runtime:stop':
        sendEvent('stopRuntime', 'click', 'button');
        break;
      case 'runtime:output':
        if (data.payload.output.message) { console.error(data.payload.output.message); }
        break;
      case 'runtime:processerror':
        console.error(data.payload.error.error);
        break;
      case 'runtime:networkerror':
        console.error(data.payload.error);
        break;
      case 'runtime:protocolerror':
        console.error(data.payload.error);
        break;
      case 'runtime:error':
        console.error(data.payload);
        break;
      default:
        // Ignored action
    }

    output.sendDone({
      pass: data,
    });
  });
};


text:
from django.conf.urls import url, include
from .views import LocationApi, IssueView, IssueCommentView, UserSearch, IssueStatusView, CommentDetailView, \
    MentionView, UserInformationApi, UserDetailView, ImageCreateView, UserOrOrgDetailView, OrganisationListView, \
    OrganisationDetailView

app_name = 'toucan_api'

urlpatterns = [
    url(r'^$', LocationApi.as_view()),
    url(
        r'^issue/(?P<issue_id>\d+)/',
        include([
            url(r'^$', IssueView.as_view(), name='issue_detail'),
            url(r'^comment/$', IssueCommentView.as_view(), name='issue_comments'),
            url(r'^status/$', IssueStatusView.as_view(), name='issue_status'),
        ])
    ),
    url(r'^aboutme/$', UserInformationApi.as_view(), name='aboutme'),
    url(r'^about/(?P<name>[\w@.\-]+)/$', UserOrOrgDetailView.as_view(), name='user_or_org_detail'),

    url(r'^user/',
        include([
            url(r'^$', UserSearch.as_view(), name='user_search'),
            url(r'^(?P<username>[\w@.\-]+)/$', UserDetailView.as_view(), name='user_detail'),
        ])
    ),
    url(r'^mentions/$', MentionView.as_view(), name='mention_search'),
    url(r'^comment/(?P<pk>\d+)/$', CommentDetailView.as_view(), name='comment_detail'),
    url(
        r'^media/',
        include([
            url(r'^image/$', ImageCreateView.as_view(), name='image_upload'),
        ])
    ),
    url(r'^organisations/',
        include([
            url(r'^$', OrganisationListView.as_view(), name='organisation_list'),
            url(r'^(?P<pk>\d+)/$', OrganisationDetailView.as_view(), name='organisation_detail')
        ])
    )
]


text:
// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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.
using System;
using Xunit;

namespace Google.Devtools.Clouderrorreporting.V1Beta1.Snippets
{
    /// <summary>
    /// Fixture which is set up at the start of the test run, and torn down at the end.
    /// The Google Cloud Project name is fetched from the TEST_PROJECT environment variable.
    /// </summary>
    [CollectionDefinition(nameof(ErrorReportingFixture))]
    public sealed class ErrorReportingFixture: IDisposable, ICollectionFixture<ErrorReportingFixture>
    {
        private const string ProjectEnvironmentVariable = "TEST_PROJECT";

        public string ProjectId { get; }

        public ErrorReportingFixture()
        {
            ProjectId = Environment.GetEnvironmentVariable(ProjectEnvironmentVariable);
            if (string.IsNullOrEmpty(ProjectId))
            {
                throw new InvalidOperationException(
                    $"Please set the {ProjectEnvironmentVariable} environment variable before running tests");
            }
        }

        public void Dispose()
        {
            // TODO: Delete events? Not ideal...
        }
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.08.01 at 02:54:01 PM PDT
//

package org.yeastrc.ms.writer.mzidentml.jaxb;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 * The table used to translate codons into nucleic acids e.g. by reference to the NCBI translation table.
 *
 *
Java class for TranslationTableType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="TranslationTableType">
 *   <complexContent>
 *     <extension base="{http://psidev.info/psi/pi/mzIdentML/1.1}IdentifiableType">
 *       <sequence>
 *         <element name="cvParam" type="{http://psidev.info/psi/pi/mzIdentML/1.1}CVParamType" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TranslationTableType", propOrder = {
    "cvParam"
})
public class TranslationTableType
    extends IdentifiableType
{

    protected List<CVParamType> cvParam;

    /**
     * Gets the value of the cvParam property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the cvParam property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getCvParam().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CVParamType }
     *
     *
     */
    public List<CVParamType> getCvParam() {
        if (cvParam == null) {
            cvParam = new ArrayList<CVParamType>();
        }
        return this.cvParam;
    }

}


text: Check if a sequence of characters reads the same backward or forward.


text:
<resources>
    <declare-styleable name="MaterialRippleLayout">
        <attr name="mrl_rippleColor" format="color" localization="suggested"/>
        <attr name="mrl_rippleDimension" format="dimension" localization="suggested"/>
        <attr name="mrl_rippleOverlay" format="boolean" localization="suggested"/>
        <attr name="mrl_rippleAlpha" format="float" localization="suggested"/>
        <attr name="mrl_rippleDuration" format="integer" localization="suggested"/>
        <attr name="mrl_rippleFadeDuration" format="integer" localization="suggested"/>
        <attr name="mrl_rippleHover" format="boolean" localization="suggested"/>
        <attr name="mrl_rippleBackground" format="color" localization="suggested"/>
        <attr name="mrl_rippleDelayClick" format="boolean" localization="suggested"/>
        <attr name="mrl_ripplePersistent" format="boolean" localization="suggested"/>
        <attr name="mrl_rippleInAdapter" format="boolean" localization="suggested"/>
        <attr name="mrl_rippleRoundedCorners" format="dimension" localization="suggested"/>
    </declare-styleable>
</resources>


text:
package Messages;
import Users.User;

import java.text.SimpleDateFormat;
import java.util.*;
public class Message
{
    private int code;
    private User sender;
    private User recipient;
    private String subject;
    private String description;
    private Date date;
    public Message(int code, User sender, User recipient, String subject, String description, Date date)
    {
        this.code = code;
        this.sender = sender;
        this.recipient = recipient;
        this.subject = subject;
        this.description = description;
        this.date = date;
    }
    public ArrayList<String> toList()
    {
        return new ArrayList<String>(Arrays.asList(code + "", sender.getCode() + "", recipient.getCode() + "", subject, description,
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)));
    }
    public int getCode()
    {
        return code;
    }
    public void setCode(int code)
    {
        this.code = code;
    }
    public User getSender()
    {
        return sender;
    }
    public void setSender(User sender)
    {
        this.sender = sender;
    }
    public User getRecipient()
    {
        return recipient;
    }
    public void setRecipient(User recipient)
    {
        this.recipient = recipient;
    }
    public String getSubject()
    {
        return subject;
    }
    public void setSubject(String subject)
    {
        this.subject = subject;
    }
    public String getDescription()
    {
        return description;
    }
    public void setDescription(String description)
    {
        this.description = description;
    }
    public Date getDate()
    {
        return date;
    }
    public void setDate(Date date)
    {
        this.date = date;
    }
}


text:
import os

import chardet
from humanfriendly import format_size
import pygments
import pygments.lexers
import pygments.lexers.special
import pygments.formatters
from pygments.util import ClassNotFound
from mako.lookup import TemplateLookup

from mfr.core import extension
from mfr.extensions.codepygments import settings
from mfr.extensions.codepygments import exceptions

class CodePygmentsRenderer(extension.BaseRenderer):

    DEFAULT_LEXER = pygments.lexers.special.TextLexer

    TEMPLATE = TemplateLookup(
        directories=[
            os.path.join(os.path.dirname(__file__), 'templates')
        ]).get_template('viewer.mako')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.metrics.add('pygments_version', pygments.__version__)

    def render(self):
        file_size = os.path.getsize(self.file_path)
        if file_size > settings.MAX_SIZE:
            raise exceptions.FileTooLargeError(
                'Text files larger than {} are not rendered. Please download '
                'the file to view.'.format(format_size(settings.MAX_SIZE, binary=True)),
                file_size=file_size,
                max_size=settings.MAX_SIZE,
                extension=self.metadata.ext,
            )

        with open(self.file_path, 'rb') as fp:
            body = self._render_html(fp, self.metadata.ext)
            return self.TEMPLATE.render(base=self.assets_url, body=body)

    @property
    def file_required(self):
        return True

    @property
    def cache_result(self):
        return True

    def _render_html(self, fp, ext, *args, **kwargs):
        """Generate an html representation of the file
        :param fp: File pointer
        :param ext: File name extension
        :return: Content html
        """
        formatter = pygments.formatters.HtmlFormatter()
        data = fp.read()

        content, encoding = None, 'utf-8'
        try:
            content = data.decode(encoding)
        except UnicodeDecodeError as e:
            detected_encoding = chardet.detect(data)
            encoding = detected_encoding.get('encoding', None)
            if encoding is None:
                raise exceptions.FileDecodingError(
                    message='Unable to detect encoding of source file.',
                    extension=ext,
                    category='undetectable_encoding',
                    code=400,
                )

            try:
                content = data.decode(encoding)
            except UnicodeDecodeError as err:
                raise exceptions.FileDecodingError(
                    message='Unable to decode file as {}.'.format(encoding),
                    extension=ext,
                    category='undecodable',
                    original_exception=err,
                    code=400,
                )

        if content is None:
            raise exceptions.FileDecodingError(
                message='File decoded to undefined using encoding "{}"'.format(encoding),
                extension=ext,
                category='decoded_to_undefined',
                code=500,
            )

        self.metrics.merge({'encoding': encoding, 'default_lexer': False})

        try:
            lexer = pygments.lexers.guess_lexer_for_filename(ext, content)
        except ClassNotFound:
            self.metrics.add('default_lexer', True)
            lexer = self.DEFAULT_LEXER()

        self.metrics.add('lexer', lexer.name)
        return pygments.highlight(content, lexer, formatter)


text:
package com.mcleodmoores.integration.serialization.jodabeans;

import java.util.Map;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.opengamma.util.ArgumentChecker;

import net.finmath.marketdata.model.curves.Curve;
import net.finmath.marketdata.model.curves.Curve.CurveBuilder;
import net.finmath.marketdata.model.curves.Curve.ExtrapolationMethod;
import net.finmath.marketdata.model.curves.Curve.InterpolationEntity;
import net.finmath.marketdata.model.curves.Curve.InterpolationMethod;
import net.finmath.marketdata.model.curves.CurveInterface;

/**
 * Bean for the Finmath curves class {@link net.finmath.marketdata.model.curves.Curve}. The Finmath
 * class does not perform checks on the inputs (e.g. for non-null parameters). However, this bean does
 * perform these checks on construction. It is not necessary to set all of the interpolation information,
 * as null values will indicate that the defaults defined in the Finmath class will be used. However, if
 *
 */
@BeanDefinition
public class CurveBean extends AbstractCurveBean {

  /** The serialization version. */
  private static final long serialVersionUID = 1L;

  /**
   * The times.
   */
  @PropertyDefinition(validate = "notNull")
  private double[] _times;

  /**
   * The values
   */
  @PropertyDefinition(validate = "notNull")
  private double[] _values;

  /**
   * An element is true if the corresponding (times, values) point is a parameter.
   */
  @PropertyDefinition(validate = "notNull")
  private boolean[] _isParameter;

  /**
   * The interpolation method.
   */
  @PropertyDefinition
  private String _interpolationMethod;

  /**
   * The extrapolation method.
   */
  @PropertyDefinition
  private String _extrapolationMethod;

  /**
   * The interpolation entity name.
   */
  @PropertyDefinition
  private String _interpolationEntity;

  /**
   * For the builder.
   */
  /* package */CurveBean() {
    super();
  }

  /**
   * Constructs an instance without parameter or interpolation information.
   * @param name The name of the curve, not null
   * @param referenceDateString The reference date as a string, not null
   * @param times The times, not null
   * @param values The values, not null. Must have the same number of entries as times array.
   */
  public CurveBean(final String name, final String referenceDateString, final double[] times, final double[] values) {
    super(name, referenceDateString);
    setTimes(times);
    setValues(values);
    ArgumentChecker.isTrue(times.length == values.length, "Times and values arrays must have the same number of elements");
  }

  /**
   * Constructs an instance without interpolation information.
   * @param name The name of the curve, not null
   * @param referenceDateString The reference date as a string, not null
   * @param times The times, not null
   * @param values The values, not null. Must have the same number of entries as times array.
   * @param isParameter An element is true if the corresponding (times, values) point is a parameter. Not null, must
   * have the same number of entries as the times array.
   */
  public CurveBean(final String name, final String referenceDateString, final double[] times, final double[] values, final boolean[] isParameter) {
    super(name, referenceDateString);
    setTimes(times);
    setValues(values);
    setIsParameter(isParameter);
    ArgumentChecker.isTrue(times.length == values.length, "Times and values arrays must have the same number of elements");
    ArgumentChecker.isTrue(times.length == isParameter.length, "Times and isParameter arrays must have the same number of elements");
  }

  /**
   * Constructs an instance without parameter information and with interpolation information.
   * @param name The name of the curve, not null
   * @param referenceDateString The reference date as a string, not null
   * @param times The times, not null
   * @param values The values, not null. Must have the same number of entries as times array.
   * have the same number of entries as the times array.
   * @param interpolationMethod The interpolation method name, not null
   * @param extrapolationMethod The extrapolation method name, not null
   * @param interpolationEntity The interpolation entity name, not null
   */
  public CurveBean(final String name, final String referenceDateString, final double[] times, final double[] values, final String interpolationMethod,
      final String extrapolationMethod, final String interpolationEntity) {
    super(name, referenceDateString);
    ArgumentChecker.notNull(interpolationMethod, "interpolationMethod");
    ArgumentChecker.notNull(extrapolationMethod, "extrapolationMethod");
    ArgumentChecker.notNull(interpolationEntity, "interpolationEntity");
    setTimes(times);
    setValues(values);
    ArgumentChecker.isTrue(times.length == values.length, "Times and values arrays must have the same number of elements");
    setInterpolationMethod(interpolationMethod);
    setExtrapolationMethod(extrapolationMethod);
    setInterpolationEntity(interpolationEntity);
    InterpolationMethod.valueOf(interpolationMethod);
    ExtrapolationMethod.valueOf(extrapolationMethod);
    InterpolationEntity.valueOf(interpolationEntity);
  }

  /**
   * Constructs an instance with interpolation information.
   * @param name The name of the curve, not null
   * @param referenceDateString The reference date as a string, not null
   * @param times The times, not null
   * @param values The values, not null. Must have the same number of entries as times array.
   * @param isParameter An element is true if the corresponding (times, values) point is a parameter. Not null, must
   * have the same number of entries as the times array.
   * @param interpolationMethod The interpolation method name, not null
   * @param extrapolationMethod The extrapolation method name, not null
   * @param interpolationEntity The interpolation entity name, not null
   */
  public CurveBean(final String name, final String referenceDateString, final double[] times, final double[] values, final boolean[] isParameter,
      final String interpolationMethod, final String extrapolationMethod, final String interpolationEntity) {
    super(name, referenceDateString);
    ArgumentChecker.notNull(interpolationMethod, "interpolationMethod");
    ArgumentChecker.notNull(extrapolationMethod, "extrapolationMethod");
    ArgumentChecker.notNull(interpolationEntity, "interpolationEntity");
    setTimes(times);
    setValues(values);
    setIsParameter(isParameter);
    ArgumentChecker.isTrue(times.length == values.length, "Times and values arrays must have the same number of elements");
    ArgumentChecker.isTrue(times.length == isParameter.length, "Times and isParameter arrays must have the same number of elements");
    setInterpolationMethod(interpolationMethod);
    setExtrapolationMethod(extrapolationMethod);
    setInterpolationEntity(interpolationEntity);
    InterpolationMethod.valueOf(interpolationMethod);
    ExtrapolationMethod.valueOf(extrapolationMethod);
    InterpolationEntity.valueOf(interpolationEntity);
  }

  @Override
  public CurveInterface buildCurve() {
    final CurveBuilder builder = new Curve.CurveBuilder(getName(), getReferenceDate());
    if (getInterpolationMethod() != null) {
      builder.setInterpolationMethod(InterpolationMethod.valueOf(getInterpolationMethod()));
    }
    if (getExtrapolationMethod() != null) {
      builder.setExtrapolationMethod(ExtrapolationMethod.valueOf(getExtrapolationMethod()));
    }
    if (getInterpolationEntity() != null) {
      builder.setInterpolationEntity(InterpolationEntity.valueOf(getInterpolationEntity()));
    }
    final int length = getTimes().length;
    for (int i = 0; i < length; i++) {
      builder.addPoint(getTimes()[i], getValues()[i], getIsParameter()[i]);
    }
    try {
      return builder.build();
    } catch (final CloneNotSupportedException e) {
      throw new IllegalStateException(e);
    }
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code CurveBean}.
   * @return the meta-bean, not null
   */
  public static CurveBean.Meta meta() {
    return CurveBean.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(CurveBean.Meta.INSTANCE);
  }

  @Override
  public CurveBean.Meta metaBean() {
    return CurveBean.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the times.
   * @return the value of the property, not null
   */
  public double[] getTimes() {
    return _times;
  }

  /**
   * Sets the times.
   * @param times  the new value of the property, not null
   */
  public void setTimes(double[] times) {
    JodaBeanUtils.notNull(times, "times");
    this._times = times;
  }

  /**
   * Gets the the {@code times} property.
   * @return the property, not null
   */
  public final Property<double[]> times() {
    return metaBean().times().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the values
   * @return the value of the property, not null
   */
  public double[] getValues() {
    return _values;
  }

  /**
   * Sets the values
   * @param values  the new value of the property, not null
   */
  public void setValues(double[] values) {
    JodaBeanUtils.notNull(values, "values");
    this._values = values;
  }

  /**
   * Gets the the {@code values} property.
   * @return the property, not null
   */
  public final Property<double[]> values() {
    return metaBean().values().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets an element is true if the corresponding (times, values) point is a parameter.
   * @return the value of the property, not null
   */
  public boolean[] getIsParameter() {
    return _isParameter;
  }

  /**
   * Sets an element is true if the corresponding (times, values) point is a parameter.
   * @param isParameter  the new value of the property, not null
   */
  public void setIsParameter(boolean[] isParameter) {
    JodaBeanUtils.notNull(isParameter, "isParameter");
    this._isParameter = isParameter;
  }

  /**
   * Gets the the {@code isParameter} property.
   * @return the property, not null
   */
  public final Property<boolean[]> isParameter() {
    return metaBean().isParameter().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the interpolation method.
   * @return the value of the property
   */
  public String getInterpolationMethod() {
    return _interpolationMethod;
  }

  /**
   * Sets the interpolation method.
   * @param interpolationMethod  the new value of the property
   */
  public void setInterpolationMethod(String interpolationMethod) {
    this._interpolationMethod = interpolationMethod;
  }

  /**
   * Gets the the {@code interpolationMethod} property.
   * @return the property, not null
   */
  public final Property<String> interpolationMethod() {
    return metaBean().interpolationMethod().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the extrapolation method.
   * @return the value of the property
   */
  public String getExtrapolationMethod() {
    return _extrapolationMethod;
  }

  /**
   * Sets the extrapolation method.
   * @param extrapolationMethod  the new value of the property
   */
  public void setExtrapolationMethod(String extrapolationMethod) {
    this._extrapolationMethod = extrapolationMethod;
  }

  /**
   * Gets the the {@code extrapolationMethod} property.
   * @return the property, not null
   */
  public final Property<String> extrapolationMethod() {
    return metaBean().extrapolationMethod().createProperty(this);
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the interpolation entity name.
   * @return the value of the property
   */
  public String getInterpolationEntity() {
    return _interpolationEntity;
  }

  /**
   * Sets the interpolation entity name.
   * @param interpolationEntity  the new value of the property
   */
  public void setInterpolationEntity(String interpolationEntity) {
    this._interpolationEntity = interpolationEntity;
  }

  /**
   * Gets the the {@code interpolationEntity} property.
   * @return the property, not null
   */
  public final Property<String> interpolationEntity() {
    return metaBean().interpolationEntity().createProperty(this);
  }

  //-----------------------------------------------------------------------
  @Override
  public CurveBean clone() {
    return JodaBeanUtils.cloneAlways(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      CurveBean other = (CurveBean) obj;
      return JodaBeanUtils.equal(getTimes(), other.getTimes()) &&
          JodaBeanUtils.equal(getValues(), other.getValues()) &&
          JodaBeanUtils.equal(getIsParameter(), other.getIsParameter()) &&
          JodaBeanUtils.equal(getInterpolationMethod(), other.getInterpolationMethod()) &&
          JodaBeanUtils.equal(getExtrapolationMethod(), other.getExtrapolationMethod()) &&
          JodaBeanUtils.equal(getInterpolationEntity(), other.getInterpolationEntity()) &&
          super.equals(obj);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = 7;
    hash = hash * 31 + JodaBeanUtils.hashCode(getTimes());
    hash = hash * 31 + JodaBeanUtils.hashCode(getValues());
    hash = hash * 31 + JodaBeanUtils.hashCode(getIsParameter());
    hash = hash * 31 + JodaBeanUtils.hashCode(getInterpolationMethod());
    hash = hash * 31 + JodaBeanUtils.hashCode(getExtrapolationMethod());
    hash = hash * 31 + JodaBeanUtils.hashCode(getInterpolationEntity());
    return hash ^ super.hashCode();
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(224);
    buf.append("CurveBean{");
    int len = buf.length();
    toString(buf);
    if (buf.length() > len) {
      buf.setLength(buf.length() - 2);
    }
    buf.append('}');
    return buf.toString();
  }

  @Override
  protected void toString(StringBuilder buf) {
    super.toString(buf);
    buf.append("times").append('=').append(JodaBeanUtils.toString(getTimes())).append(',').append(' ');
    buf.append("values").append('=').append(JodaBeanUtils.toString(getValues())).append(',').append(' ');
    buf.append("isParameter").append('=').append(JodaBeanUtils.toString(getIsParameter())).append(',').append(' ');
    buf.append("interpolationMethod").append('=').append(JodaBeanUtils.toString(getInterpolationMethod())).append(',').append(' ');
    buf.append("extrapolationMethod").append('=').append(JodaBeanUtils.toString(getExtrapolationMethod())).append(',').append(' ');
    buf.append("interpolationEntity").append('=').append(JodaBeanUtils.toString(getInterpolationEntity())).append(',').append(' ');
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code CurveBean}.
   */
  public static class Meta extends AbstractCurveBean.Meta {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code times} property.
     */
    private final MetaProperty<double[]> _times = DirectMetaProperty.ofReadWrite(
        this, "times", CurveBean.class, double[].class);
    /**
     * The meta-property for the {@code values} property.
     */
    private final MetaProperty<double[]> _values = DirectMetaProperty.ofReadWrite(
        this, "values", CurveBean.class, double[].class);
    /**
     * The meta-property for the {@code isParameter} property.
     */
    private final MetaProperty<boolean[]> _isParameter = DirectMetaProperty.ofReadWrite(
        this, "isParameter", CurveBean.class, boolean[].class);
    /**
     * The meta-property for the {@code interpolationMethod} property.
     */
    private final MetaProperty<String> _interpolationMethod = DirectMetaProperty.ofReadWrite(
        this, "interpolationMethod", CurveBean.class, String.class);
    /**
     * The meta-property for the {@code extrapolationMethod} property.
     */
    private final MetaProperty<String> _extrapolationMethod = DirectMetaProperty.ofReadWrite(
        this, "extrapolationMethod", CurveBean.class, String.class);
    /**
     * The meta-property for the {@code interpolationEntity} property.
     */
    private final MetaProperty<String> _interpolationEntity = DirectMetaProperty.ofReadWrite(
        this, "interpolationEntity", CurveBean.class, String.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, (DirectMetaPropertyMap) super.metaPropertyMap(),
        "times",
        "values",
        "isParameter",
        "interpolationMethod",
        "extrapolationMethod",
        "interpolationEntity");

    /**
     * Restricted constructor.
     */
    protected Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 110364486:  // times
          return _times;
        case -823812830:  // values
          return _values;
        case -1162087009:  // isParameter
          return _isParameter;
        case 374385573:  // interpolationMethod
          return _interpolationMethod;
        case 170930137:  // extrapolationMethod
          return _extrapolationMethod;
        case 153665191:  // interpolationEntity
          return _interpolationEntity;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends CurveBean> builder() {
      return new DirectBeanBuilder<CurveBean>(new CurveBean());
    }

    @Override
    public Class<? extends CurveBean> beanType() {
      return CurveBean.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code times} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<double[]> times() {
      return _times;
    }

    /**
     * The meta-property for the {@code values} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<double[]> values() {
      return _values;
    }

    /**
     * The meta-property for the {@code isParameter} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<boolean[]> isParameter() {
      return _isParameter;
    }

    /**
     * The meta-property for the {@code interpolationMethod} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> interpolationMethod() {
      return _interpolationMethod;
    }

    /**
     * The meta-property for the {@code extrapolationMethod} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> extrapolationMethod() {
      return _extrapolationMethod;
    }

    /**
     * The meta-property for the {@code interpolationEntity} property.
     * @return the meta-property, not null
     */
    public final MetaProperty<String> interpolationEntity() {
      return _interpolationEntity;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 110364486:  // times
          return ((CurveBean) bean).getTimes();
        case -823812830:  // values
          return ((CurveBean) bean).getValues();
        case -1162087009:  // isParameter
          return ((CurveBean) bean).getIsParameter();
        case 374385573:  // interpolationMethod
          return ((CurveBean) bean).getInterpolationMethod();
        case 170930137:  // extrapolationMethod
          return ((CurveBean) bean).getExtrapolationMethod();
        case 153665191:  // interpolationEntity
          return ((CurveBean) bean).getInterpolationEntity();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 110364486:  // times
          ((CurveBean) bean).setTimes((double[]) newValue);
          return;
        case -823812830:  // values
          ((CurveBean) bean).setValues((double[]) newValue);
          return;
        case -1162087009:  // isParameter
          ((CurveBean) bean).setIsParameter((boolean[]) newValue);
          return;
        case 374385573:  // interpolationMethod
          ((CurveBean) bean).setInterpolationMethod((String) newValue);
          return;
        case 170930137:  // extrapolationMethod
          ((CurveBean) bean).setExtrapolationMethod((String) newValue);
          return;
        case 153665191:  // interpolationEntity
          ((CurveBean) bean).setInterpolationEntity((String) newValue);
          return;
      }
      super.propertySet(bean, propertyName, newValue, quiet);
    }

    @Override
    protected void validate(Bean bean) {
      JodaBeanUtils.notNull(((CurveBean) bean)._times, "times");
      JodaBeanUtils.notNull(((CurveBean) bean)._values, "values");
      JodaBeanUtils.notNull(((CurveBean) bean)._isParameter, "isParameter");
      super.validate(bean);
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-2-10.js
 * @description Array.prototype.every applied to Array-like object, 'length' is an inherited accessor property
 */

function testcase() {
        function callbackfn1(val, idx, obj) {
            return val > 10;
        }

        function callbackfn2(val, idx, obj) {
            return val > 11;
        }

        var proto = { };

        Object.defineProperty(proto, "length", {
            get: function () {
                return 2;
            },
            configurable: true
        });

        var Con = function () { };
        Con.prototype = proto;

        var child = new Con();
        child[0] = 12;
        child[1] = 11;
        child[2] = 9;

        return Array.prototype.every.call(child, callbackfn1) &&
            !Array.prototype.every.call(child, callbackfn2);
    }
runTestCase(testcase);


text:
import logging
from irc.schedule import IScheduler
from tempora import schedule
from tempora.schedule import Scheduler

log = logging.getLogger(__name__)

# same as InvokeScheduler from the original implementation,
# but with the extra try-catch
class SafeInvokeScheduler(Scheduler):
    """
    Command targets are functions to be invoked on schedule.
    """

    def run(self, command):
        try:
            command.target()
        except Exception:
            # we do "except Exception" to not catch KeyboardInterrupt and SystemExit (so the bot can properly quit)
            log.exception("Logging an uncaught exception (main thread)")

# same as DefaultScheduler from the original implementation,
# but extends SafeInvokeScheduler instead
class SafeDefaultScheduler(SafeInvokeScheduler, IScheduler):
    def execute_every(self, period, func):
        self.add(schedule.PeriodicCommand.after(period, func))

    def execute_at(self, when, func):
        self.add(schedule.DelayedCommand.at_time(when, func))

    def execute_after(self, delay, func):
        self.add(schedule.DelayedCommand.after(delay, func))


text:
<?php

declare(strict_types=1);

namespace Company\Infrastructure\Doctrine\Entity;

use Administration\Infrastructure\Persistence\DoctrineOrm\Entities\Contact;
use Company\Domain\Model\Company as CompanyModel;
use Company\Domain\Storage\Company\CompanyEntity;
use Core\Domain\Common\Model\VO\ContactUuid;
use Core\Domain\Common\Model\VO\EmailField;
use Core\Domain\Common\Model\VO\NameField;
use Core\Domain\Common\Model\VO\PhoneField;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="company")
 * @ORM\Entity(repositoryClass="Company\Infrastructure\Doctrine\Repository\CompanyRepository")
 */
class Company extends Contact implements CompanyEntity
{
    public function __construct(Contact $contact)
    {
        parent::__construct(
            $contact->uuid,
            $contact->companyName,
            $contact->address,
            $contact->zipCode,
            $contact->town,
            $contact->country,
            $contact->phone,
            $contact->facsimile,
            $contact->email,
            $contact->contactName,
            $contact->cellphone,
            $contact->slug
        );
    }

    public static function fromModel(CompanyModel $companyModel): self
    {
        $contact = Contact::create(
            $companyModel->uuid(),
            $companyModel->companyName(),
            $companyModel->address(),
            $companyModel->zipCode(),
            $companyModel->town(),
            $companyModel->country(),
            $companyModel->phone(),
            $companyModel->facsimile(),
            $companyModel->email(),
            $companyModel->contactName(),
            $companyModel->cellphone(),
            $companyModel->slug()
        );

        return new self($contact);
    }

    public function toModel(): CompanyModel
    {
        return CompanyModel::create(
            ContactUuid::fromString($this->uuid),
            NameField::fromString($this->companyName),
            $this->address,
            $this->zipCode,
            $this->town,
            $this->country,
            PhoneField::fromString($this->phone),
            PhoneField::fromString($this->facsimile),
            EmailField::fromString($this->email),
            $this->contactName,
            PhoneField::fromString($this->cellphone),
        );
    }

    public function update(CompanyModel $companyModel): self
    {
        $this->companyName = $companyModel->companyName();
        $this->address = $companyModel->address();
        $this->zipCode = $companyModel->zipCode();
        $this->town = $companyModel->town();
        $this->country = $companyModel->country();
        $this->phone = $companyModel->phone();
        $this->facsimile = $companyModel->facsimile();
        $this->email = $companyModel->email();
        $this->contactName = $companyModel->contactName();
        $this->cellphone = $companyModel->cellphone();

        return $this;
    }
}


text:
#include "config.h"
#include "PasteboardHelper.h"

#include "Chrome.h"
#include "DataObjectGtk.h"
#include "Frame.h"
#include "GtkVersioning.h"
#include "Page.h"
#include "Pasteboard.h"
#include "TextResourceDecoder.h"
#include <gtk/gtk.h>
#include <wtf/gobject/GOwnPtr.h>

namespace WebCore {

static GdkAtom textPlainAtom;
static GdkAtom markupAtom;
static GdkAtom netscapeURLAtom;
static GdkAtom uriListAtom;
static String gMarkupPrefix;

static void removeMarkupPrefix(String& markup)
{

    // The markup prefix is not harmful, but we remove it from the string anyway, so that
    // we can have consistent results with other ports during the layout tests.
    if (markup.startsWith(gMarkupPrefix))
        markup.remove(0, gMarkupPrefix.length());
}

static void initGdkAtoms()
{
    static gboolean initialized = FALSE;

    if (initialized)
        return;

    initialized = TRUE;

    textPlainAtom = gdk_atom_intern("text/plain;charset=utf-8", FALSE);
    markupAtom = gdk_atom_intern("text/html", FALSE);
    netscapeURLAtom = gdk_atom_intern("_NETSCAPE_URL", FALSE);
    uriListAtom = gdk_atom_intern("text/uri-list", FALSE);
    gMarkupPrefix = "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">";
}

PasteboardHelper::PasteboardHelper()
    : m_targetList(gtk_target_list_new(0, 0))
{
    initGdkAtoms();
}

PasteboardHelper::~PasteboardHelper()
{
    gtk_target_list_unref(m_targetList);
}

void PasteboardHelper::initializeTargetList()
{
    gtk_target_list_add_text_targets(m_targetList, getIdForTargetType(TargetTypeText));
    gtk_target_list_add(m_targetList, markupAtom, 0, getIdForTargetType(TargetTypeMarkup));
    gtk_target_list_add_uri_targets(m_targetList, getIdForTargetType(TargetTypeURIList));
    gtk_target_list_add(m_targetList, netscapeURLAtom, 0, getIdForTargetType(TargetTypeNetscapeURL));
    gtk_target_list_add_image_targets(m_targetList, getIdForTargetType(TargetTypeImage), TRUE);
}

static inline GtkWidget* widgetFromFrame(Frame* frame)
{
    ASSERT(frame);
    Page* page = frame->page();
    ASSERT(page);
    Chrome* chrome = page->chrome();
    ASSERT(chrome);
    PlatformPageClient client = chrome->platformPageClient();
    ASSERT(client);
    return client;
}

GtkClipboard* PasteboardHelper::getCurrentClipboard(Frame* frame)
{
    if (usePrimarySelectionClipboard(widgetFromFrame(frame)))
        return getPrimarySelectionClipboard(frame);
    return getClipboard(frame);
}

GtkClipboard* PasteboardHelper::getClipboard(Frame* frame) const
{
    return gtk_widget_get_clipboard(widgetFromFrame(frame), GDK_SELECTION_CLIPBOARD);
}

GtkClipboard* PasteboardHelper::getPrimarySelectionClipboard(Frame* frame) const
{
    return gtk_widget_get_clipboard(widgetFromFrame(frame), GDK_SELECTION_PRIMARY);
}

GtkTargetList* PasteboardHelper::targetList() const
{
    return m_targetList;
}

static String selectionDataToUTF8String(GtkSelectionData* data)
{
    // g_strndup guards against selection data that is not null-terminated.
    GOwnPtr<gchar> markupString(g_strndup(reinterpret_cast<const char*>(gtk_selection_data_get_data(data)), gtk_selection_data_get_length(data)));
    return String::fromUTF8(markupString.get());
}

void PasteboardHelper::getClipboardContents(GtkClipboard* clipboard)
{
    DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
    ASSERT(dataObject);

    if (gtk_clipboard_wait_is_text_available(clipboard)) {
        GOwnPtr<gchar> textData(gtk_clipboard_wait_for_text(clipboard));
        if (textData)
            dataObject->setText(String::fromUTF8(textData.get()));
    }

    if (gtk_clipboard_wait_is_target_available(clipboard, markupAtom)) {
        if (GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, markupAtom)) {
            String markup(selectionDataToUTF8String(data));
            removeMarkupPrefix(markup);
            dataObject->setMarkup(markup);
            gtk_selection_data_free(data);
        }
    }

    if (gtk_clipboard_wait_is_target_available(clipboard, uriListAtom)) {
        if (GtkSelectionData* data = gtk_clipboard_wait_for_contents(clipboard, uriListAtom)) {
            dataObject->setURIList(selectionDataToUTF8String(data));
            gtk_selection_data_free(data);
        }
    }
}

void PasteboardHelper::fillSelectionData(GtkSelectionData* selectionData, guint info, DataObjectGtk* dataObject)
{
    if (info == getIdForTargetType(TargetTypeText))
        gtk_selection_data_set_text(selectionData, dataObject->text().utf8().data(), -1);

    else if (info == getIdForTargetType(TargetTypeMarkup)) {
        // Some Linux applications refuse to accept pasted markup unless it is
        // prefixed by a content-type meta tag.
        CString markup = (gMarkupPrefix + dataObject->markup()).utf8();
        gtk_selection_data_set(selectionData, markupAtom, 8,
            reinterpret_cast<const guchar*>(markup.data()), markup.length() + 1);

    } else if (info == getIdForTargetType(TargetTypeURIList)) {
        CString uriList = dataObject->uriList().utf8();
        gtk_selection_data_set(selectionData, uriListAtom, 8,
            reinterpret_cast<const guchar*>(uriList.data()), uriList.length() + 1);

    } else if (info == getIdForTargetType(TargetTypeNetscapeURL) && dataObject->hasURL()) {
        String url(dataObject->url());
        String result(url);
        result.append("\n");

        if (dataObject->hasText())
            result.append(dataObject->text());
        else
            result.append(url);

        GOwnPtr<gchar> resultData(g_strdup(result.utf8().data()));
        gtk_selection_data_set(selectionData, netscapeURLAtom, 8,
            reinterpret_cast<const guchar*>(resultData.get()), strlen(resultData.get()) + 1);

    } else if (info == getIdForTargetType(TargetTypeImage))
        gtk_selection_data_set_pixbuf(selectionData, dataObject->image());
}

GtkTargetList* PasteboardHelper::targetListForDataObject(DataObjectGtk* dataObject)
{
    GtkTargetList* list = gtk_target_list_new(0, 0);

    if (dataObject->hasText())
        gtk_target_list_add_text_targets(list, getIdForTargetType(TargetTypeText));

    if (dataObject->hasMarkup())
        gtk_target_list_add(list, markupAtom, 0, getIdForTargetType(TargetTypeMarkup));

    if (dataObject->hasURIList()) {
        gtk_target_list_add_uri_targets(list, getIdForTargetType(TargetTypeURIList));
        gtk_target_list_add(list, netscapeURLAtom, 0, getIdForTargetType(TargetTypeNetscapeURL));
    }

    if (dataObject->hasImage())
        gtk_target_list_add_image_targets(list, getIdForTargetType(TargetTypeImage), TRUE);

    return list;
}

void PasteboardHelper::fillDataObjectFromDropData(GtkSelectionData* data, guint info, DataObjectGtk* dataObject)
{
    if (!gtk_selection_data_get_data(data))
        return;

    GdkAtom target = gtk_selection_data_get_target(data);
    if (target == textPlainAtom)
        dataObject->setText(selectionDataToUTF8String(data));
    else if (target == markupAtom) {
        String markup(selectionDataToUTF8String(data));
        removeMarkupPrefix(markup);
        dataObject->setMarkup(markup);
    } else if (target == uriListAtom) {
        dataObject->setURIList(selectionDataToUTF8String(data));
    } else if (target == netscapeURLAtom) {
        String urlWithLabel(selectionDataToUTF8String(data));
        Vector<String> pieces;
        urlWithLabel.split("\n", pieces);

        // Give preference to text/uri-list here, as it can hold more
        // than one URI but still take  the label if there is one.
        if (!dataObject->hasURIList())
            dataObject->setURIList(pieces[0]);
        if (pieces.size() > 1)
            dataObject->setText(pieces[1]);
    }
}

Vector<GdkAtom> PasteboardHelper::dropAtomsForContext(GtkWidget* widget, GdkDragContext* context)
{
    // Always search for these common atoms.
    Vector<GdkAtom> dropAtoms;
    dropAtoms.append(textPlainAtom);
    dropAtoms.append(markupAtom);
    dropAtoms.append(uriListAtom);
    dropAtoms.append(netscapeURLAtom);

    // For images, try to find the most applicable image type.
    GRefPtr<GtkTargetList> list(gtk_target_list_new(0, 0));
    gtk_target_list_add_image_targets(list.get(), getIdForTargetType(TargetTypeImage), TRUE);
    GdkAtom atom = gtk_drag_dest_find_target(widget, context, list.get());
    if (atom != GDK_NONE)
        dropAtoms.append(atom);

    return dropAtoms;
}

static DataObjectGtk* settingClipboardDataObject = 0;

static void getClipboardContentsCallback(GtkClipboard* clipboard, GtkSelectionData *selectionData, guint info, gpointer data)
{
    DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
    ASSERT(dataObject);
    Pasteboard::generalPasteboard()->helper()->fillSelectionData(selectionData, info, dataObject);
}

static void clearClipboardContentsCallback(GtkClipboard* clipboard, gpointer data)
{
    DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
    ASSERT(dataObject);

    // Only clear the DataObject for this clipboard if we are not currently setting it.
    if (dataObject != settingClipboardDataObject)
        dataObject->clear();

    if (!data)
        return;

    GClosure* callback = static_cast<GClosure*>(data);
    GValue firstArgument = {0, {{0}}};
    g_value_init(&firstArgument, G_TYPE_POINTER);
    g_value_set_pointer(&firstArgument, clipboard);
    g_closure_invoke(callback, 0, 1, &firstArgument, 0);
    g_closure_unref(callback);
}

void PasteboardHelper::writeClipboardContents(GtkClipboard* clipboard, GClosure* callback)
{
    DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
    GtkTargetList* list = targetListForDataObject(dataObject);

    int numberOfTargets;
    GtkTargetEntry* table = gtk_target_table_new_from_list(list, &numberOfTargets);

    if (numberOfTargets > 0 && table) {
        settingClipboardDataObject = dataObject;

        gtk_clipboard_set_with_data(clipboard, table, numberOfTargets,
            getClipboardContentsCallback, clearClipboardContentsCallback, callback);
        gtk_clipboard_set_can_store(clipboard, 0, 0);

        settingClipboardDataObject = 0;

    } else
        gtk_clipboard_clear(clipboard);

    if (table)
        gtk_target_table_free(table, numberOfTargets);
    gtk_target_list_unref(list);
}

}