text:
package apavlov.board;

import apavlov.model.element.Element;
import apavlov.model.element.landscape.Stone;
import apavlov.model.element.unit.Unit;
import java.util.ArrayList;
import java.util.List;

/**
 * The class Board - model game board.
 *
 * @author Pavlov Artem
 * @since 19.01.2018
 */
public class Board {
    /**
     * The constant - default width game board.
     */
    private static final int DEFAULT_WIDTH = 20;

    /**
     * The constant - default height game board.
     */
    private static final int DEFAULT_HEIGHT = 15;

    /**
     * The constant - default min length (width, height) game board.
     */
    private static final int MIN_LENGTH = 5;

    /**
     * The link object work with string.
     */
    private final StringBuilder sb;

    /**
     * The array - game board.
     */
    private final Cell[][] board;

    /**
     * The getter for field board.
     *
     * @return link array game board;
     */
    public Cell[][] getBoard() {
        return this.board;
    }

    /**
     * The constructor for class Board.
     *
     * @param width  - width game board;
     * @param height - height game board;
     */
    private Board(int width, int height) {
        this.board = new Cell[getCorrectHeight(height)][getCorrectWidth(width)];
        this.sb = new StringBuilder();
        createBoard();
    }

    /**
     * The default constructor for class Board.
     */
    public Board() {
        this(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    /**
     * The method return correct value width.
     *
     * @param width - width for check;
     * @return correct width;
     */
    private int getCorrectWidth(int width) {
        if (width < MIN_LENGTH) {
            width = DEFAULT_WIDTH;
        } else if (width % 2 == 0) {
            width++;
        }
        return width;
    }

    /**
     * The method return correct value height.
     *
     * @param height - height for check;
     * @return correct height;
     */
    private int getCorrectHeight(int height) {
        if (height < MIN_LENGTH) {
            height = DEFAULT_HEIGHT;
        } else if (height % 2 == 0) {
            height++;
        }
        return height;
    }

    /**
     * The method create start elements to game board.
     */
    private void createBoard() {
        for (int height = 0; height < this.board.length; height++) {
            for (int width = 0; width < this.board[height].length; width++) {
                if (height == 0 || height == this.board.length - 1 || width == 0 || width == this.board[height].length - 1) {
                    this.board[height][width] = new Cell(new Stone(this.board, new Position(width, height)));
                } else if (width % 2 == 0 && height % 2 == 0) {
                    this.board[height][width] = new Cell(new Stone(this.board, new Position(width, height)));
                } else {
                    this.board[height][width] = new Cell();
                }
            }
        }
    }

    /**
     * The method add new unit to game board.
     *
     * @param unit - unit for addition;
     * @return true, if is add or false;
     */
    public boolean addUnit(Unit unit) {
        boolean result = unit != null;
        if (result) {
            Cell cell = unit.getCell(unit.getPosition());
            if (result = cell != null) {
                result = cell.putUnit(unit);
            }
        }
        return result;
    }

    /**
     * The method add new element to game board.
     *
     * @param element - element for addition;
     * @return true, if is add or false;
     */
    public boolean addElement(Element element) {
        boolean result = element != null;
        if (result) {
            Cell cell = element.getCell(element.getPosition());
            if (result = cell != null) {
                result = cell.putElement(element);
            }
        }
        return result;
    }

    /**
     * The method return list position empty cells.
     *
     * @return list position empty cells;
     */
    public List<Position> getListEmptyCell() {
        List<Position> resultList = new ArrayList<>();
        for (int height = 0; height < this.board.length; height++) {
            for (int width = 0; width < this.board[height].length; width++) {
                if (this.board[height][width].isEmpty()) {
                    resultList.add(new Position(width, height));
                }
            }
        }
        return resultList;
    }

    @Override
    public String toString() {
        sb.delete(0, sb.length());
        for (Cell[] lineX : this.board) {
            for (Cell cell : lineX) {
                sb.append(cell);
            }
            sb.append(System.lineSeparator());
        }
        return sb.toString();
    }
}


text:
import { useFeaturesArchive } from 'hooks/api/getters/useFeaturesArchive/useFeaturesArchive';
import { ArchiveTable } from './ArchiveTable/ArchiveTable';
import { SortingRule } from 'react-table';
import { usePageTitle } from 'hooks/usePageTitle';
import { createLocalStorage } from 'utils/createLocalStorage';

const defaultSort: SortingRule<string> = { id: 'createdAt' };
const { value, setValue } = createLocalStorage(
    'FeaturesArchiveTable:v1',
    defaultSort
);

export const FeaturesArchiveTable = () => {
    usePageTitle('Archive');

    const {
        archivedFeatures = [],
        loading,
        refetchArchived,
    } = useFeaturesArchive();

    return (
        <ArchiveTable
            title="Archive"
            archivedFeatures={archivedFeatures}
            loading={loading}
            storedParams={value}
            setStoredParams={setValue}
            refetch={refetchArchived}
        />
    );
};

redpajama_set_name: RedPajamaGithub


text:
package sqlancer.h2;

import sqlancer.Randomly;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.SQLQueryAdapter;
import sqlancer.h2.H2Provider.H2GlobalState;
import sqlancer.h2.H2Schema.H2Table;

public final class H2DeleteGenerator {

    private H2DeleteGenerator() {
    }

    public static SQLQueryAdapter getQuery(H2GlobalState globalState) {
        StringBuilder sb = new StringBuilder("DELETE FROM ");
        ExpectedErrors errors = new ExpectedErrors();
        H2Table table = globalState.getSchema().getRandomTable(t -> !t.isView());
        sb.append(table.getName());
        if (Randomly.getBoolean()) {
            sb.append(" WHERE ");
            sb.append(H2ToStringVisitor.asString(
                    new H2ExpressionGenerator(globalState).setColumns(table.getColumns()).generateExpression()));
        }
        if (Randomly.getBoolean()) {
            sb.append(" LIMIT ");
            sb.append(H2ToStringVisitor.asString(new H2ExpressionGenerator(globalState).generateConstant()));
        }
        H2Errors.addExpressionErrors(errors);
        H2Errors.addDeleteErrors(errors);
        return new SQLQueryAdapter(sb.toString(), errors);
    }

}


text:
require 'spec_helper'

RSpec.describe MutatorRails::FullMutate do
  let(:object) { described_class.call }

  describe '#call' do
    it 'processes all code' do
      object
    end
  end

  describe '#unprocessed' do
    it 'processes the unprocessed code' do
      described_class.new.unprocessed
    end
  end

  describe '#j1' do
    it 'processes the j1 code' do
      described_class.new.j1
    end
  end

  describe '#changed' do
    it 'processes the changed code' do
      described_class.new.changed
    end
  end
end


text:
from django.contrib import admin
from django.db.models import AutoField
from django.forms import ValidationError
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _

from mezzanine.conf import settings
from mezzanine.core.forms import DynamicInlineAdminForm
from mezzanine.core.models import CONTENT_STATUS_PUBLISHED, Orderable
from mezzanine.utils.urls import admin_url

class DisplayableAdmin(admin.ModelAdmin):
    """
    Admin class for subclasses of the abstract ``Displayable`` model.
    """

    list_display = ("title", "status", "admin_link")
    list_display_links = ("title",)
    list_editable = ("status",)
    list_filter = ("status",)
    search_fields = ("title", "content",)
    date_hierarchy = "publish_date"
    radio_fields = {"status": admin.HORIZONTAL}
    fieldsets = (
        (None, {
            "fields": ["title", "status", ("publish_date", "expiry_date")],
        }),
        (_("Meta data"), {
            "fields": ["_meta_title", "slug",
                       ("description", "gen_description"),
                       "keywords"],
            "classes": ("collapse-closed",)
        }),
    )

    def get_form(self, request, obj=None, **kwargs):
        """
        Add validation for the content field - it's required if status
        is set to published. We patch this method onto the form to avoid
        problems that come up with trying to use a form class. See:
        https://bitbucket.org/stephenmcd/mezzanine/pull-request/23/
        allow-content-field-on-richtextpage-to-be
        """
        form = super(DisplayableAdmin, self).get_form(request, obj, **kwargs)

        def clean_content(form):
            status = form.cleaned_data.get("status")
            content = form.cleaned_data.get("content")
            if status == CONTENT_STATUS_PUBLISHED and not content:
                raise ValidationError(_("This field is required if status "
                                        "is set to published."))
            return content

        form.clean_content = clean_content
        return form

class BaseDynamicInlineAdmin(object):
    """
    Admin inline that uses JS to inject an "Add another" link which
    when clicked, dynamically reveals another fieldset. Also handles
    adding the ``_order`` field and its widget for models that
    subclass ``Orderable``.
    """

    form = DynamicInlineAdminForm
    extra = 20

    def __init__(self, *args, **kwargs):
        super(BaseDynamicInlineAdmin, self).__init__(*args, **kwargs)
        if issubclass(self.model, Orderable):
            fields = self.fields
            if not fields:
                fields = self.model._meta.fields
                exclude = self.exclude or []
                fields = [f.name for f in fields if f.editable and
                    f.name not in exclude and not isinstance(f, AutoField)]
            if "_order" in fields:
                del fields[fields.index("_order")]
                fields.append("_order")
            self.fields = fields

class TabularDynamicInlineAdmin(BaseDynamicInlineAdmin, admin.TabularInline):
    template = "admin/includes/dynamic_inline_tabular.html"

class StackedDynamicInlineAdmin(BaseDynamicInlineAdmin, admin.StackedInline):
    template = "admin/includes/dynamic_inline_stacked.html"

    def __init__(self, *args, **kwargs):
        """
        Stacked dynamic inlines won't work without grappelli
        installed, as the JavaScript in dynamic_inline.js isn't
        able to target each of the inlines to set the value of
        the order field.
        """
        grappelli_name = getattr(settings, "PACKAGE_NAME_GRAPPELLI")
        if grappelli_name not in settings.INSTALLED_APPS:
            error = "StackedDynamicInlineAdmin requires Grappelli installed."
            raise Exception(error)
        super(StackedDynamicInlineAdmin, self).__init__(*args, **kwargs)

class OwnableAdmin(admin.ModelAdmin):
    """
    Admin class for models that subclass the abstract ``Ownable``
    model. Handles limiting the change list to objects owned by the
    logged in user, as well as setting the owner of newly created \
    objects to the logged in user.
    """

    def save_form(self, request, form, change):
        """
        Set the object's owner as the logged in user.
        """
        obj = form.save(commit=False)
        if obj.user_id is None:
            obj.user = request.user
        return super(OwnableAdmin, self).save_form(request, form, change)

    def queryset(self, request):
        """
        Filter the change list by currently logged in user if not a
        superuser.
        """
        qs = super(OwnableAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user__id=request.user.id)

class SingletonAdmin(admin.ModelAdmin):
    """
    Admin class for models that should only contain a single instance
    in the database. Redirect all views to the change view when the
    instance exists, and to the add view when it doesn't.
    """

    def handle_save(self, request, response):
        """
        Handles redirect back to the dashboard when save is clicked
        (eg not save and continue editing), by checking for a redirect
        response, which only occurs if the form is valid.
        """
        form_valid = isinstance(response, HttpResponseRedirect)
        if request.POST.get("_save") and form_valid:
            return redirect("admin:index")
        return response

    def add_view(self, *args, **kwargs):
        """
        Redirect to the change view if the singleton instance exists.
        """
        try:
            singleton = self.model.objects.get()
        except (self.model.DoesNotExist, self.model.MultipleObjectsReturned):
            kwargs.setdefault("extra_context", {})
            kwargs["extra_context"]["singleton"] = True
            response = super(SingletonAdmin, self).add_view(*args, **kwargs)
            return self.handle_save(args[0], response)
        return redirect(admin_url(self.model, "change", singleton.id))

    def changelist_view(self, *args, **kwargs):
        """
        Redirect to the add view if no records exist or the change
        view if the singleton instance exists.
        """
        try:
            singleton = self.model.objects.get()
        except self.model.MultipleObjectsReturned:
            return super(SingletonAdmin, self).changelist_view(*args, **kwargs)
        except self.model.DoesNotExist:
            return redirect(admin_url(self.model, "add"))
        return redirect(admin_url(self.model, "change", singleton.id))

    def change_view(self, *args, **kwargs):
        """
        If only the singleton instance exists, pass ``True`` for
        ``singleton`` into the template which will use CSS to hide
        the "save and add another" button.
        """
        kwargs.setdefault("extra_context", {})
        kwargs["extra_context"]["singleton"] = self.model.objects.count() == 1
        response = super(SingletonAdmin, self).change_view(*args, **kwargs)
        return self.handle_save(args[0], response)


text:
import { reaction } from "mobx"
import { DataSet, IDataSet, toCanonical } from "./data-set"
import { FilteredCases } from "./filtered-cases"

describe("DerivedDataSet", () => {
  let data: IDataSet

  beforeEach(() => {
    data = DataSet.create()
    data.addAttribute({ id: "xId", name: "x" })
    data.addAttribute({ id: "yId", name: "y" })
    data.addCases(toCanonical(data, [
      { __id__: "c1", x: 1, y: 1 }, { __id__: "c2", x: 2 }, { __id__: "c3", y: 3 }
    ]))
  })

  it("handles construction without a filter", () => {
    const filtered = new FilteredCases({ source: data })
    expect(filtered.caseIds.length).toBe(3)
    expect(filtered.caseIds).toEqual(["c1", "c2", "c3"])
    expect(filtered.hasCaseId("c1")).toBe(true)
    expect(filtered.hasCaseId("c3")).toBe(true)
    filtered.destroy()
  })

  it("handles construction with a filter", () => {
    const filtered = new FilteredCases({
      source: data,
      filter: (_data, caseId) => isFinite(_data.getNumeric(caseId, "xId") ?? NaN) &&
                                 isFinite(_data.getNumeric(caseId, "yId") ?? NaN) })
    expect(filtered.caseIds.length).toBe(1)
    expect(filtered.caseIds).toEqual(["c1"])
    expect(filtered.hasCaseId("c1")).toBe(true)
    expect(filtered.hasCaseId("c3")).toBe(false)
    filtered.destroy()
  })

  it("handles filtering when adding/removing cases", () => {
    const filtered = new FilteredCases({
      source: data,
      filter: (_data, caseId) => isFinite(_data.getNumeric(caseId, "xId") ?? NaN) &&
                                 isFinite(_data.getNumeric(caseId, "yId") ?? NaN) })
    data.addCases([{ __id__: "c4", xId: 4, yId: 4 }])
    expect(filtered.caseIds.length).toBe(2)
    expect(filtered.caseIds).toEqual(["c1", "c4"])
    expect(filtered.hasCaseId("c4")).toBe(true)

    data.removeCases(["c1"])
    expect(filtered.caseIds.length).toBe(1)
    expect(filtered.caseIds).toEqual(["c4"])
    expect(filtered.hasCaseId("c1")).toBe(false)

    filtered.destroy()
  })

  it("handles updated values which change filtering (no listener)", () => {
    const filtered = new FilteredCases({
      source: data,
      filter: (_data, caseId) => isFinite(_data.getNumeric(caseId, "xId") ?? NaN) &&
                                 isFinite(_data.getNumeric(caseId, "yId") ?? NaN) })
    data.setCaseValues([{ __id__: "c3", xId: 3 }])
    expect(filtered.caseIds.length).toBe(2)
    expect(filtered.caseIds).toEqual(["c1", "c3"])
    expect(filtered.hasCaseId("c3")).toBe(true)

    data.setCaseValues([{ __id__: "c3", xId: 4 }])
    expect(filtered.caseIds.length).toBe(2)
    expect(filtered.caseIds).toEqual(["c1", "c3"])
    expect(filtered.hasCaseId("c3")).toBe(true)

    data.setCaseValues([{ __id__: "c1", xId: "" }])
    expect(filtered.caseIds.length).toBe(1)
    expect(filtered.caseIds).toEqual(["c3"])
    expect(filtered.hasCaseId("c1")).toBe(false)

    filtered.destroy()
  })

  it("handles updated values which change filtering (listener)", () => {
    const handleSetCaseValues = jest.fn()
    const filtered = new FilteredCases({
      source: data,
      filter: (_data, caseId) => isFinite(_data.getNumeric(caseId, "xId") ?? NaN) &&
                                 isFinite(_data.getNumeric(caseId, "yId") ?? NaN),
      onSetCaseValues: handleSetCaseValues })

    data.setCaseValues([{ __id__: "c3", xId: 3 }])
    expect(handleSetCaseValues).toHaveBeenCalledTimes(1)
    expect(handleSetCaseValues.mock.lastCall[1]).toEqual({ added: ["c3"], changed: [], removed: [] })

    data.setCaseValues([{ __id__: "c3", xId: 4 }])
    expect(handleSetCaseValues).toHaveBeenCalledTimes(2)
    expect(handleSetCaseValues.mock.lastCall[1]).toEqual({ added: [], changed: ["c3"], removed: [] })

    data.setCaseValues([{ __id__: "c1", xId: "" }])
    expect(handleSetCaseValues).toHaveBeenCalledTimes(3)
    expect(handleSetCaseValues.mock.lastCall[1]).toEqual({ added: [], changed: [], removed: ["c1"] })

    data.setCaseValues([{ __id__: "c1", xId: 1 }, { __id__: "c2", xId: 2.2 }, { __id__: "c3", xId: "" }])
    expect(handleSetCaseValues).toHaveBeenCalledTimes(4)
    expect(handleSetCaseValues.mock.lastCall[1]).toEqual({ added: ["c1"], changed: ["c2"], removed: ["c3"] })

    filtered.destroy()
  })

  it("triggers observers on value changes which change filtering", () => {
    const filtered = new FilteredCases({
      source: data,
      filter: (_data, caseId) => isFinite(_data.getNumeric(caseId, "xId") ?? NaN) &&
                                 isFinite(_data.getNumeric(caseId, "yId") ?? NaN) })

    const trigger = jest.fn()
    reaction(() => filtered.caseIds, () => trigger())
    expect(trigger).toHaveBeenCalledTimes(0)

    data.setCaseValues([{ __id__: "c3", xId: 3 }])
    expect(trigger).toHaveBeenCalledTimes(1)
    expect(filtered.caseIds.length).toBe(2)
    expect(filtered.caseIds).toEqual(["c1", "c3"])

    data.setCaseValues([{ __id__: "c1", xId: "" }])
    expect(filtered.caseIds.length).toBe(1)
    expect(filtered.caseIds).toEqual(["c3"])
    expect(trigger).toHaveBeenCalledTimes(2)

    filtered.destroy()
  })
})


text:
import { Join, Separator, Spacer, Text } from "@artsy/palette"
import { FollowArtistPopover_artist$data } from "__generated__/FollowArtistPopover_artist.graphql"
import { FollowArtistPopoverQuery } from "__generated__/FollowArtistPopoverQuery.graphql"
import { SystemContext, SystemContextProps } from "System"
import { SystemQueryRenderer } from "System/Relay/SystemQueryRenderer"
import { useContext } from "react"
import * as React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { Provider } from "unstated"
import {
  FollowArtistPopoverRowFragmentContainer,
  FollowArtistPopoverRowPlaceholder,
} from "./FollowArtistPopoverRow"
import { FollowArtistPopoverState } from "./state"
import { extractNodes } from "Utils/extractNodes"

interface FollowArtistPopoverProps extends SystemContextProps {
  artist: FollowArtistPopover_artist$data
}

const FollowArtistPopover: React.FC<FollowArtistPopoverProps> = ({
  artist: { related },
  user,
}) => {
  const suggestedArtists = extractNodes(related?.suggestedConnection)
  const excludeArtistIds = suggestedArtists.map(({ internalID }) => internalID)

  if (suggestedArtists.length === 0) {
    return (
      <Text variant="sm-display" color="black60">
        No suggestions at this time
      </Text>
    )
  }

  return (
    <Provider inject={[new FollowArtistPopoverState({ excludeArtistIds })]}>
      <Spacer mt={1} />

      <Join separator={<Separator my={1} />}>
        {suggestedArtists.map(artist => {
          return (
            <FollowArtistPopoverRowFragmentContainer
              key={artist.id}
              user={user}
              artist={artist}
            />
          )
        })}
      </Join>
    </Provider>
  )
}

export const FollowArtistPopoverFragmentContainer = createFragmentContainer(
  FollowArtistPopover,
  {
    artist: graphql`
      fragment FollowArtistPopover_artist on Artist {
        related {
          suggestedConnection(
            first: 3
            excludeFollowedArtists: true
            includeFallbackArtists: true
          ) {
            edges {
              node {
                id
                internalID
                ...FollowArtistPopoverRow_artist
              }
            }
          }
        }
      }
    `,
  }
)

export const FollowArtistPopoverQueryRenderer = ({
  artistID,
}: {
  artistID: string
}) => {
  const { relayEnvironment, user } = useContext(SystemContext)

  return (
    <SystemQueryRenderer<FollowArtistPopoverQuery>
      environment={relayEnvironment}
      variables={{ artistID }}
      placeholder={<FollowArtistPopoverPlaceholder />}
      query={graphql`
        query FollowArtistPopoverQuery($artistID: String!) {
          artist(id: $artistID) {
            ...FollowArtistPopover_artist
          }
        }
      `}
      render={({ props }) => {
        if (props?.artist) {
          return (
            <FollowArtistPopoverFragmentContainer
              artist={props.artist}
              user={user}
            />
          )
        }

        return <FollowArtistPopoverPlaceholder />
      }}
    />
  )
}

export const FollowArtistPopoverPlaceholder: React.FC = () => {
  return (
    <>
      <Spacer mt={1} />

      <Join separator={<Separator my={1} />}>
        <FollowArtistPopoverRowPlaceholder />
        <FollowArtistPopoverRowPlaceholder />
        <FollowArtistPopoverRowPlaceholder />
      </Join>
    </>
  )
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<link href="estilo.css" rel="stylesheet" type="text/css">

<title>Henrique Cursos</title>

        <? include_once "inc_topo.php"; ?>

        <? include_once "example.php"; ?>

                 NEW SEITAI

    PROGRAMA DO CURSO

Carga horária  38h

Ministrante: Prof.Hideschi Goto

A técnica de  tratamento de New Seitai foi desenvolvida pelo Mestre Keniti Takagi no Japão  como inovação do Seitai, Técnica Milenar Janopesa de manipulação vertebral. E  possui o seu representante no Brasil: O professor Hideshi Goto.

Método efetivo para tratamento de dores no  corpo, diagnosticando a causa e provendo método de tratamento com ferramentas  próprias, os Martelos. A técnica é suave e seu alívio é imediato.

Eficaz no tratamento de dores no corpo como:

-Coluna vertebral (lombar, Dorsal, cervical e casos de Hérnia de Disco);

-Quadril e Nervo Ciático;

-tendinite (DORT,LER);

-Artrose;

-Enxaqueca etc.

Obs: caso o aluno queira  adquirir os martelos do New Seitai, ao custo de R$1.200,00 ( que pode ser  parcelado em 3 x) deverá informar no ato da inscrição.

      Veja vídeo sobre a técnica:

http://www.youtube.com/watch?v=7oira25Wl6g

http://www.youtube.com/watch?v=uTA204FNCXg

	  				  <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="562" height="63">

                          <param name="movie" value="banners_horizontal_botao_baixo.swf" />

                          <param name="quality" value="high" />

                      	  <param name="wmode" value="transparent" />

                          <embed src="banners_horizontal_botao_baixo.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="562" height="63"></embed>

  				      </object>


text:
using System;
using LiveScoreUpdateSystem.Data.Models.Contracts;
using System.ComponentModel.DataAnnotations.Schema;

namespace LiveScoreUpdateSystem.Data.Models.Abstraction
{
    public class DataModel : IDeletable, IAuditable, IDataModel
    {
        public DataModel()
        {
            this.Id = Guid.NewGuid();
        }

        public Guid Id { get; set; }

        public DateTime? CreatedOn { get; set; }

        public DateTime? ModifiedOn { get; set; }

        [Index]
        public bool IsDeleted { get; set; }

        public DateTime? DeletedOn { get; set; }
    }
}


text:
class SessionsController < ApplicationController

  def new
    redirect_to '/auth/github'
  end

  def create
    @user = User.where(user_params).first_or_create

    if @user
      session[:user_id] = @user.id
      redirect_to profile_path
    else
      redirect_to root_url
    end
  end

  def destroy
    reset_session
    redirect_to root_url
  end

  protected

  def user_params
    request.env['omniauth.auth'].permit(:uid, :provider)
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="ja_JP">
<context>
    <name>ArtNetPlugin</name>
    <message>
        <location filename="artnetplugin.cpp" line="78"/>
        <source>This plugin provides DMX output for devices supporting the ArtNet communication protocol.</source>
        <translation type="unfinished">このプラグインは、ArtNet対応デバイスとの間でDMX信号を送受信します。</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="113"/>
        <source>Output</source>
        <translation type="unfinished">出力</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="117"/>
        <location filename="artnetplugin.cpp" line="266"/>
        <source>Status: Not open</source>
        <translation type="unfinished">状態: 未接続</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="120"/>
        <location filename="artnetplugin.cpp" line="269"/>
        <source>Status: Open</source>
        <translation type="unfinished">状態: 接続</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="122"/>
        <source>Nodes discovered: </source>
        <translation type="unfinished">見つかったノード:</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="125"/>
        <source>Packets sent: </source>
        <translation type="unfinished">送信されたパケット:</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="262"/>
        <source>Input</source>
        <translation type="unfinished">入力</translation>
    </message>
    <message>
        <location filename="artnetplugin.cpp" line="271"/>
        <source>Packets received: </source>
        <translation type="unfinished">受信したパケット:</translation>
    </message>
</context>
<context>
    <name>ConfigureArtNet</name>
    <message>
        <location filename="configureartnet.ui" line="14"/>
        <source>Configure ArtNet Plugin</source>
        <translation type="unfinished">ArtNetプラグイン設定</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="24"/>
        <source>Universes Configuration</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="30"/>
        <source>Configuration of the patched universes</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="38"/>
        <source>Interface</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="43"/>
        <source>Universe</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="48"/>
        <source>IP Address</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="53"/>
        <source>ArtNet Universe</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="58"/>
        <source>Transmission Mode</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="67"/>
        <source>Nodes Tree</source>
        <translation type="unfinished">Nodes Tree</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="77"/>
        <source>IP</source>
        <translation type="unfinished">IP</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="82"/>
        <source>Short Name</source>
        <translation type="unfinished">Short Name</translation>
    </message>
    <message>
        <location filename="configureartnet.ui" line="87"/>
        <source>Long Name</source>
        <translation type="unfinished">Long Name</translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="71"/>
        <source>%1 nodes</source>
        <translation type="unfinished">%1 nodes</translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="111"/>
        <source>Inputs</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="117"/>
        <source>Outputs</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="157"/>
        <source>Full</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="configureartnet.cpp" line="158"/>
        <source>Partial</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
package main

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/lxc/lxd/shared"
)

var networkConfigKeys = map[string]func(value string) error{
	"bridge.driver": func(value string) error {
		return shared.IsOneOf(value, []string{"native", "openvswitch"})
	},
	"bridge.external_interfaces": func(value string) error {
		if value == "" {
			return nil
		}

		for _, entry := range strings.Split(value, ",") {
			entry = strings.TrimSpace(entry)
			if networkValidName(entry) != nil {
				return fmt.Errorf("Invalid interface name '%s'", entry)
			}
		}

		return nil
	},
	"bridge.mtu": shared.IsInt64,
	"bridge.mode": func(value string) error {
		return shared.IsOneOf(value, []string{"standard", "fan"})
	},

	"fan.overlay_subnet": networkValidNetworkV4,
	"fan.underlay_subnet": func(value string) error {
		if value == "auto" {
			return nil
		}

		return networkValidNetworkV4(value)
	},
	"fan.type": func(value string) error {
		return shared.IsOneOf(value, []string{"vxlan", "ipip"})
	},

	"tunnel.TARGET.protocol": func(value string) error {
		return shared.IsOneOf(value, []string{"gre", "vxlan"})
	},
	"tunnel.TARGET.local":     networkValidAddressV4,
	"tunnel.TARGET.remote":    networkValidAddressV4,
	"tunnel.TARGET.port":      networkValidPort,
	"tunnel.TARGET.group":     networkValidAddressV4,
	"tunnel.TARGET.id":        shared.IsInt64,
	"tunnel.TARGET.interface": networkValidName,

	"ipv4.address": func(value string) error {
		if shared.IsOneOf(value, []string{"none", "auto"}) == nil {
			return nil
		}

		return networkValidAddressCIDRV4(value)
	},
	"ipv4.firewall":     shared.IsBool,
	"ipv4.nat":          shared.IsBool,
	"ipv4.dhcp":         shared.IsBool,
	"ipv4.dhcp.gateway": networkValidAddressV4,
	"ipv4.dhcp.expiry":  shared.IsAny,
	"ipv4.dhcp.ranges":  shared.IsAny,
	"ipv4.routes":       shared.IsAny,
	"ipv4.routing":      shared.IsBool,

	"ipv6.address": func(value string) error {
		if shared.IsOneOf(value, []string{"none", "auto"}) == nil {
			return nil
		}

		return networkValidAddressCIDRV6(value)
	},
	"ipv6.firewall":      shared.IsBool,
	"ipv6.nat":           shared.IsBool,
	"ipv6.dhcp":          shared.IsBool,
	"ipv6.dhcp.expiry":   shared.IsAny,
	"ipv6.dhcp.stateful": shared.IsBool,
	"ipv6.dhcp.ranges":   shared.IsAny,
	"ipv6.routes":        shared.IsAny,
	"ipv6.routing":       shared.IsBool,

	"dns.domain": shared.IsAny,
	"dns.mode": func(value string) error {
		return shared.IsOneOf(value, []string{"dynamic", "managed", "none"})
	},

	"raw.dnsmasq": shared.IsAny,
}

func networkValidateConfig(name string, config map[string]string) error {
	bridgeMode := config["bridge.mode"]

	if bridgeMode == "fan" && len(name) > 11 {
		return fmt.Errorf("Network name too long to use with the FAN (must be 11 characters or less)")
	}

	for k, v := range config {
		key := k

		// User keys are free for all
		if strings.HasPrefix(key, "user.") {
			continue
		}

		// Tunnel keys have the remote name in their name, so extract the real key
		if strings.HasPrefix(key, "tunnel.") {
			fields := strings.Split(key, ".")
			if len(fields) != 3 {
				return fmt.Errorf("Invalid network configuration key: %s", k)
			}

			if len(name)+len(fields[1]) > 14 {
				return fmt.Errorf("Network name too long for tunnel interface: %s-%s", name, fields[1])
			}

			key = fmt.Sprintf("tunnel.TARGET.%s", fields[2])
		}

		// Then validate
		validator, ok := networkConfigKeys[key]
		if !ok {
			return fmt.Errorf("Invalid network configuration key: %s", k)
		}

		err := validator(v)
		if err != nil {
			return err
		}

		// Bridge mode checks
		if bridgeMode == "fan" && strings.HasPrefix(key, "ipv4.") && v != "" {
			return fmt.Errorf("IPv4 configuration may not be set when in 'fan' mode")
		}

		if bridgeMode == "fan" && strings.HasPrefix(key, "ipv6.") && v != "" {
			return fmt.Errorf("IPv6 configuration may not be set when in 'fan' mode")
		}

		if bridgeMode != "fan" && strings.HasPrefix(key, "fan.") && v != "" {
			return fmt.Errorf("FAN configuration may only be set when in 'fan' mode")
		}

		// MTU checks
		if key == "bridge.mtu" && v != "" {
			mtu, err := strconv.ParseInt(v, 10, 64)
			if err != nil {
				return fmt.Errorf("Invalid value for an integer: %s", v)
			}

			ipv6 := config["ipv6.address"]
			if ipv6 != "" && ipv6 != "none" && mtu < 1280 {
				return fmt.Errorf("The minimum MTU for an IPv6 network is 1280")
			}

			ipv4 := config["ipv4.address"]
			if ipv4 != "" && ipv4 != "none" && mtu < 68 {
				return fmt.Errorf("The minimum MTU for an IPv4 network is 68")
			}

			if config["bridge.mode"] == "fan" {
				if config["fan.type"] == "ipip" {
					if mtu > 1480 {
						return fmt.Errorf("Maximum MTU for an IPIP FAN bridge is 1480")
					}
				} else {
					if mtu > 1450 {
						return fmt.Errorf("Maximum MTU for a VXLAN FAN bridge is 1450")
					}
				}
			}
		}
	}

	return nil
}

func networkFillAuto(config map[string]string) error {
	if config["ipv4.address"] == "auto" {
		subnet, err := networkRandomSubnetV4()
		if err != nil {
			return err
		}

		config["ipv4.address"] = subnet
	}

	if config["ipv6.address"] == "auto" {
		subnet, err := networkRandomSubnetV6()
		if err != nil {
			return err
		}

		config["ipv6.address"] = subnet
	}

	if config["fan.underlay_subnet"] == "auto" {
		subnet, _, err := networkDefaultGatewaySubnetV4()
		if err != nil {
			return err
		}

		config["fan.underlay_subnet"] = subnet.String()
	}

	return nil
}


text:
const rootPreview = require('../../../.storybook/preview');

export const parameters = {
    ...rootPreview.preview
};


text:
'use strict';

exports.find = function(req, res, next){
  req.query.title = req.query.title ? req.query.title : '';
  req.query.limit = req.query.limit ? parseInt(req.query.limit, null) : 20;
  req.query.page = req.query.page ? parseInt(req.query.page, null) : 1;
  req.query.sort = req.query.sort ? req.query.sort : '_id';

  var filters = {username:req.user.username};
  if (req.query.username) {
    filters.username = new RegExp('^.*?'+ req.query.username +'.*$', 'i');
  }

  req.app.db.models.Blog.pagedFind({
    filters: filters,
    keys: 'title description username',
    limit: req.query.limit,
    page: req.query.page,
    sort: req.query.sort
  }, function(err, results) {
    if (err) {
      return next(err);
    }

    if (req.xhr) {
      res.header("Cache-Control", "no-cache, no-store, must-revalidate");
      results.filters = req.query;
      res.send(results);
    }
    else {
      results.filters = req.query;
      res.render('myblogs/index', { data: results.data });
    }
  });
};


text:
"""Operations run inside the report directory to extract data.

:copyright: Copyright (c) 2019 RadiaSoft LLC.  All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcompat
from pykern import pkio
from pykern import pkjson
from pykern.pkcollections import PKDict
from pykern.pkdebug import pkdp, pkdexc, pkdc, pkdlog
from sirepo import job
from sirepo import simulation_db
from sirepo.template import template_common
import contextlib
import re
import requests
import signal
import sirepo.sim_data
import sirepo.template
import sirepo.util
import subprocess
import sys
import time

_MAX_FASTCGI_EXCEPTIONS = 3

_MAX_FASTCGI_MSG = int(1e8)

def default_command(in_file):
    """Reads `in_file` passes to `msg.jobCmd`

    Must be called in run_dir

    Writes its output on stdout.

    Args:
        in_file (str): json parsed to msg
    Returns:
        str: json output of command, e.g. status msg
    """
    try:
        f = pkio.py_path(in_file)
        msg = pkjson.load_any(f)
        # TODO(e-carlin): find common place to serialize/deserialize paths
        msg.runDir = pkio.py_path(msg.runDir)
        f.remove()
        res = globals()["_do_" + msg.jobCmd](
            msg, sirepo.template.import_module(msg.simulationType)
        )
        if res is None:
            return
        r = PKDict(res).pksetdefault(state=job.COMPLETED)
    except Exception as e:
        r = _maybe_parse_user_alert(e)
    return pkjson.dump_pretty(r, pretty=False)

class _AbruptSocketCloseError(Exception):
    """Fastcgi unix domain socket closed"""

    pass

def _background_percent_complete(msg, template, is_running):
    return template.background_percent_complete(
        sirepo.sim_data.get_class(msg.simulationType).parse_model(msg.data),
        msg.runDir,
        is_running,
    ).pksetdefault(
        # TODO(robnagler) this is incorrect, because we want to see file updates
        #   not just our polling frequency
        lastUpdateTime=lambda: _mtime_or_now(msg.runDir),
        frameCount=0,
        percentComplete=0.0,
    )

def _dispatch_compute(msg):
    try:
        return getattr(template_common, f"{msg.jobCmd}_dispatch")(msg.data)
    except Exception as e:
        return _maybe_parse_user_alert(e)

def _do_cancel(msg, template):
    if hasattr(template, "remove_last_frame"):
        template.remove_last_frame(msg.runDir)
    return PKDict()

def _do_compute(msg, template):
    msg.runDir = pkio.py_path(msg.runDir)
    with msg.runDir.join(template_common.RUN_LOG).open("w") as run_log:
        p = subprocess.Popen(
            _do_prepare_simulation(msg, template).cmd,
            stdout=run_log,
            stderr=run_log,
        )
    while True:
        for j in range(20):
            time.sleep(0.1)
            r = p.poll()
            i = r is None
            if not i:
                if r == -signal.SIGKILL:
                    return PKDict(
                        state=job.ERROR,
                        error="Terminated Process. Possibly ran out of memory",
                    )
                break
        if msg.isParallel:
            # TODO(e-carlin): This has a potential to fail. We likely
            # don't want the job to fail in this case
            _write_parallel_status(msg, template, i)
        if i:
            continue
        return _on_do_compute_exit(
            r == 0,
            msg.isParallel,
            template,
            msg.runDir,
        )

def _do_analysis_job(msg, template):
    return _dispatch_compute(msg)

def _do_download_data_file(msg, template):
    try:
        r = template.get_data_file(
            msg.runDir,
            msg.analysisModel,
            msg.frame,
            options=PKDict(suffix=msg.suffix),
        )
        if not isinstance(r, PKDict):
            if isinstance(r, str):
                r = msg.runDir.join(r, abs=1)
            r = PKDict(filename=r)
        u = r.get("uri")
        if u is None:
            u = r.filename.basename
        c = r.get("content")
        if c is None:
            c = (
                pkcompat.to_bytes(pkio.read_text(r.filename))
                if u.endswith((".py", ".txt", ".csv"))
                else r.filename.read_binary()
            )
            e = _validate_msg(c)
            if e:
                return e
        requests.put(
            msg.dataFileUri + u,
            data=c,
            verify=job.cfg().verify_tls,
        ).raise_for_status()
        return PKDict()
    except Exception as e:
        return PKDict(state=job.ERROR, error=e, stack=pkdexc())

def _do_fastcgi(msg, template):
    import socket

    @contextlib.contextmanager
    def _update_run_dir_and_maybe_chdir(msg):
        msg.runDir = pkio.py_path(msg.runDir) if msg.runDir else None
        with pkio.save_chdir(
            msg.runDir,
        ) if msg.runDir else contextlib.nullcontext():
            yield

    def _recv():
        m = b""
        while True:
            r = s.recv(_MAX_FASTCGI_MSG)
            if not r:
                pkdlog(
                    "job_cmd should be killed before socket is closed msg={}",
                    msg,
                )
                raise _AbruptSocketCloseError()
            if len(m) + len(r) > _MAX_FASTCGI_MSG:
                raise RuntimeError("message larger than {} bytes", _MAX_FASTCGI_MSG)
            m += r
            if m[-1:] == b"\n":
                return pkjson.load_any(m)

    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.connect(msg.fastcgiFile)
    c = 0
    while True:
        try:
            m = _recv()
            if not m:
                return
            with _update_run_dir_and_maybe_chdir(m):
                r = globals()["_do_" + m.jobCmd](
                    m, sirepo.template.import_module(m.simulationType)
                )
            r = PKDict(r).pksetdefault(state=job.COMPLETED)
            c = 0
        except _AbruptSocketCloseError:
            return
        except Exception as e:
            assert (
                c < _MAX_FASTCGI_EXCEPTIONS
            ), "too many fastgci exceptions {}. Most recent error={}".format(c, e)
            c += 1
            r = _maybe_parse_user_alert(e)
        s.sendall(_validate_msg_and_jsonl(r))

def _do_get_simulation_frame(msg, template):
    try:
        return template_common.sim_frame_dispatch(
            msg.data.copy().pkupdate(run_dir=msg.runDir),
        )
    except Exception as e:
        return _maybe_parse_user_alert(e, error="report not generated")

def _do_prepare_simulation(msg, template):
    if "libFileList" in msg:
        msg.data.libFileList = msg.libFileList
    return PKDict(
        cmd=simulation_db.prepare_simulation(
            msg.data,
            msg.runDir,
        )[0],
    )

def _do_sbatch_status(msg, template):
    s = pkio.py_path(msg.stopSentinel)
    while True:
        if s.exists():
            if job.COMPLETED not in s.read():
                # told to stop for an error or otherwise
                return None
            _write_parallel_status(msg, template, False)
            pkio.unchecked_remove(s)
            return PKDict(state=job.COMPLETED)
        _write_parallel_status(msg, template, True)
        time.sleep(msg.nextRequestSeconds)
    # DOES NOT RETURN

def _do_sequential_result(msg, template):
    r = template_common.read_sequential_result(msg.runDir)
    # Read this first: https://github.com/radiasoft/sirepo/issues/2007
    if hasattr(template, "prepare_sequential_output_file") and "models" in msg.data:
        template.prepare_sequential_output_file(msg.runDir, msg.data)
        r = template_common.read_sequential_result(msg.runDir)
    return r

def _do_stateful_compute(msg, template):
    return _dispatch_compute(msg)

def _do_stateless_compute(msg, template):
    return _dispatch_compute(msg)

def _maybe_parse_user_alert(exception, error=None):
    e = error or str(exception)
    if isinstance(exception, sirepo.util.UserAlert):
        e = exception.sr_args.error
    return PKDict(state=job.ERROR, error=e, stack=pkdexc())

def _on_do_compute_exit(success_exit, is_parallel, template, run_dir):
    # locals() must be called before anything else so we only get the function
    # arguments
    kwargs = locals()

    def _failure_exit():
        a = _post_processing()
        if not a:
            f = run_dir.join(template_common.RUN_LOG)
            if f.exists():
                a = _parse_python_errors(pkio.read_text(f))
        if not a:
            a = "non-zero exit code"
        return PKDict(state=job.ERROR, error=a)

    def _post_processing():
        if hasattr(template, "post_execution_processing"):
            return template.post_execution_processing(**kwargs)
        return None

    def _success_exit():
        return PKDict(
            state=job.COMPLETED,
            alert=_post_processing(),
        )

    try:
        return _success_exit() if success_exit else _failure_exit()
    except Exception as e:
        return PKDict(state=job.ERROR, error=e, stack=pkdexc())

def _mtime_or_now(path):
    """mtime for path if exists else time.time()

    Args:
        path (py.path):

    Returns:
        int: modification time
    """
    return int(path.mtime() if path.exists() else time.time())

def _parse_python_errors(text):
    m = re.search(
        r"^Traceback .*?^\w*(?:Error|Exception):\s*(.*)",
        text,
        re.MULTILINE | re.DOTALL,
    )
    if m:
        return re.sub(r"\nTraceback.*$", "", m.group(1), flags=re.S).strip()
    return ""

def _validate_msg(msg):
    if len(msg) >= job.cfg().max_message_bytes:
        return PKDict(state=job.COMPLETED, error="Response is too large to send")
    return None

def _validate_msg_and_jsonl(msg):
    m = pkjson.dump_bytes(msg)
    r = _validate_msg(m)
    if r:
        m = pkjson.dump_bytes(r)
    return m + b"\n"

def _write_parallel_status(msg, template, is_running):
    sys.stdout.write(
        pkjson.dump_pretty(
            PKDict(
                state=job.RUNNING,
                parallelStatus=_background_percent_complete(msg, template, is_running),
            ),
            pretty=False,
        )
        + "\n",
    )


text:
package jaeger

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
	"log"
	"net/url"
	"strings"
	"sync"

	opentracing "github.com/opentracing/opentracing-go"
)

// Injector is responsible for injecting SpanContext instances in a manner suitable
// for propagation via a format-specific "carrier" object. Typically the
// injection will take place across an RPC boundary, but message queues and
// other IPC mechanisms are also reasonable places to use an Injector.
type Injector interface {
	// Inject takes `SpanContext` and injects it into `carrier`. The actual type
	// of `carrier` depends on the `format` passed to `Tracer.Inject()`.
	//
	// Implementations may return opentracing.ErrInvalidCarrier or any other
	// implementation-specific error if injection fails.
	Inject(ctx SpanContext, carrier interface{}) error
}

// Extractor is responsible for extracting SpanContext instances from a
// format-specific "carrier" object. Typically the extraction will take place
// on the server side of an RPC boundary, but message queues and other IPC
// mechanisms are also reasonable places to use an Extractor.
type Extractor interface {
	// Extract decodes a SpanContext instance from the given `carrier`,
	// or (nil, opentracing.ErrSpanContextNotFound) if no context could
	// be found in the `carrier`.
	Extract(carrier interface{}) (SpanContext, error)
}

type textMapPropagator struct {
	headerKeys  *HeadersConfig
	metrics     Metrics
	encodeValue func(string) string
	decodeValue func(string) string
}

func newTextMapPropagator(headerKeys *HeadersConfig, metrics Metrics) *textMapPropagator {
	return &textMapPropagator{
		headerKeys: headerKeys,
		metrics:    metrics,
		encodeValue: func(val string) string {
			return val
		},
		decodeValue: func(val string) string {
			return val
		},
	}
}

func newHTTPHeaderPropagator(headerKeys *HeadersConfig, metrics Metrics) *textMapPropagator {
	return &textMapPropagator{
		headerKeys: headerKeys,
		metrics:    metrics,
		encodeValue: func(val string) string {
			return url.QueryEscape(val)
		},
		decodeValue: func(val string) string {
			// ignore decoding errors, cannot do anything about them
			if v, err := url.QueryUnescape(val); err == nil {
				return v
			}
			return val
		},
	}
}

type binaryPropagator struct {
	tracer  *Tracer
	buffers sync.Pool
}

func newBinaryPropagator(tracer *Tracer) *binaryPropagator {
	return &binaryPropagator{
		tracer:  tracer,
		buffers: sync.Pool{New: func() interface{} { return &bytes.Buffer{} }},
	}
}

func (p *textMapPropagator) Inject(
	sc SpanContext,
	abstractCarrier interface{},
) error {
	textMapWriter, ok := abstractCarrier.(opentracing.TextMapWriter)
	if !ok {
		return opentracing.ErrInvalidCarrier
	}

	// Do not encode the string with trace context to avoid accidental double-encoding
	// if people are using opentracing < 0.10.0. Our colon-separated representation
	// of the trace context is already safe for HTTP headers.
	textMapWriter.Set(p.headerKeys.TraceContextHeaderName, sc.String())
	for k, v := range sc.baggage {
		safeKey := p.addBaggageKeyPrefix(k)
		safeVal := p.encodeValue(v)
		textMapWriter.Set(safeKey, safeVal)
	}
	return nil
}

func (p *textMapPropagator) Extract(abstractCarrier interface{}) (SpanContext, error) {
	textMapReader, ok := abstractCarrier.(opentracing.TextMapReader)
	if !ok {
		return emptyContext, opentracing.ErrInvalidCarrier
	}
	var ctx SpanContext
	var baggage map[string]string
	err := textMapReader.ForeachKey(func(rawKey, value string) error {
		key := strings.ToLower(rawKey) // TODO not necessary for plain TextMap
		if key == p.headerKeys.TraceContextHeaderName {
			var err error
			safeVal := p.decodeValue(value)
			if ctx, err = ContextFromString(safeVal); err != nil {
				return err
			}
		} else if key == p.headerKeys.JaegerDebugHeader {
			ctx.debugID = p.decodeValue(value)
		} else if key == p.headerKeys.JaegerBaggageHeader {
			if baggage == nil {
				baggage = make(map[string]string)
			}
			for k, v := range p.parseCommaSeparatedMap(value) {
				baggage[k] = v
			}
		} else if strings.HasPrefix(key, p.headerKeys.TraceBaggageHeaderPrefix) {
			if baggage == nil {
				baggage = make(map[string]string)
			}
			safeKey := p.removeBaggageKeyPrefix(key)
			safeVal := p.decodeValue(value)
			baggage[safeKey] = safeVal
		}
		return nil
	})
	if err != nil {
		p.metrics.DecodingErrors.Inc(1)
		return emptyContext, err
	}
	if !ctx.traceID.IsValid() && ctx.debugID == "" && len(baggage) == 0 {
		return emptyContext, opentracing.ErrSpanContextNotFound
	}
	ctx.baggage = baggage
	return ctx, nil
}

func (p *binaryPropagator) Inject(
	sc SpanContext,
	abstractCarrier interface{},
) error {
	carrier, ok := abstractCarrier.(io.Writer)
	if !ok {
		return opentracing.ErrInvalidCarrier
	}

	// Handle the tracer context
	if err := binary.Write(carrier, binary.BigEndian, sc.traceID); err != nil {
		return err
	}
	if err := binary.Write(carrier, binary.BigEndian, sc.spanID); err != nil {
		return err
	}
	if err := binary.Write(carrier, binary.BigEndian, sc.parentID); err != nil {
		return err
	}
	if err := binary.Write(carrier, binary.BigEndian, sc.flags); err != nil {
		return err
	}

	// Handle the baggage items
	if err := binary.Write(carrier, binary.BigEndian, int32(len(sc.baggage))); err != nil {
		return err
	}
	for k, v := range sc.baggage {
		if err := binary.Write(carrier, binary.BigEndian, int32(len(k))); err != nil {
			return err
		}
		io.WriteString(carrier, k)
		if err := binary.Write(carrier, binary.BigEndian, int32(len(v))); err != nil {
			return err
		}
		io.WriteString(carrier, v)
	}

	return nil
}

func (p *binaryPropagator) Extract(abstractCarrier interface{}) (SpanContext, error) {
	carrier, ok := abstractCarrier.(io.Reader)
	if !ok {
		return emptyContext, opentracing.ErrInvalidCarrier
	}
	var ctx SpanContext

	if err := binary.Read(carrier, binary.BigEndian, &ctx.traceID); err != nil {
		return emptyContext, opentracing.ErrSpanContextCorrupted
	}
	if err := binary.Read(carrier, binary.BigEndian, &ctx.spanID); err != nil {
		return emptyContext, opentracing.ErrSpanContextCorrupted
	}
	if err := binary.Read(carrier, binary.BigEndian, &ctx.parentID); err != nil {
		return emptyContext, opentracing.ErrSpanContextCorrupted
	}
	if err := binary.Read(carrier, binary.BigEndian, &ctx.flags); err != nil {
		return emptyContext, opentracing.ErrSpanContextCorrupted
	}

	// Handle the baggage items
	var numBaggage int32
	if err := binary.Read(carrier, binary.BigEndian, &numBaggage); err != nil {
		return emptyContext, opentracing.ErrSpanContextCorrupted
	}
	if iNumBaggage := int(numBaggage); iNumBaggage > 0 {
		ctx.baggage = make(map[string]string, iNumBaggage)
		buf := p.buffers.Get().(*bytes.Buffer)
		defer p.buffers.Put(buf)

		var keyLen, valLen int32
		for i := 0; i < iNumBaggage; i++ {
			if err := binary.Read(carrier, binary.BigEndian, &keyLen); err != nil {
				return emptyContext, opentracing.ErrSpanContextCorrupted
			}
			buf.Reset()
			buf.Grow(int(keyLen))
			if n, err := io.CopyN(buf, carrier, int64(keyLen)); err != nil || int32(n) != keyLen {
				return emptyContext, opentracing.ErrSpanContextCorrupted
			}
			key := buf.String()

			if err := binary.Read(carrier, binary.BigEndian, &valLen); err != nil {
				return emptyContext, opentracing.ErrSpanContextCorrupted
			}
			buf.Reset()
			buf.Grow(int(valLen))
			if n, err := io.CopyN(buf, carrier, int64(valLen)); err != nil || int32(n) != valLen {
				return emptyContext, opentracing.ErrSpanContextCorrupted
			}
			ctx.baggage[key] = buf.String()
		}
	}

	return ctx, nil
}

// Converts a comma separated key value pair list into a map
// e.g. key1=value1, key2=value2, key3 = value3
// is converted to map[string]string { "key1" : "value1",
//                                     "key2" : "value2",
//                                     "key3" : "value3" }
func (p *textMapPropagator) parseCommaSeparatedMap(value string) map[string]string {
	baggage := make(map[string]string)
	value, err := url.QueryUnescape(value)
	if err != nil {
		log.Printf("Unable to unescape %s, %v", value, err)
		return baggage
	}
	for _, kvpair := range strings.Split(value, ",") {
		kv := strings.Split(strings.TrimSpace(kvpair), "=")
		if len(kv) == 2 {
			baggage[kv[0]] = kv[1]
		} else {
			log.Printf("Malformed value passed in for %s", p.headerKeys.JaegerBaggageHeader)
		}
	}
	return baggage
}

// Converts a baggage item key into an http header format,
// by prepending TraceBaggageHeaderPrefix and encoding the key string
func (p *textMapPropagator) addBaggageKeyPrefix(key string) string {
	// TODO encodeBaggageKeyAsHeader add caching and escaping
	return fmt.Sprintf("%v%v", p.headerKeys.TraceBaggageHeaderPrefix, key)
}

func (p *textMapPropagator) removeBaggageKeyPrefix(key string) string {
	// TODO decodeBaggageHeaderKey add caching and escaping
	return key[len(p.headerKeys.TraceBaggageHeaderPrefix):]
}


text:
"use strict";

define ([
    'jquery',
    'cf',
    'prototypes'
], function (
    $,
    cf,
    prototypes
) {

    console.log("current-user initialization routine");

    var cu = Object.create(prototypes.user),
        ce = cf('currentUser'),
        priv = cf('currentUserPriv'),
        flag1;

    console.log("current-user: ce is ", ce);
    console.log("current-user: priv is " + priv);

    if (ce) {
        $.extend(cu, ce)
    }

    return function (sw, arg) {
        var emptyObj = { "nick": null };
        if (sw === 'obj') {
            // console.log('current-user function called with "obj"', arg);
            if (typeof arg === 'object' && arg) {
                console.log('NOTICE: setting current user object to ', arg);
                cu = $.extend({}, arg);
                cf('currentUser', cu);
            }
            if (arg === null) {
                console.log('NOTICE: resetting currentUser object');
                cu = $.extend({}, emptyObj);
                cf('currentUser', cu);
            }
            return cu;
        }
        if (sw === 'priv') {
            // console.log('current-user function called with "priv"');
            if (arg) {
                console.log('NOTICE: setting current user priv to ' + arg);
                priv = arg;
                cf('currentUserPriv', priv);
            }
            if (arg === null || arg === "") {
                console.log('NOTICE: resetting current user priv');
                priv = null;
                cf('currentUserPriv', priv);
            }
            return priv;
        }
        if (sw === 'flag1') {
            // console.log('current-user function called with "flag1"');
            if (arg || arg === 0 || arg === 'null' || arg === false) {
                console.log('NOTICE: setting current user flag1 to ' + arg);
                flag1 = arg;
            }
            return flag1;
        }
        // console.log('current-user function called with no arguments');
        return {
            'obj': cu,
            'priv': priv,
            'flag1': flag1
        };
    };

});


text:
/*
 * 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.
 */
package io.trino.sql.planner.iterative.rule;

import com.google.common.collect.ImmutableList;
import io.trino.matching.Capture;
import io.trino.matching.Captures;
import io.trino.matching.Pattern;
import io.trino.sql.planner.iterative.Rule;
import io.trino.sql.planner.plan.LimitNode;
import io.trino.sql.planner.plan.RowNumberNode;

import java.util.Optional;

import static io.trino.matching.Capture.newCapture;
import static io.trino.sql.planner.plan.ChildReplacer.replaceChildren;
import static io.trino.sql.planner.plan.Patterns.limit;
import static io.trino.sql.planner.plan.Patterns.rowNumber;
import static io.trino.sql.planner.plan.Patterns.source;
import static java.lang.Math.toIntExact;

public class PushdownLimitIntoRowNumber
        implements Rule<LimitNode>
{
    private static final Capture<RowNumberNode> CHILD = newCapture();
    private static final Pattern<LimitNode> PATTERN = limit()
            .matching(limit -> !limit.isWithTies() && limit.getCount() != 0 && limit.getCount() <= Integer.MAX_VALUE)
            .with(source().matching(rowNumber().capturedAs(CHILD)));

    @Override
    public Pattern<LimitNode> getPattern()
    {
        return PATTERN;
    }

    @Override
    public Result apply(LimitNode node, Captures captures, Context context)
    {
        RowNumberNode source = captures.get(CHILD);
        int limit = toIntExact(node.getCount());
        RowNumberNode rowNumberNode = mergeLimit(source, limit);
        if (rowNumberNode.getPartitionBy().isEmpty()) {
            return Result.ofPlanNode(rowNumberNode);
        }
        if (source.getMaxRowCountPerPartition().isPresent()) {
            if (rowNumberNode.getMaxRowCountPerPartition().equals(source.getMaxRowCountPerPartition())) {
                // Source node unchanged
                return Result.empty();
            }
        }
        return Result.ofPlanNode(replaceChildren(node, ImmutableList.of(rowNumberNode)));
    }

    private static RowNumberNode mergeLimit(RowNumberNode node, int newRowCountPerPartition)
    {
        if (node.getMaxRowCountPerPartition().isPresent()) {
            newRowCountPerPartition = Math.min(node.getMaxRowCountPerPartition().get(), newRowCountPerPartition);
        }
        return new RowNumberNode(
                node.getId(),
                node.getSource(),
                node.getPartitionBy(),
                node.isOrderSensitive(),
                node.getRowNumberSymbol(),
                Optional.of(newRowCountPerPartition),
                node.getHashSymbol());
    }
}


text:
module Azure::DataBox::Mgmt::V2018_01_01
  module Models
    #
    # Shipping address where customer wishes to receive the device.
    #
    class ShippingAddress

      include MsRestAzure

      # @return [String] Street Address line 1.
      attr_accessor :street_address1

      # @return [String] Street Address line 2.
      attr_accessor :street_address2

      # @return [String] Street Address line 3.
      attr_accessor :street_address3

      # @return [String] Name of the City.
      attr_accessor :city

      # @return [String] Name of the State or Province.
      attr_accessor :state_or_province

      # @return [String] Name of the Country.
      attr_accessor :country

      # @return [String] Postal code.
      attr_accessor :postal_code

      # @return [String] Extended Zip Code.
      attr_accessor :zip_extended_code

      # @return [String] Name of the company.
      attr_accessor :company_name

      # @return [AddressType] Type of address. Possible values include: 'None',
      # 'Residential', 'Commercial'
      attr_accessor :address_type

      #
      # Mapper for ShippingAddress class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ShippingAddress',
          type: {
            name: 'Composite',
            class_name: 'ShippingAddress',
            model_properties: {
              street_address1: {
                client_side_validation: true,
                required: true,
                serialized_name: 'streetAddress1',
                type: {
                  name: 'String'
                }
              },
              street_address2: {
                client_side_validation: true,
                required: false,
                serialized_name: 'streetAddress2',
                type: {
                  name: 'String'
                }
              },
              street_address3: {
                client_side_validation: true,
                required: false,
                serialized_name: 'streetAddress3',
                type: {
                  name: 'String'
                }
              },
              city: {
                client_side_validation: true,
                required: false,
                serialized_name: 'city',
                type: {
                  name: 'String'
                }
              },
              state_or_province: {
                client_side_validation: true,
                required: false,
                serialized_name: 'stateOrProvince',
                type: {
                  name: 'String'
                }
              },
              country: {
                client_side_validation: true,
                required: true,
                serialized_name: 'country',
                type: {
                  name: 'String'
                }
              },
              postal_code: {
                client_side_validation: true,
                required: true,
                serialized_name: 'postalCode',
                type: {
                  name: 'String'
                }
              },
              zip_extended_code: {
                client_side_validation: true,
                required: false,
                serialized_name: 'zipExtendedCode',
                type: {
                  name: 'String'
                }
              },
              company_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'companyName',
                type: {
                  name: 'String'
                }
              },
              address_type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'addressType',
                type: {
                  name: 'Enum',
                  module: 'AddressType'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
define(["dojo/_base/declare", "./PersistentObject", "ppwcode-util-oddsAndEnds/js", "dojo/date/stamp",
        "ppwcode-util-oddsAndEnds/log/logger!", "module"],
    function(declare, PersistentObject, js, dateStamp,
             logger, module) {

      function stringToDate(candidate) {
        //noinspection FallthroughInSwitchStatementJS
        switch (js.typeOf(candidate)) {
          case "undefined":
          case "null":
            return null;
          case "date":
            return candidate;
          case "string":
            return dateStamp.fromISOString(candidate);
          default:
            logger.error("cannot convert to date: ", candidate, js.typeOf(candidate));
            throw "ERROR: cannot convert to date: " + candidate;
        }
      }

      function compareDate(d1, d2) {
        // summary:
        //   We use < 1000 (1s) instead of < 0, because the server stores dates only to the second.
        //   With the current server implementation, we see that if we retrieve quickly after an
        //   update or create, the retrieve lastModified at is later than the one in the response
        //   of the action. The reason is, that the data in the action response comes from RAM,
        //   and has values up to the nanosecond or so (23/6/2012 15:45:32.424242242), while the
        //   data in the retrieve comes from the DB, which only stores up to the second
        //   (23/6/2012 15:45:32). So, it seems that retrieve-date is earlier than the action
        //   response date, which is impossible. By giving our comparison a 1 second leeway,
        //   this is resolved.

        if (d1 === d2) {
          return 0;
        }
        if (!d1) {
          return -1;
        }
        if (!d2) {
          return +1;
        }
        var delta = d1.getTime() - d2.getTime();
        if (delta < -1000) {
          return -1;
        }
        if (delta > +1000) {
          return +1;
        }
        return 0;
      }

      // MUDO There is a much worse problem: a RAM-created server Date is in the local time of the server
      //      While the time in the DB has no timezone. A RAM-created server Date that is sent over JSON
      //      contains timezone information. A date that is retrieved from the DB does not contain
      //      timezone in RAM, and thus does also not contain timezone information when it is sent over
      //      JSON.
      //      When JavaScript parses a string with timezone information, it takes it into account.
      //      When JavaScript parses a string without timezone information, it assumes the local
      //      timezone.
      //      When server and client are in a different timezone, when the JSON contains timezone information,
      //      the string is interpreted in the timezone of the server. When the JSON does not contain
      //      timezone information, the string is interpreted in the timezone of the client.
      //      For webapplications, this in unacceptable.
      // MUDO for now we work around this by NOT SENDING THE DATA TO THE SERVER IN THE FIRST PLACE
      //      that was another workaround; the effect of this is that we will not see this data after update
      // MUDO but it is obviously wrong

      // MUDO Attempted workaround for PICTOPERFECT-484: send the data to the server

      var InsertAuditableObject = declare([PersistentObject], {
        // InsertAuditableObjects have a `createdAt` and `createdBy` property, which is set by the server.
        // These properties cannot be set in the UI, and are initially null. Once set, the server should always
        // return the same values, except after delete, when they all turn null together again.

        _c_invar: [
          function() {return this._c_prop_string("createdBy");},
          function() {return this._c_prop_date("createdAt");},
          /*
            createdAt must be in the past
            but we cannot test that: server time and time of this local computer are incomparable
           */
          function() {return !!this.get("persistenceId") === !!this.get("createdBy");}, // both exist together or not
          function() {return !!this.get("createdBy") === !!this.get("createdAt");} // both exist together or not
        ],

        // createdBy: String
        createdBy: null,

        // createdAt: Date
        createdAt: null,

        _createdAtSetter: function() {
          // createdAt is read-only
          throw "ERROR createdAt is read-only";
        },

        _createdBySetter: function() {
          // createdBy is read-only
          throw "ERROR createdBy is read-only";
        },

        reload: function(/*Object*/ json) {
          // created.. can change from null to an actual date and username number after create,
          this._c_pre(function() {return json;});
// MUDO PICTOPERFECT-482          this._c_pre(function() {return !!json.persistenceId === !!json.createdBy;});
          this._c_pre(function() {return !!json.createdBy === !!json.createdAt;});
          this._c_pre(function() {return this._c_prop_string(json, "createdBy");});
          /*
          this._c_pre(function() {return !this.get("persistenceId") || !json.persistenceId || (this.get("createdBy") === json.createdBy);});
          The above is true, from the outside, but we cannot test it here, with this contract framework, because persistenceId is set
          by the superclass from null to the new value (on create) before we reach this test. It was true before reload, but not
          halfway. What follows is an equivalent local version.
          */
// MUDO PICTOPERFECT-482          this._c_pre(function() {return !this.get("createdBy") || !json.persistenceId || (this.get("createdBy") === json.createdBy);});

          logger.trace("Trying to convert to date: ", json.createdAt);
          if (!json.createdAt && logger.isDebugEnabled()) {
            logger.debug("No createdAt in json: ", JSON.stringify(json));
          }

          this._c_pre(function() {return this._c_prop_string(json, "createdAt") || this._c_prop_date(json, "createdAt");});
          this._c_pre(function() {return !this.get("createdBy") || !json.persistenceId || compareDate(this.get("createdAt"), stringToDate(json.createdAt)) === 0;});
          if (!this.get("createdBy") || !json.createdBy) {
            this._changeAttrValue("createdBy", json.createdBy);
            this._changeAttrValue("createdAt", stringToDate(json.createdAt));
          }
        },

        // it makes no senses whatsoever to send this data back to the back-end
        // MUDO Workaround for PICTOPERFECT-484: send the data to the server; this does eem to do the trick; is the timezone info above no longer applicable?

        _extendJsonObject:function (/*Object*/ json) {
          json.createdBy = this.get("createdBy");
          json.createdAt = this.get("createdAt");
        },

        _stateToString: function(/*String[]*/ toStrings) {
          toStrings.push("createdAt: " + this.createdAt);
          toStrings.push("createdBy: " + this.createdBy);
        }
      });

      InsertAuditableObject.mid = module.id;
      InsertAuditableObject.stringToDate = stringToDate;
      InsertAuditableObject.compareDate = compareDate;
      return InsertAuditableObject;
    }
);


text:
from django.urls import include, path, re_path

from accounts.paths import AccountPaths
from accounts.ui.views import accounts as account_views
from accounts.ui.views import teams as team_views
from accounts.ui.views import users as user_views
from accounts.ui.views.content import content
from manager.paths import RootPaths

urlpatterns = [
    re_path(
        RootPaths.content.value
        + r"/(?P<project_name>[^/]+)?(/(?P<version>live|latest|v\d+))?(/~(?P<key>[^/]+))?(/(?P<file_path>.+))?/?$",
        content,
        name="ui-accounts-content",
    ),
    path(
        RootPaths.users.value + "/",
        account_views.list_users,
        name="ui-accounts-list-users",
    ),
    path(
        RootPaths.orgs.value + "/",
        account_views.list_orgs,
        name="ui-accounts-list-orgs",
    ),
    path(
        RootPaths.orgs.value + "/new/", account_views.create, name="ui-accounts-create"
    ),
    re_path(
        r"^(?P<account>[^/]+)/teams/(?P<team>\d+)(?P<rest>.*)",
        team_views.redirect,
        name="ui-accounts-teams-redirect",
    ),
    re_path(
        r"^(?P<account>\d+)(?P<rest>.*)",
        account_views.redirect,
        name="ui-accounts-redirect",
    ),
    path(
        "<slug:account>/",
        include(
            [
                path("", account_views.retrieve, name="ui-accounts-retrieve"),
                path(
                    AccountPaths.profile.value + "/",
                    include(
                        [
                            path(
                                "", account_views.profile, name="ui-accounts-profile",
                            ),
                            path(
                                "image",
                                account_views.profile_image,
                                name="ui-accounts-profile-image",
                            ),
                        ]
                    ),
                ),
                path(
                    AccountPaths.publishing.value + "/",
                    account_views.publishing,
                    name="ui-accounts-publishing",
                ),
                path(
                    AccountPaths.plan.value + "/",
                    account_views.plan,
                    name="ui-accounts-plan",
                ),
                path(
                    AccountPaths.billing.value + "/",
                    account_views.billing,
                    name="ui-accounts-billing",
                ),
                path(
                    AccountPaths.users.value + "/",
                    user_views.update,
                    name="ui-accounts-users",
                ),
                path(
                    AccountPaths.teams.value + "/",
                    include(
                        [
                            path("", team_views.list, name="ui-accounts-teams-list"),
                            path(
                                "new/",
                                team_views.create,
                                name="ui-accounts-teams-create",
                            ),
                            path(
                                "<slug:team>/",
                                team_views.retrieve,
                                name="ui-accounts-teams-retrieve",
                            ),
                            path(
                                "<slug:team>/settings/",
                                team_views.update,
                                name="ui-accounts-teams-update",
                            ),
                        ]
                    ),
                ),
            ]
        ),
    ),
]


text:
from _pytest.compat import importlib_metadata

def test_pytest_entry_points_are_identical():
    dist = importlib_metadata.distribution("pytest")
    entry_map = {ep.name: ep for ep in dist.entry_points}
    assert entry_map["pytest"].value == entry_map["py.test"].value


text:
export const transitionMixin = nodeTarget => ({
    init: function() {
        if(!this.opts.transition)
            return
        const transitionName = this.opts.transition.name
        const origUnmount = this.unmount

        const mountTransition = () => {
            const target = (nodeTarget || (() => this.root))()
            if(!target) return

            target.classList.add(transitionName)
            target.classList.add(`${transitionName}-mount`)
            setTimeout(() => {
                target.classList.remove(`${transitionName}-mount`)
            }, 10)
        }

        let guard = false
        const unmountTransition = () => {
            if(guard) return
            guard = true
            const target = (nodeTarget || (() => this.root))()
            if(!target) return origUnmount.call(this)

            target.addEventListener("transitionend", () => {
                origUnmount.call(this)
            })
            target.classList.add(`${transitionName}-unmount`)
        }

        this.one("mount", mountTransition)
        Object.defineProperty(this, "unmount", {
            value: unmountTransition
        })
    }
})


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.postgresqlflexibleserver.fluent;

import com.azure.core.http.HttpPipeline;
import java.time.Duration;

/** The interface for PostgreSqlManagementClient class. */
public interface PostgreSqlManagementClient {
    /**
     * Gets The ID of the target subscription.
     *
     * @return the subscriptionId value.
     */
    String getSubscriptionId();

    /**
     * Gets server parameter.
     *
     * @return the endpoint value.
     */
    String getEndpoint();

    /**
     * Gets Api Version.
     *
     * @return the apiVersion value.
     */
    String getApiVersion();

    /**
     * Gets The HTTP pipeline to send requests through.
     *
     * @return the httpPipeline value.
     */
    HttpPipeline getHttpPipeline();

    /**
     * Gets The default poll interval for long-running operation.
     *
     * @return the defaultPollInterval value.
     */
    Duration getDefaultPollInterval();

    /**
     * Gets the ServersClient object to access its operations.
     *
     * @return the ServersClient object.
     */
    ServersClient getServers();

    /**
     * Gets the FirewallRulesClient object to access its operations.
     *
     * @return the FirewallRulesClient object.
     */
    FirewallRulesClient getFirewallRules();

    /**
     * Gets the ConfigurationsClient object to access its operations.
     *
     * @return the ConfigurationsClient object.
     */
    ConfigurationsClient getConfigurations();

    /**
     * Gets the CheckNameAvailabilitiesClient object to access its operations.
     *
     * @return the CheckNameAvailabilitiesClient object.
     */
    CheckNameAvailabilitiesClient getCheckNameAvailabilities();

    /**
     * Gets the LocationBasedCapabilitiesClient object to access its operations.
     *
     * @return the LocationBasedCapabilitiesClient object.
     */
    LocationBasedCapabilitiesClient getLocationBasedCapabilities();

    /**
     * Gets the VirtualNetworkSubnetUsagesClient object to access its operations.
     *
     * @return the VirtualNetworkSubnetUsagesClient object.
     */
    VirtualNetworkSubnetUsagesClient getVirtualNetworkSubnetUsages();

    /**
     * Gets the OperationsClient object to access its operations.
     *
     * @return the OperationsClient object.
     */
    OperationsClient getOperations();

    /**
     * Gets the DatabasesClient object to access its operations.
     *
     * @return the DatabasesClient object.
     */
    DatabasesClient getDatabases();

    /**
     * Gets the GetPrivateDnsZoneSuffixesClient object to access its operations.
     *
     * @return the GetPrivateDnsZoneSuffixesClient object.
     */
    GetPrivateDnsZoneSuffixesClient getGetPrivateDnsZoneSuffixes();
}


text:
template<class Value>
size_t check_outputs(const std::vector<Value>& a,
                     const std::vector<Value>& b,
                     Value deflt)
{
    typedef typename std::vector<Value>::const_iterator Iterator;

    size_t counter = 0;

    Iterator it_a = a.begin();
    Iterator it_b = b.begin();

    while ( it_a != a.end() && it_b != b.end() )
    {
      if ( *it_a != *it_b && *it_b != deflt && *it_a != deflt )
        ++counter;

      ++it_a;
      ++it_b;
    }

    return counter;
}

template <class Tree, class K>
void test_hint_strategies(Tree& tree,
                          CGAL::Polyhedron_3<K>& polyhedron,
                          const double duration)
{
        typedef typename K::Point_3 Point;
        typedef typename Tree::Primitive::Id Id;
        typedef typename Tree::Point_and_primitive_id Point_and_primitive_id;

        std::vector<Point> queries;
        std::vector<Id> outputs1, outputs2, outputs3;

        queries.reserve(NBQ);
        outputs1.reserve(NBQ);
        outputs2.reserve(NBQ);
        outputs3.reserve(NBQ);

        size_t counter;

        for(size_t i = 0; i < NBQ; ++i)
                queries.push_back(random_point_in<K>(tree.bbox()));

        CGAL::spatial_sort(queries.begin(), queries.end());

        CGAL::Timer timer;
        timer.start();
        counter = 0;
        while(timer.time() < duration && counter < NBQ) {
                outputs1.push_back(tree.closest_point_and_primitive(queries[counter]).second);
                ++counter;
        }
        timer.stop();
        double speed = static_cast<double>(counter)/(counter == NBQ? timer.time(): duration);
        std::cout << "without hint:      " << speed << " queries/s" << std::endl;
        timer.reset();

        Point_and_primitive_id hint = tree.any_reference_point_and_id();

        timer.start();
        counter = 0;
        while(timer.time() < duration && counter < NBQ) {
                outputs2.push_back((hint = tree.closest_point_and_primitive(queries[counter], hint)).second);
                ++counter;
        }
        timer.stop();
        speed = static_cast<double>(counter)/(counter == NBQ? timer.time(): duration);
        std::cout << "with spatial sort: " << speed << " queries/s" << std::endl;
        timer.reset();

        tree.accelerate_distance_queries(polyhedron.points_begin(),polyhedron.points_end());

        timer.start();
        counter = 0;
        while(timer.time() < duration && counter < NBQ) {
                outputs3.push_back(tree.closest_point_and_primitive(queries[counter]).second);
                ++counter;
        }
        timer.stop();
        speed = static_cast<double>(counter)/(counter == NBQ? timer.time(): duration);
        std::cout << "with KD-tree:      " << speed << " queries/s" << std::endl << std::endl;
        std::cout << "Consistency:" << std::endl;
        if((counter = check_outputs(outputs1, outputs2, Id())) == 0)
                std::cout << "without hint and spatial sort are consistent" << std::endl;
        else
                std::cout << "without hint and spatial sort have " << counter << " inconsistencies (closest point on vertex/edge?)" << std::endl;

        if((counter = check_outputs(outputs1, outputs3, Id())) == 0)
                std::cout << "without hint and with KD-tree are consistent (modulo hint case)" << std::endl;
        else
                std::cout << "without hint and with KD-tree have " << counter << " inconsistencies (closest point on vertex/edge? the hint case has been excluded)" << std::endl;

        std::cout << std::endl;
}

template<class K, class Tree, class Polyhedron, Primitive_type Type>
void test_impl(Tree& tree,
               Polyhedron& p,
               const double duration)
{
  test_hint_strategies<Tree,K>(tree, p, duration);
}

int main(void)
{
    const double duration = 0.1;
    std::cout << "AABB hint strategy tests" << std::endl;
    test_kernels<TRIANGLE>("./data/cube.off",duration);
    test_kernels<TRIANGLE>("./data/coverrear.off",duration);
    test_kernels<TRIANGLE>("./data/finger.off",duration);
    return EXIT_SUCCESS;
}


text:
.. _mcmc:

Markov chain Monte Carlo (MCMC)
===============================

``openmmtools`` provides an extensible Markov chain Monte Carlo simulation framework.

This module provides a framework for equilibrium sampling from a given thermodynamic state of a biomolecule using a Markov chain Monte Carlo scheme.

It currently offer supports for

 - Langevin dynamics (assumed to be free of integration error; use at your own risk]),
 - hybrid Monte Carlo,
 - generalized hybrid Monte Carlo, and
 - Monte Carlo barostat moves,

which can be combined through the ``SequenceMove`` and ``WeightedMove`` classes.

By default, the ``MCMCMoves`` use the fastest OpenMM platform available and a shared global ``ContextCache`` that minimizes the number of OpenMM ``Context`` objects that must be maintained at once.
The examples below show how to configure these aspects.

.. NOTE::
   To use the ``ContextCache`` on the CUDA platform, the NVIDIA driver must be set to ``shared`` mode to allow the process to create multiple GPU contexts.

Using the MCMC framework requires importing :class:`ThermodynamicState` and :class:`SamplerState` from :mod:`openmmtools.states`:

::

    from simtk import unit
    from openmmtools import testsystems, cache
    from openmmtools.states import ThermodynamicState, SamplerState

Create the initial state (thermodynamic and microscopic) for an alanine
dipeptide system in vacuum.

::

    test = testsystems.AlanineDipeptideVacuum()
    thermodynamic_state = ThermodynamicState(system=test.system, temperature=298*unit.kelvin)
    sampler_state = SamplerState(positions=test.positions)

Create an MCMC move to perform at every iteration of the simulation, and
initialize a sampler instance.

::

    ghmc_move = GHMCMove(timestep=1.0*unit.femtosecond, n_steps=50)
    langevin_move = LangevinDynamicsMove(n_steps=10)
    sampler = MCMCSampler(thermodynamic_state, sampler_state, move=ghmc_move)

You can combine them to form a sequence of moves

::

    sequence_move = SequenceMove([ghmc_move, langevin_move])
    sampler = MCMCSampler(thermodynamic_state, sampler_state, move=sequence_move)

or create a move that selects one of them at random with given probability
at each iteration.

::

    weighted_move = WeightedMove([(ghmc_move, 0.5), (langevin_move, 0.5)])
    sampler = MCMCSampler(thermodynamic_state, sampler_state, move=weighted_move)

By default the ``MCMCMove`` use a global ContextCache that creates ``Context`` on the
fastest available OpenMM platform. You can configure the default platform to use
before starting the simulation

::

    reference_platform = openmm.Platform.getPlatformByName('Reference')
    cache.global_context_cache.platform = reference_platform
    cache.global_context_cache.time_to_live = 10  # number of read/write operations

Minimize and run the simulation for few iterations.

::

    sampler.minimize()
    sampler.run(n_iterations=2)

If you don't want to use a global cache, you can create local ones.

::

    local_cache1 = cache.ContextCache(capacity=5, time_to_live=50)
    local_cache2 = cache.ContextCache(platform=reference_platform, capacity=1)
    sequence_move = SequenceMove([HMCMove(), LangevinDynamicsMove()], context_cache=local_cache1)
    ghmc_move = GHMCMove(context_cache=local_cache2)

If you don't want to cache ``Context`` at all but create one every time, you can use
the ``DummyCache``.

::

    dummy_cache = cache.DummyContextCache(platform=reference_platform)
    ghmc_move = GHMCMove(context_cache=dummy_cache)

This book by Jun Liu is an excellent overview of Markov chain Monte Carlo:

Jun S. Liu. Monte Carlo Strategies in Scientific Computing. Springer, 2008.

MCMC samplers
-------------

An MCMC sampler driver is provided that can either utilize a programmed sequence of moves or draw from a weighted set of moves.

.. currentmodule:: openmmtools.mcmc
.. autosummary::
    :nosignatures:
    :toctree: api/generated/

    MCMCSampler
    SequenceMove
    WeightedMove

MCMC move types
---------------

A number of MCMC component move types that can be arranged into groups or subclassed are provided.

.. currentmodule:: openmmtools.mcmc
.. autosummary::
    :nosignatures:
    :toctree: api/generated/

    MCMCMove
    BaseIntegratorMove
    MetropolizedMove
    IntegratorMove
    LangevinDynamicsMove
    LangevinSplittingDynamicsMove
    GHMCMove
    HMCMove
    MonteCarloBarostatMove
    MCDisplacementMove
    MCRotationMove


text:
using App.Metrics.Facts.TestHelpers;
using App.Metrics.FactsCommon;
using App.Metrics.Meter;
using FluentAssertions;
using Xunit;

namespace App.Metrics.Facts.Meter
{
    public class MeterMetricTests
    {
        private readonly IClock _clock;
        private readonly DefaultMeterMetric _meter;

        public MeterMetricTests()
        {
            _clock = new TestClock();
            var schedular = new TestMeterTickerScheduler(_clock);
            _meter = new DefaultMeterMetric(_clock, schedular);
        }

        [Fact]
        public void Can_calculate_mean_rate()
        {
            _meter.Mark();
            _clock.Advance(TimeUnit.Seconds, 1);

            _meter.Value.MeanRate.Should().Be(1);

            _clock.Advance(TimeUnit.Seconds, 1);

            _meter.Value.MeanRate.Should().Be(0.5);
        }

        [Fact]
        public void Can_compute_multiple_rates()
        {
            _meter.Mark();
            _clock.Advance(TimeUnit.Seconds, 10);
            _meter.Mark(2);

            var value = _meter.Value;

            value.MeanRate.Should().BeApproximately(0.3, 0.001);
            value.OneMinuteRate.Should().BeApproximately(0.1840, 0.001);
            value.FiveMinuteRate.Should().BeApproximately(0.1966, 0.001);
            value.FifteenMinuteRate.Should().BeApproximately(0.1988, 0.001);
        }

        [Fact]
        public void Can_compute_percent_with_zero_total()
        {
            _meter.Mark("A");
            _meter.Mark("A", -1);

            _meter.Value.Count.Should().Be(0);

            _meter.Value.Items[0].Item.Should().Be("A");
            _meter.Value.Items[0].Value.Count.Should().Be(0);
            _meter.Value.Items[0].Percent.Should().Be(0);
        }

        [Fact]
        public void Can_count()
        {
            _meter.Mark();

            _meter.Value.Count.Should().Be(1L);

            _meter.Mark();
            _meter.Value.Count.Should().Be(2L);

            _meter.Mark(8L);
            _meter.Value.Count.Should().Be(10L);
        }

        [Fact]
        public void Can_count_for_multiple_set_items()
        {
            _meter.Mark("A");
            _meter.Mark("B");

            _meter.Value.Count.Should().Be(2L);
            _meter.Value.Items.Should().HaveCount(2);

            _meter.Value.Items[0].Item.Should().Be("A");
            _meter.Value.Items[0].Value.Count.Should().Be(1);
            _meter.Value.Items[0].Percent.Should().Be(50);

            _meter.Value.Items[1].Item.Should().Be("B");
            _meter.Value.Items[1].Value.Count.Should().Be(1);
            _meter.Value.Items[1].Percent.Should().Be(50);
        }

        [Fact]
        public void Can_count_for_set_item()
        {
            _meter.Mark("A");
            _meter.Value.Count.Should().Be(1L);
            _meter.Value.Items.Should().HaveCount(1);

            _meter.Value.Items[0].Item.Should().Be("A");
            _meter.Value.Items[0].Value.Count.Should().Be(1);
            _meter.Value.Items[0].Percent.Should().Be(100);
        }

        [Fact]
        public void Can_reset()
        {
            _meter.Mark();
            _meter.Mark();
            _clock.Advance(TimeUnit.Seconds, 10);
            _meter.Mark(2);

            _meter.Reset();
            _meter.Value.Count.Should().Be(0L);
            _meter.Value.OneMinuteRate.Should().Be(0);
            _meter.Value.FiveMinuteRate.Should().Be(0);
            _meter.Value.FifteenMinuteRate.Should().Be(0);
        }

        [Fact]
        public void Can_reset_set_item()
        {
            _meter.Mark("A");
            _meter.Value.Items[0].Value.Count.Should().Be(1);
            _meter.Reset();
            _meter.Value.Items[0].Value.Count.Should().Be(0L);
        }

        [Fact]
        public void Can_get_value()
        {
            _meter.Mark();
            var value = _meter.GetValue();
            value.Count.Should().Be(1);
            _meter.Value.Count.Should().Be(1);
        }

        [Fact]
        public void Can_get_value_and_reset()
        {
            _meter.Mark();
            var value = _meter.GetValue(true);
            value.Count.Should().Be(1);
            _meter.Value.Count.Should().Be(0L);
        }

        [Fact]
        public void Rates_should_start_at_zero()
        {
            _meter.Value.MeanRate.Should().Be(0L);
            _meter.Value.OneMinuteRate.Should().Be(0L);
            _meter.Value.FiveMinuteRate.Should().Be(0L);
            _meter.Value.FifteenMinuteRate.Should().Be(0L);
        }

        [Fact]
        public void Returns_empty_meter_if_not_meter_metric()
        {
            var meter = new CustomMeter();
            var value = meter.GetValueOrDefault();
            value.Should().NotBeNull();
        }

        [Fact]
        public void Value_can_scale_down()
        {
            _meter.Mark();
            _clock.Advance(TimeUnit.Milliseconds, 1);
            _meter.Mark();
            _clock.Advance(TimeUnit.Milliseconds, 1);

            var scaledValue = _meter.Value.Scale(TimeUnit.Milliseconds);

            scaledValue.MeanRate.Should().Be(1);
        }

        [Fact]
        public void Value_can_scale_down_to_decimal()
        {
            _meter.Mark();
            _clock.Advance(TimeUnit.Seconds, 1);
            _meter.Mark();
            _clock.Advance(TimeUnit.Seconds, 1);

            var scaledValue = _meter.Value.Scale(TimeUnit.Milliseconds);

            scaledValue.MeanRate.Should().Be(0.001);
        }

        [Fact]
        public void Value_can_scale_up()
        {
            _meter.Mark();
            _clock.Advance(TimeUnit.Minutes, 1);
            _meter.Mark();
            _clock.Advance(TimeUnit.Minutes, 1);

            var scaledValue = _meter.GetValueOrDefault().Scale(TimeUnit.Minutes);

            scaledValue.MeanRate.Should().Be(1);
        }
    }
}


text:
package nl.yeex.knowledge.mavenplugin;

import java.io.File;

import nl.yeex.knowledge.Main;
import nl.yeex.knowledge.offline.generators.GeneratorContext;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * Start executing of the export as maven plugin.
 *
 */
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class Owl2HTMLPluginMojo extends AbstractMojo {

    @Parameter
    private String outputDirectory;
    @Parameter
    private String inputDirectory;
    @Parameter
    private String themesDirectory;
    @Parameter
    private String theme;
    @Parameter
    private String generation;
    @Parameter
    private String inferenceenabled;
    @Parameter
    private File owlSourceFile;

    public void execute() throws MojoExecutionException {
        getLog().info("plugin parameter: outputDirectory: " + outputDirectory);
        getLog().info("plugin parameter: inputDirectory: " + inputDirectory);
        getLog().info("plugin parameter: themesDirectory: " + themesDirectory);
        getLog().info("plugin parameter: theme: " + theme);
        getLog().info("plugin parameter: owlSourceFile: " + owlSourceFile);
        getLog().info("plugin parameter: generation: " + generation);
        getLog().info("plugin parameter: inferenceenabled: " + inferenceenabled);

        GeneratorContext configuration = new GeneratorContext();
        configuration.setOutputDirectory((outputDirectory != null) ? outputDirectory
                : GeneratorContext.DEFAULT_OUTPUT_DIRECTORY);
        configuration.setInputDirectory((outputDirectory != null) ? inputDirectory
                : GeneratorContext.DEFAULT_INPUT_DIRECTORY);
        configuration.setThemesDirectory((themesDirectory != null) ? themesDirectory
                : GeneratorContext.DEFAULT_THEMES_DIRECTORY);
        configuration.setTheme((theme != null) ? theme : GeneratorContext.DEFAULT_THEME);
        configuration.setOwlSourceFile(owlSourceFile);
        configuration.setGeneration(generation);
        configuration.setEnableInference("true".equalsIgnoreCase(inferenceenabled));
        Main.start(configuration);
    }
}