text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Windows;
using Microsoft.R.Components.View;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;

namespace Microsoft.R.Components.History.Implementation {
    public class RHistoryWindowVisualComponent : IRHistoryWindowVisualComponent {
        private readonly IVisualComponentContainer<IRHistoryWindowVisualComponent> _container;
        private IRHistory _history;

        public const string TextViewRole = "TextViewRole";

        public RHistoryWindowVisualComponent(ITextBuffer historyTextBuffer, IRHistoryProvider historyProvider, ITextEditorFactoryService textEditorFactory, IVisualComponentContainer<IRHistoryWindowVisualComponent> container) {
            _container = container;
            _history = historyProvider.GetAssociatedRHistory(historyTextBuffer);

            TextView = CreateTextView(historyTextBuffer, textEditorFactory);
            TextView.Selection.SelectionChanged += TextViewSelectionChanged;

            Control = textEditorFactory.CreateTextViewHost(TextView, false).HostControl;
        }

        public FrameworkElement Control { get; }
        public IVisualComponentContainer<IVisualComponent> Container => _container;
        public IWpfTextView TextView { get; private set; }

        public void Dispose() {
            if (TextView == null) {
                return;
            }

            TextView.Selection.SelectionChanged -= TextViewSelectionChanged;
            TextView.Close();
            TextView = null;
            _history = null;
        }

        private void TextViewSelectionChanged(object sender, EventArgs e) {
            if (TextView.Selection.Start != TextView.Selection.End) {
                _history.ClearHistoryEntrySelection();
            }
        }

        private static IWpfTextView CreateTextView(ITextBuffer historyTextBuffer, ITextEditorFactoryService textEditorFactory) {
            var textView = textEditorFactory.CreateTextView(historyTextBuffer, textEditorFactory.DefaultRoles.UnionWith(textEditorFactory.CreateTextViewRoleSet(TextViewRole)));
            textView.Options.SetOptionValue(DefaultTextViewHostOptions.VerticalScrollBarId, true);
            textView.Options.SetOptionValue(DefaultTextViewHostOptions.HorizontalScrollBarId, true);
            textView.Options.SetOptionValue(DefaultTextViewHostOptions.SelectionMarginId, false);
            textView.Options.SetOptionValue(DefaultTextViewHostOptions.GlyphMarginId, false);
            textView.Options.SetOptionValue(DefaultTextViewHostOptions.ZoomControlId, false);
            textView.Options.SetOptionValue(DefaultWpfViewOptions.EnableMouseWheelZoomId, false);
            textView.Options.SetOptionValue(DefaultWpfViewOptions.EnableHighlightCurrentLineId, false);
            textView.Options.SetOptionValue(DefaultTextViewOptions.AutoScrollId, true);
            textView.Options.SetOptionValue(DefaultTextViewOptions.BraceCompletionEnabledOptionId, false);
            textView.Options.SetOptionValue(DefaultTextViewOptions.DragDropEditingId, false);
            textView.Options.SetOptionValue(DefaultTextViewOptions.UseVirtualSpaceId, false);
            textView.Caret.IsHidden = true;
            return textView;
        }
    }
}


text:
          #ifndef AviaryCollector_ATTRIBUTEREQUEST_H
          #define AviaryCollector_ATTRIBUTEREQUEST_H

       /**
        * AttributeRequest.h
        *
        * This file was auto-generated from WSDL
        * by the Apache Axis2/Java version: 1.0  Built on : Nov 08, 2012 (09:07:42 EST)
        */

       /**
        *  AttributeRequest class
        */

        namespace AviaryCollector{
            class AttributeRequest;
        }

                #include "AviaryCommon_ResourceID.h"

        #include <stdio.h>
        #include <OMElement.h>
        #include <ServiceClient.h>
        #include <ADBDefines.h>

namespace AviaryCollector
{

        class AttributeRequest {

        private:
             AviaryCommon::ResourceID* property_Id;

                bool isValidId;
            std::vector<std::string*>* property_Names;

                bool isValidNames;

        /*** Private methods ***/

        bool WSF_CALL
        setIdNil();

        bool WSF_CALL
        setNamesNil();

        /******************************* public functions *********************************/

        public:

        /**
         * Constructor for class AttributeRequest
         */

        AttributeRequest();

        /**
         * Destructor AttributeRequest
         */
        ~AttributeRequest();

        /**
         * Constructor for creating AttributeRequest
         * @param
         * @param Id AviaryCommon::ResourceID*
         * @param Names std::vector<std::string*>*
         * @return newly created AttributeRequest object
         */
        AttributeRequest(AviaryCommon::ResourceID* arg_Id,std::vector<std::string*>* arg_Names);

        /**
         * resetAll for AttributeRequest
         */
        WSF_EXTERN bool WSF_CALL resetAll();

        /********************************** Class get set methods **************************************/
        /******** Deprecated for array types, Use 'Getters and Setters for Arrays' instead ***********/

        /**
         * Getter for id.
         * @return AviaryCommon::ResourceID*
         */
        WSF_EXTERN AviaryCommon::ResourceID* WSF_CALL
        getId();

        /**
         * Setter for id.
         * @param arg_Id AviaryCommon::ResourceID*
         * @return true on success, false otherwise
         */
        WSF_EXTERN bool WSF_CALL
        setId(AviaryCommon::ResourceID*  arg_Id);

        /**
         * Re setter for id
         * @return true on success, false
         */
        WSF_EXTERN bool WSF_CALL
        resetId();

        /**
         * Getter for names. Deprecated for array types, Use getNamesAt instead
         * @return Array of std::strings.
         */
        WSF_EXTERN std::vector<std::string*>* WSF_CALL
        getNames();

        /**
         * Setter for names.Deprecated for array types, Use setNamesAt
         * or addNames instead.
         * @param arg_Names Array of std::strings.
         * @return true on success, false otherwise
         */
        WSF_EXTERN bool WSF_CALL
        setNames(std::vector<std::string*>*  arg_Names);

        /**
         * Re setter for names
         * @return true on success, false
         */
        WSF_EXTERN bool WSF_CALL
        resetNames();

        /****************************** Get Set methods for Arrays **********************************/
        /************ Array Specific Operations: get_at, set_at, add, remove_at, sizeof *****************/

        /**
         * E.g. use of get_at, set_at, add and sizeof
         *
         * for(i = 0; i < adb_element->sizeofProperty(); i ++ )
         * {
         *     // Getting ith value to property_object variable
         *     property_object = adb_element->getPropertyAt(i);
         *
         *     // Setting ith value from property_object variable
         *     adb_element->setPropertyAt(i, property_object);
         *
         *     // Appending the value to the end of the array from property_object variable
         *     adb_element->addProperty(property_object);
         *
         *     // Removing the ith value from an array
         *     adb_element->removePropertyAt(i);
         *
         * }
         *
         */

        /**
         * Get the ith element of names.
        * @param i index of the item to be obtained
         * @return ith std::string of the array
         */
        WSF_EXTERN std::string WSF_CALL
        getNamesAt(int i);

        /**
         * Set the ith element of names. (If the ith already exist, it will be replaced)
         * @param i index of the item to return
         * @param arg_Names element to set std::string to the array
         * @return ith std::string of the array
         */
        WSF_EXTERN bool WSF_CALL
        setNamesAt(int i,
                const std::string arg_Names);

        /**
         * Add to names.
         * @param arg_Names element to add std::string to the array
         * @return true on success, false otherwise.
         */
        WSF_EXTERN bool WSF_CALL
        addNames(
            const std::string arg_Names);

        /**
         * Get the size of the names array.
         * @return the size of the names array.
         */
        WSF_EXTERN int WSF_CALL
        sizeofNames();

        /**
         * Remove the ith element of names.
         * @param i index of the item to remove
         * @return true on success, false otherwise.
         */
        WSF_EXTERN bool WSF_CALL
        removeNamesAt(int i);

        /******************************* Checking and Setting NIL values *********************************/
        /* Use 'Checking and Setting NIL values for Arrays' to check and set nil for individual elements */

        /**
         * NOTE: set_nil is only available for nillable properties
         */

        /**
         * Check whether id is Nill
         * @return true if the element is Nil, false otherwise
         */
        bool WSF_CALL
        isIdNil();

        /**
         * Check whether names is Nill
         * @return true if the element is Nil, false otherwise
         */
        bool WSF_CALL
        isNamesNil();

        /*************************** Checking and Setting 'NIL' values in Arrays *****************************/

        /**
         * NOTE: You may set this to remove specific elements in the array
         *       But you can not remove elements, if the specific property is declared to be non-nillable or sizeof(array) < minOccurs
         */

        /**
         * Check whether names is Nill at position i
         * @param i index of the item to return.
         * @return true if the value is Nil at position i, false otherwise
         */
        bool WSF_CALL
        isNamesNilAt(int i);

        /**
         * Set names to NILL at the  position i.
         * @param i . The index of the item to be set Nill.
         * @return true on success, false otherwise.
         */
        bool WSF_CALL
        setNamesNilAt(int i);

        /**************************** Serialize and De serialize functions ***************************/
        /*********** These functions are for use only inside the generated code *********************/

        /**
         * Deserialize the ADB object to an XML
         * @param dp_parent double pointer to the parent node to be deserialized
         * @param dp_is_early_node_valid double pointer to a flag (is_early_node_valid?)
         * @param dont_care_minoccurs Dont set errors on validating minoccurs,
         *              (Parent will order this in a case of choice)
         * @return true on success, false otherwise
         */
        bool WSF_CALL
        deserialize(axiom_node_t** omNode, bool *isEarlyNodeValid, bool dontCareMinoccurs);

       /**
         * Declare namespace in the most parent node
         * @param parent_element parent element
         * @param namespaces hash of namespace uri to prefix
         * @param next_ns_index pointer to an int which contain the next namespace index
         */
        void WSF_CALL
        declareParentNamespaces(axiom_element_t *parent_element, axutil_hash_t *namespaces, int *next_ns_index);

        /**
         * Serialize the ADB object to an xml
         * @param AttributeRequest_om_node node to serialize from
         * @param AttributeRequest_om_element parent element to serialize from
         * @param tag_closed Whether the parent tag is closed or not
         * @param namespaces hash of namespace uris to prefixes
         * @param next_ns_index an int which contains the next namespace index
         * @return axiom_node_t on success,NULL otherwise.
         */
        axiom_node_t* WSF_CALL
        serialize(axiom_node_t* AttributeRequest_om_node, axiom_element_t *AttributeRequest_om_element, int tag_closed, axutil_hash_t *namespaces, int *next_ns_index);

        /**
         * Check whether the AttributeRequest is a particle class (E.g. group, inner sequence)
         * @return true if this is a particle class, false otherwise.
         */
        bool WSF_CALL
        isParticle();

        /******************************* get the value by the property number  *********************************/
        /************NOTE: This method is introduced to resolve a problem in unwrapping mode *******************/

        /**
         * Getter for id by property number (1)
         * @return AviaryCommon::ResourceID
         */

        AviaryCommon::ResourceID* WSF_CALL
        getProperty1();

        /**
         * Getter for names by property number (2)
         * @return Array of std::strings.
         */

        std::vector<std::string*>* WSF_CALL
        getProperty2();

};

}
 #endif /* ATTRIBUTEREQUEST_H */

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import ResizeObserver from 'resize-observer-polyfill';

interface Props {
  itemCount: number;
  itemHeight: number;
  renderer: (idx: number, style: React.CSSProperties) => React.ReactNode;
  className?: string;
  style?: React.CSSProperties;
}

interface State {
  offset: number;
  height: number;
  itemStyle?: React.CSSProperties;
}

export default class VirtualList extends React.Component<Props, State> {
  static getDerivedStateFromProps(props: Props, state: State) {
    if (state?.itemStyle?.height !== props.itemHeight) {
      // cache children style in state to reduce re-render
      return {itemStyle: {height: props.itemHeight}};
    }
    return {};
  }

  static defaultProps = {};

  state: State = {offset: 0, height: 0};
  resizeObserver: any;

  private rootNode!: HTMLElement;
  private getRef = (node: HTMLDivElement): void => {
    this.rootNode = node;
  };

  componentDidMount() {
    this.rootNode.addEventListener('scroll', this.handleScroll, {
      passive: true,
    });

    this.resizeObserver = new ResizeObserver((resizes: any) => {
      this.setState({
        height: this.rootNode.clientHeight,
      });
    });
    this.resizeObserver.observe(this.rootNode);
  }

  componentWillUnmount() {
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
    }
    this.rootNode.removeEventListener('scroll', this.handleScroll);
  }

  onPointerDown = (e: React.PointerEvent) => {
    if (e.shiftKey) {
      // not allow shift key to select range in virtual scroller
      e.preventDefault();
    }
  };

  render() {
    const {itemCount, itemHeight, renderer, className, style} = this.props;
    const {height, offset, itemStyle} = this.state;

    if (this.state.height > 0 && itemCount > 0) {
      let contentHeight = itemCount * itemHeight;
      let start = Math.floor(offset / itemHeight);
      let end = Math.ceil((offset + height) / itemHeight);
      if (end > itemCount) {
        end = itemCount;
      }
      let children: React.ReactNode[] = [];
      let paddingTop = '';
      if (end > start) {
        for (let i = start; i < end; ++i) {
          children.push(renderer(i, itemStyle));
        }
        paddingTop = `${start * itemHeight}px`;
      }

      return (
        <div
          ref={this.getRef}
          className={`ticl-v-scroll ${className}`}
          style={style}
          onPointerDown={this.onPointerDown}
        >
          <div className="ticl-v-scroll-content" style={{height: `${contentHeight}px`, paddingTop}}>
            {children}

      );
    } else {
      // not mounted or not visible, create dummy div to measure size
      return <div ref={this.getRef} className={`ticl-v-scroll ${className}`} style={style}>
;
    }
  }

  handleScroll = (event: UIEvent) => {
    const offset = this.rootNode.scrollTop;

    if (offset < 0 || this.state.offset === offset || event.target !== this.rootNode) {
      return;
    }

    this.setState({
      offset,
    });
  };
}


text:
// ***********************************************************************
// <copyright file="SqliteCharConverter.cs" company="ServiceStack, Inc.">
//     Copyright (c) ServiceStack, Inc. All Rights Reserved.
// </copyright>
// <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary>
// ***********************************************************************

namespace ServiceStack.OrmLite.Sqlite.Converters;

using System;

/// <summary>
/// Class SqliteCharConverter.
/// Implements the <see cref="ServiceStack.OrmLite.OrmLiteConverter" />
/// </summary>
/// <seealso cref="ServiceStack.OrmLite.OrmLiteConverter" />
public class SqliteCharConverter : OrmLiteConverter
{
    /// <summary>
    /// SQL Column Definition used in CREATE Table.
    /// </summary>
    /// <value>The column definition.</value>
    public override string ColumnDefinition => "CHAR(1)";

    /// <summary>
    /// Parameterized value in parameterized queries
    /// </summary>
    /// <param name="fieldType">Type of the field.</param>
    /// <param name="value">The value.</param>
    /// <returns>System.Object.</returns>
    public override object ToDbValue(Type fieldType, object value)
    {
        return value.ToString();
    }

    /// <summary>
    /// Froms the database value.
    /// </summary>
    /// <param name="fieldType">Type of the field.</param>
    /// <param name="value">The value.</param>
    /// <returns>System.Object.</returns>
    public override object FromDbValue(Type fieldType, object value)
    {
        return ((string)value)[0];
    }

}


text:
from __future__ import division, unicode_literals

from py2neo.batch.core import Batch

class ReadBatch(Batch):
    """ Generic batch execution facility for data read requests,
    """

    def __init__(self, graph):
        Batch.__init__(self, graph)

    def stream(self):
        for result in self.graph.batch.stream(self):
            yield result.content

    def submit(self):
        return [result.content for result in self.graph.batch.submit(self)]


text:
import sys
from warnings import catch_warnings
with catch_warnings():
    if sys.py3kwarning:
        sys.filterwarnings("ignore", ".*mimetools has been removed",
                           DeprecationWarning)
    import mimetools


text:
Please review the `[redshift]` section in [example-config.toml](https://github.com/fullstorydev/hauser/blob/master/example-config.toml) to understand which items should be configured to integrate with your Redshift cluster. Values must be provided for all items.

Core configuration items are:

1. The Redshift credentials required to login to your Redshift host
2. The names of your Export and Sync tables. Tables will be created on your behalf if necessary (assuming that the provided credentials have been granted CREATE permissions on a schema)
3. The AWS IAM Role arn that will be used to import files from S3 into Redshift
4. The database schema used when querying (and creating) the Export and Sync tables

## Database Schema Configuration

The `DatabaseSchema` parameter can accept two different types of values:

1. A schema that exists in your Redshift cluster (including the "public" schema)
2. "search_path"

If "search_path" is provided, hauser will use your database's [search_path](https://docs.aws.amazon.com/redshift/latest/dg/r_search_path.html) configuration to determine which schema to use when accessing and creating tables.


text:
package org.xlcloud.service.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.log4j.Logger;

import org.xlcloud.service.dao.utils.QueryContext;
import org.xlcloud.service.dao.utils.OrderByEntry;

/**
 * Jpa 2.0 implementation of {@link GenericDao} interface
 *
 * @author Tomek Adamczewski, AMG.net
 * @param <Q>
 */
public abstract class JpaGenericDao<T> implements GenericDao<T> {

    @Inject
    private QueryContext queryContext;

    private static final Logger LOG = Logger.getLogger(JpaGenericDao.class);

    @SuppressWarnings( "unchecked" )
    public JpaGenericDao() {
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            persistenceClass = (Class<T>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
            if (LOG.isDebugEnabled()) {
                LOG.debug("persistenceClass for DAO " + this.getClass() + " set to " + persistenceClass);
            }
        } else {
            throw new RuntimeException("could not retreive persistenceClass for DAO " + this.getClass());
        }
    }

    /**
     * Field that lets generically access the type of entity.
     */
    protected Class<T> persistenceClass;

    @PersistenceContext
    protected EntityManager em;

    /** {@inheritDoc} */
    @Override
    public List<T> findAll() {
        return findAll(false);
    }

    /** {@inheritDoc} */
    @Override
    public List<T> findAll(boolean paged) {
        CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
        CriteriaQuery<T> query = criteriaBuilder.createQuery(persistenceClass);
        return getEntityList(query, query.from(persistenceClass), paged);
    }

    /** {@inheritDoc} */
    @Override
    public BigInteger findAllCount() {
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
        Root<T> root = query.from(persistenceClass);
        CriteriaQuery<Long> select = query.select(criteriaBuilder.count(root));
        TypedQuery<Long> typedQuery = em.createQuery(select);
        return BigInteger.valueOf(typedQuery.getSingleResult());
    }

    /** {@inheritDoc} */
    @Override
    public T find(Long id) {
        return em.find(persistenceClass, id);
    }

    /** {@inheritDoc} */
    @Override
    public T createOrUpdate(T object) {
        em.persist(object);
        em.flush();
        return object;
    }

    /** {@inheritDoc} */
    @Override
    public void remove(Long id) {
        em.remove(em.find(persistenceClass, id));
    }

    /** {@inheritDoc} */
    @Override
    public Collection<T> find(Collection<Long> ids) {
        return find(ids, false);
    }

    /** {@inheritDoc} */
    @Override
    public Collection<T> find(Collection<Long> ids, boolean paged) {
        if(ids.isEmpty()) {
            return new ArrayList<T>();
        } else {
            CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
            CriteriaQuery<T> query = criteriaBuilder.createQuery(persistenceClass);

            Root<T> root = query.from(persistenceClass);
            SingularAttribute<? super T, Long> id = root.getModel().getId(Long.class);
            query.where(root.get(id).in(ids));
            return getEntityList(query, root, paged);
        }
    }

    /** {@inheritDoc} */
    @Override
    public BigInteger findCount(Collection<Long> ids) {
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
        Root<T> root = query.from(persistenceClass);
        SingularAttribute<? super T, Long> id = root.getModel().getId(Long.class);
        query.where(root.get(id).in(ids));
        CriteriaQuery<Long> select = query.select(criteriaBuilder.count(root));
        TypedQuery<Long> typedQuery = em.createQuery(select);
        return BigInteger.valueOf(typedQuery.getSingleResult());
    }

    private <Q> TypedQuery<Q> createLimitedQuery(CriteriaQuery<Q> query) {
        TypedQuery<Q> typedQuery = em.createQuery(query);
        if (queryContext.getLimit() != null) {
            typedQuery.setMaxResults(queryContext.getLimit());
        }
        if (queryContext.getOffset() != null) {
            typedQuery.setFirstResult(queryContext.getOffset());
        }
        return typedQuery;
    }

    private List<Order> createOrderList(CriteriaBuilder criteriaBuilder, Root<T> root) {
        List<Order> orderList = new LinkedList<Order>();
        for (OrderByEntry order : queryContext.getOrderbylist()) {
            String modelFieldName = getModelFieldName(order.getKey());
            Path<Object> path = null;
            path = buildOrderPath(root, modelFieldName);
            if (order.isAscending()) {
                orderList.add(criteriaBuilder.asc(path));
            } else {
                orderList.add(criteriaBuilder.desc(path));
            }
        }
        SingularAttribute<? super T, Long> id = root.getModel().getId(Long.class);
        orderList.add(criteriaBuilder.asc(root.get(id.getName())));
        return orderList;
    }

    private Path<Object> buildOrderPath(Root<T> root, String modelFieldName) {
        Path<Object> path = null;
        String[] fields = modelFieldName.split("\\.", -1);
        for (String fName : fields) {
            path = path == null ? root.get(fName) : path.get(fName);
        }
        return path;
    }

    /**
     * Returns create builder from the entity manager.
     * @return new criteria builder
     */
    protected CriteriaBuilder getCriteriaBuilder() {
        return em.getCriteriaBuilder();
    }

    /**
     * Returns results lists, using order list for {@link QueryContext} to sort them
     * and if paged then query only for needed records. X type may be object type T or
     * {@link Tuple}.
     * @param criteriaQuery
     * @param root
     * @param paged Indicates if to limit number of results to the page (true) or to return all records (false)
     * @return
     */
    protected <X> List<X> getResultList(CriteriaQuery<X> criteriaQuery, Root<T> root, boolean paged) {
        List<Order> orderList = createOrderList(em.getCriteriaBuilder(), root);
        criteriaQuery.orderBy(orderList);

        TypedQuery<X> typedQuery = paged ? createLimitedQuery(criteriaQuery) : em.createQuery(criteriaQuery);

        List<X> entities = typedQuery.getResultList();

        return entities == null || entities.isEmpty() ? new ArrayList<X>() : entities;
    }

    /**
     * Returns results lists, using order list for {@link QueryContext} to sort them
     * and if paged then query only for needed records.
     * @param criteriaQuery
     * @param root
     * @param paged Indicates if to limit number of results to the page (true) or to return all records (false)
     * @return
     */
    protected List<T> getEntityList(CriteriaQuery<T> criteriaQuery, Root<T> root, boolean paged) {
        return getResultList(criteriaQuery,root, paged);
    }

    /**
     * Returns the result of the query or null if the queried object was not found.
     * @param criteriaQuery
     * @return entity
     */
    protected T getEntity(CriteriaQuery<T> criteriaQuery) {
        try {
            return em.createQuery(criteriaQuery).getSingleResult();
        } catch (NoResultException e) {
            // That can (and sometimes should) happen.
            return null;
        }
    }

    /**
     * This method must be overriden to provide a method of getting model field name
     * on the base of jaxbName used to pass the order list through {@link QueryContext}.
     * @param jaxbName
     * @return model field name
     */
    protected abstract String getModelFieldName(String jaxbName);

    /**
     * For JUnit tests only.
     */
    protected void setQueryContext(QueryContext queryContext) {
        this.queryContext = queryContext;
    }

}


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

#include "third_party/blink/renderer/platform/fonts/font_matching_metrics.h"

#include "base/metrics/histogram_macros.h"
#include "services/metrics/public/cpp/metrics_utils.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_metric_builder.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_token.h"
#include "third_party/blink/renderer/platform/fonts/font_global_context.h"
#include "third_party/blink/renderer/platform/privacy_budget/identifiability_digest_helpers.h"

namespace {

constexpr double kUkmFontLoadCountBucketSpacing = 1.3;

template <typename T>
HashSet<T> SetIntersection(const HashSet<T>& a, const HashSet<T>& b) {
  HashSet<T> result;
  for (const T& a_value : a) {
    if (b.Contains(a_value))
      result.insert(a_value);
  }
  return result;
}

}  // namespace

namespace blink {

namespace {

bool IdentifiabilityStudyShouldSampleFonts() {
  return IdentifiabilityStudySettings::Get()->ShouldSampleAnyType({
      IdentifiableSurface::Type::kLocalFontLookupByUniqueOrFamilyName,
      IdentifiableSurface::Type::kLocalFontLookupByUniqueNameOnly,
      IdentifiableSurface::Type::kLocalFontLookupByFallbackCharacter,
      IdentifiableSurface::Type::kLocalFontLookupAsLastResort,
      IdentifiableSurface::Type::kGenericFontLookup,
      IdentifiableSurface::Type::kLocalFontLoadPostScriptName,
      IdentifiableSurface::Type::kLocalFontExistenceByUniqueNameOnly,
  });
}

}  // namespace

FontMatchingMetrics::FontMatchingMetrics(
    bool top_level,
    ukm::UkmRecorder* ukm_recorder,
    ukm::SourceId source_id,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : load_context_(top_level ? kTopLevelFrame : kSubframe),
      ukm_recorder_(ukm_recorder),
      source_id_(source_id),
      identifiability_metrics_timer_(
          task_runner,
          this,
          &FontMatchingMetrics::IdentifiabilityMetricsTimerFired) {
  Initialize();
}

FontMatchingMetrics::FontMatchingMetrics(
    ukm::UkmRecorder* ukm_recorder,
    ukm::SourceId source_id,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : load_context_(kWorker),
      ukm_recorder_(ukm_recorder),
      source_id_(source_id),
      identifiability_metrics_timer_(
          task_runner,
          this,
          &FontMatchingMetrics::IdentifiabilityMetricsTimerFired) {
  Initialize();
}

void FontMatchingMetrics::Initialize() {
  // Estimate of average page font use from anecdotal browsing session.
  constexpr unsigned kEstimatedFontCount = 7;
  local_fonts_succeeded_.ReserveCapacityForSize(kEstimatedFontCount);
  local_fonts_failed_.ReserveCapacityForSize(kEstimatedFontCount);
}

void FontMatchingMetrics::ReportSuccessfulFontFamilyMatch(
    const AtomicString& font_family_name) {
  successful_font_families_.insert(font_family_name);
}

void FontMatchingMetrics::ReportFailedFontFamilyMatch(
    const AtomicString& font_family_name) {
  failed_font_families_.insert(font_family_name);
}

void FontMatchingMetrics::ReportSystemFontFamily(
    const AtomicString& font_family_name) {
  system_font_families_.insert(font_family_name);
}

void FontMatchingMetrics::ReportWebFontFamily(
    const AtomicString& font_family_name) {
  web_font_families_.insert(font_family_name);
}

void FontMatchingMetrics::ReportSuccessfulLocalFontMatch(
    const AtomicString& font_name) {
  local_fonts_succeeded_.insert(font_name);
  ReportLocalFontExistenceByUniqueNameOnly(font_name, /*font_exists=*/true);
}

void FontMatchingMetrics::ReportFailedLocalFontMatch(
    const AtomicString& font_name) {
  local_fonts_failed_.insert(font_name);
  ReportLocalFontExistenceByUniqueNameOnly(font_name, /*font_exists=*/false);
}

void FontMatchingMetrics::ReportLocalFontExistenceByUniqueNameOnly(
    const AtomicString& font_name,
    bool font_exists) {
  if (!IdentifiabilityStudySettings::Get()->ShouldSampleType(
          IdentifiableSurface::Type::kLocalFontExistenceByUniqueNameOnly)) {
    return;
  }
  IdentifiableTokenKey input_key(
      IdentifiabilityBenignCaseFoldingStringToken(font_name));
  local_font_existence_by_unique_name_only_.insert(input_key, font_exists);
}

void FontMatchingMetrics::InsertFontHashIntoMap(IdentifiableTokenKey input_key,
                                                SimpleFontData* font_data,
                                                TokenToTokenHashMap& hash_map) {
  DCHECK(IdentifiabilityStudyShouldSampleFonts());
  if (hash_map.Contains(input_key))
    return;
  IdentifiableToken output_token(GetHashForFontData(font_data));
  hash_map.insert(input_key, output_token);

  // We only record postscript name metrics if both the the broader lookup's
  // type and kLocalFontLoadPostScriptName are allowed. (If the former is not,
  // InsertFontHashIntoMap would not be called.)
  if (!font_data ||
      !IdentifiabilityStudySettings::Get()->ShouldSampleType(
          IdentifiableSurface::Type::kLocalFontLoadPostScriptName)) {
    return;
  }
  IdentifiableTokenKey postscript_name_key(
      GetPostScriptNameTokenForFontData(font_data));
  font_load_postscript_name_.insert(postscript_name_key, output_token);
}

IdentifiableTokenBuilder
FontMatchingMetrics::GetTokenBuilderWithFontSelectionRequest(
    const FontDescription& font_description) {
  IdentifiableTokenBuilder builder;
  builder.AddValue(font_description.GetFontSelectionRequest().GetHash());
  return builder;
}

void FontMatchingMetrics::ReportFontLookupByUniqueOrFamilyName(
    const AtomicString& name,
    const FontDescription& font_description,
    SimpleFontData* resulting_font_data) {
  if (!IdentifiabilityStudySettings::Get()->ShouldSampleType(
          IdentifiableSurface::Type::kLocalFontLookupByUniqueOrFamilyName)) {
    return;
  }
  OnFontLookup();

  IdentifiableTokenBuilder builder =
      GetTokenBuilderWithFontSelectionRequest(font_description);

  // Font name lookups are case-insensitive.
  builder.AddToken(IdentifiabilityBenignCaseFoldingStringToken(name));

  IdentifiableTokenKey input_key(builder.GetToken());
  InsertFontHashIntoMap(input_key, resulting_font_data,
                        font_lookups_by_unique_or_family_name_);
}

void FontMatchingMetrics::ReportFontLookupByUniqueNameOnly(
    const AtomicString& name,
    const FontDescription& font_description,
    SimpleFontData* resulting_font_data,
    bool is_loading_fallback) {
  // We ignore lookups that result in loading fallbacks for now as they should
  // only be temporary.
  if (is_loading_fallback ||
      !IdentifiabilityStudySettings::Get()->ShouldSampleType(
          IdentifiableSurface::Type::kLocalFontLookupByUniqueNameOnly)) {
    return;
  }
  OnFontLookup();

  IdentifiableTokenBuilder builder =
      GetTokenBuilderWithFontSelectionRequest(font_description);

  // Font name lookups are case-insensitive.
  builder.AddToken(IdentifiabilityBenignCaseFoldingStringToken(name));

  IdentifiableTokenKey input_key(builder.GetToken());
  InsertFontHashIntoMap(input_key, resulting_font_data,
                        font_lookups_by_unique_name_only_);
}

void FontMatchingMetrics::ReportFontLookupByFallbackCharacter(
    UChar32 fallback_character,
    FontFallbackPriority fallback_priority,
    const FontDescription& font_description,
    SimpleFontData* resulting_font_data) {
  if (!IdentifiabilityStudySettings::Get()->ShouldSampleType(
          IdentifiableSurface::Type::kLocalFontLookupByFallbackCharacter)) {
    return;
  }
  OnFontLookup();

  IdentifiableTokenBuilder builder =
      GetTokenBuilderWithFontSelectionRequest(font_description);
  builder.AddValue(fallback_character)
      .AddToken(IdentifiableToken(fallback_priority));

  IdentifiableTokenKey input_key(builder.GetToken());
  InsertFontHashIntoMap(input_key, resulting_font_data,
                        font_lookups_by_fallback_character_);
}

void FontMatchingMetrics::ReportLastResortFallbackFontLookup(
    const FontDescription& font_description,
    SimpleFontData* resulting_font_data) {
  if (!IdentifiabilityStudySettings::Get()->ShouldSampleType(
          IdentifiableSurface::Type::kLocalFontLookupAsLastResort)) {
    return;
  }
  OnFontLookup();

  IdentifiableTokenBuilder builder =
      GetTokenBuilderWithFontSelectionRequest(font_description);

  IdentifiableTokenKey input_key(builder.GetToken());
  InsertFontHashIntoMap(input_key, resulting_font_data,
                        font_lookups_as_last_resort_);
}

void FontMatchingMetrics::ReportFontFamilyLookupByGenericFamily(
    const AtomicString& generic_font_family_name,
    UScriptCode script,
    FontDescription::GenericFamilyType generic_family_type,
    const AtomicString& resulting_font_name) {
  if (!IdentifiabilityStudySettings::Get()->ShouldSampleType(
          IdentifiableSurface::Type::kGenericFontLookup)) {
    return;
  }
  OnFontLookup();

  // kStandardFamily/kWebkitBodyFamily lookups override the
  // |generic_font_family_name|. See FontSelector::FamilyNameFromSettings.
  // No need to be case-insensitive as generic names should already be
  // lowercase.
  DCHECK(generic_family_type == FontDescription::kStandardFamily ||
         generic_family_type == FontDescription::kWebkitBodyFamily ||
         generic_font_family_name == generic_font_family_name.LowerASCII());
  IdentifiableToken lookup_name_token = IdentifiabilityBenignStringToken(
      (generic_family_type == FontDescription::kStandardFamily ||
       generic_family_type == FontDescription::kWebkitBodyFamily)
          ? font_family_names::kWebkitStandard
          : generic_font_family_name);

  IdentifiableTokenBuilder builder;
  builder.AddToken(lookup_name_token).AddToken(IdentifiableToken(script));
  IdentifiableTokenKey input_key(builder.GetToken());

  // Font name lookups are case-insensitive.
  generic_font_lookups_.insert(
      input_key,
      IdentifiabilityBenignCaseFoldingStringToken(resulting_font_name));
}

void FontMatchingMetrics::ReportEmojiSegmentGlyphCoverage(
    unsigned num_clusters,
    unsigned num_broken_clusters) {
  total_emoji_clusters_shaped_ += num_clusters;
  total_broken_emoji_clusters_ += num_broken_clusters;
}

void FontMatchingMetrics::PublishIdentifiabilityMetrics() {
  if (!IdentifiabilityStudyShouldSampleFonts())
    return;

  IdentifiabilityMetricBuilder builder(source_id_);

  std::pair<TokenToTokenHashMap*, IdentifiableSurface::Type>
      hash_maps_with_corresponding_surface_types[] = {
          {&font_lookups_by_unique_or_family_name_,
           IdentifiableSurface::Type::kLocalFontLookupByUniqueOrFamilyName},
          {&font_lookups_by_unique_name_only_,
           IdentifiableSurface::Type::kLocalFontLookupByUniqueNameOnly},
          {&font_lookups_by_fallback_character_,
           IdentifiableSurface::Type::kLocalFontLookupByFallbackCharacter},
          {&font_lookups_as_last_resort_,
           IdentifiableSurface::Type::kLocalFontLookupAsLastResort},
          {&generic_font_lookups_,
           IdentifiableSurface::Type::kGenericFontLookup},
          {&font_load_postscript_name_,
           IdentifiableSurface::Type::kLocalFontLoadPostScriptName},
          {&local_font_existence_by_unique_name_only_,
           IdentifiableSurface::Type::kLocalFontExistenceByUniqueNameOnly},
      };

  for (const auto& surface_entry : hash_maps_with_corresponding_surface_types) {
    TokenToTokenHashMap* hash_map = surface_entry.first;
    const IdentifiableSurface::Type surface_type = surface_entry.second;
    if (IdentifiabilityStudySettings::Get()->ShouldSampleType(surface_type)) {
      for (const auto& individual_lookup : *hash_map) {
        builder.Add(IdentifiableSurface::FromTypeAndToken(
                        surface_type, individual_lookup.key.token),
                    individual_lookup.value);
      }
    }
    hash_map->clear();
  }

  builder.Record(ukm_recorder_);
}

void FontMatchingMetrics::PublishUkmMetrics() {
  ukm::builders::FontMatchAttempts(source_id_)
      .SetLoadContext(load_context_)
      .SetSystemFontFamilySuccesses(ukm::GetExponentialBucketMin(
          SetIntersection(successful_font_families_, system_font_families_)
              .size(),
          kUkmFontLoadCountBucketSpacing))
      .SetSystemFontFamilyFailures(ukm::GetExponentialBucketMin(
          SetIntersection(failed_font_families_, system_font_families_).size(),
          kUkmFontLoadCountBucketSpacing))
      .SetSystemFontFamilyTotal(ukm::GetExponentialBucketMin(
          system_font_families_.size(), kUkmFontLoadCountBucketSpacing))
      .SetWebFontFamilySuccesses(ukm::GetExponentialBucketMin(
          SetIntersection(successful_font_families_, web_font_families_).size(),
          kUkmFontLoadCountBucketSpacing))
      .SetWebFontFamilyFailures(ukm::GetExponentialBucketMin(
          SetIntersection(failed_font_families_, web_font_families_).size(),
          kUkmFontLoadCountBucketSpacing))
      .SetWebFontFamilyTotal(ukm::GetExponentialBucketMin(
          web_font_families_.size(), kUkmFontLoadCountBucketSpacing))
      .SetLocalFontFailures(ukm::GetExponentialBucketMin(
          local_fonts_failed_.size(), kUkmFontLoadCountBucketSpacing))
      .SetLocalFontSuccesses(ukm::GetExponentialBucketMin(
          local_fonts_succeeded_.size(), kUkmFontLoadCountBucketSpacing))
      .SetLocalFontTotal(ukm::GetExponentialBucketMin(
          local_fonts_succeeded_.size() + local_fonts_failed_.size(),
          kUkmFontLoadCountBucketSpacing))
      .Record(ukm_recorder_);
}

void FontMatchingMetrics::PublishEmojiGlyphMetrics() {
  DCHECK_LE(total_broken_emoji_clusters_, total_emoji_clusters_shaped_);
  if (total_emoji_clusters_shaped_) {
    double percentage = static_cast<double>(total_broken_emoji_clusters_) /
                        total_emoji_clusters_shaped_;
    UMA_HISTOGRAM_PERCENTAGE("Blink.Fonts.EmojiClusterBrokenness",
                             static_cast<int>(round(percentage * 100)));
  }
}

void FontMatchingMetrics::OnFontLookup() {
  DCHECK(IdentifiabilityStudyShouldSampleFonts());
  if (!identifiability_metrics_timer_.IsActive()) {
    identifiability_metrics_timer_.StartOneShot(base::Minutes(1), FROM_HERE);
  }
}

void FontMatchingMetrics::IdentifiabilityMetricsTimerFired(TimerBase*) {
  PublishIdentifiabilityMetrics();
}

void FontMatchingMetrics::PublishAllMetrics() {
  PublishIdentifiabilityMetrics();
  PublishUkmMetrics();
  PublishEmojiGlyphMetrics();
}

int64_t FontMatchingMetrics::GetHashForFontData(SimpleFontData* font_data) {
  return font_data ? FontGlobalContext::Get()
                         .GetOrComputeTypefaceDigest(font_data->PlatformData())
                         .ToUkmMetricValue()
                   : 0;
}

IdentifiableToken FontMatchingMetrics::GetPostScriptNameTokenForFontData(
    SimpleFontData* font_data) {
  DCHECK(font_data);
  return FontGlobalContext::Get().GetOrComputePostScriptNameDigest(
      font_data->PlatformData());
}

}  // namespace blink


text:
<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\Config\RectorConfig;
use Rector\Doctrine\Set\DoctrineSetList;
use Rector\Set\ValueObject\LevelSetList;
use Rector\PHPUnit\Set\PHPUnitSetList;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->paths([
        __DIR__ . '/src',
        __DIR__ . '/tests',
        __DIR__ . '/tests-unit',
    ]);

    // register a single rule
    $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);

    $rectorConfig->sets([
        PHPUnitSetList::PHPUNIT_91,
        DoctrineSetList::DOCTRINE_DBAL_30,
        DoctrineSetList::DOCTRINE_DBAL_211,
        DoctrineSetList::DOCTRINE_CODE_QUALITY,
    ]);
};


text:
app.controller('ResultCtrl', function ($scope, $stateParams) {
    $scope.title = 'Test Results'
});


text:
if [[ -o login ]]; then
    if [ x"$TERM" != "xscreen" ]; then
        # Indicates start of command output. Runs just before command executes.
        iterm2_before_cmd_executes() {
            printf "\033]133;C;\r\007"
        }

        iterm2_set_user_var() {
            printf "\033]1337;SetUserVar=%s=%s\007" "$1" $(printf "%s" "$2" | base64)
        }

        # Users can write their own version of this method. It should call
        # iterm2_set_user_var but not produce any other output.
        # e.g., iterm2_set_user_var currentDirectory $PWD
        # Accessible in iTerm2 (in a badge now, elsewhere in the future) as
        # \(user.currentDirectory).
        iterm2_print_user_vars() {
        }

        iterm2_print_state_data() {
            printf "\033]1337;RemoteHost=%s@%s\007" "$USER" "$iterm2_hostname"
            printf "\033]1337;CurrentDir=%s\007" "$PWD"
            iterm2_print_user_vars
        }

        # Report return code of command; runs after command finishes but before prompt
        iterm2_after_cmd_executes() {
            printf "\033]133;D;$?\007"
            iterm2_print_state_data
        }

        # Mark start of prompt
        iterm2_prompt_start() {
            printf "\033]133;A\007"
        }

        # Mark end of prompt
        iterm2_prompt_end() {
            printf "\033]133;B\007"
        }

        iterm2_precmd() {
            iterm2_after_cmd_executes

            # The user or another precmd may have changed PS1 (e.g., powerline-shell).
            # Ensure that our escape sequences are added back in.
            if [[ "$ITERM2_SAVED_PS1" != "$PS1" ]]; then
                PS1="%{$(iterm2_prompt_start)%}$PS1%{$(iterm2_prompt_end)%}"
                ITERM2_SAVED_PS1="$PS1"
            fi
        }

        iterm2_preexec() {
            PS1="$ITERM2_SAVED_PS1"
            iterm2_before_cmd_executes
        }

        # If hostname -f is slow on your system, set iterm2_hostname prior to sourcing this script.
        [[ -z "$iterm2_hostname" ]] && iterm2_hostname=`hostname -f`

        [[ -z $precmd_functions ]] && precmd_functions=()
        precmd_functions=($precmd_functions iterm2_precmd)

        [[ -z $preexec_functions ]] && preexec_functions=()
        preexec_functions=($preexec_functions iterm2_preexec)

        iterm2_print_state_data
        printf "\033]1337;ShellIntegrationVersion=1\007"
    fi
fi


text:
var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var ActivitySchema   = new Schema({
    name:String,
    description:String,
    activitytype:String,
    persons:[{type: Schema.ObjectId, ref: 'Person' }],
    personsLists: Array,
    images:Array,
    url:String,
    createdAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Activity', ActivitySchema);


text:
use libc::{c_char, c_int, execvp, PRIO_PROCESS};
use std::ffi::CString;
use std::io::Error;
use std::ptr;

use clap::{crate_version, Arg, ArgAction, Command};
use uucore::{
    error::{set_exit_code, UClapError, UResult, USimpleError, UUsageError},
    format_usage, show_error, show_warning,
};

pub mod options {
    pub static ADJUSTMENT: &str = "adjustment";
    pub static COMMAND: &str = "COMMAND";
}

const ABOUT: &str = "\
    Run COMMAND with an adjusted niceness, which affects process scheduling. \
    With no COMMAND, print the current niceness.  Niceness values range from at \
    least -20 (most favorable to the process) to 19 (least favorable to the \
    process).";
const USAGE: &str = "{} [OPTIONS] [COMMAND [ARGS]]";

#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
    let matches = uu_app().try_get_matches_from(args).with_exit_code(125)?;

    nix::errno::Errno::clear();
    let mut niceness = unsafe { libc::getpriority(PRIO_PROCESS, 0) };
    if Error::last_os_error().raw_os_error().unwrap() != 0 {
        return Err(USimpleError::new(
            125,
            format!("getpriority: {}", Error::last_os_error()),
        ));
    }

    let adjustment = match matches.get_one::<String>(options::ADJUSTMENT) {
        Some(nstr) => {
            if !matches.contains_id(options::COMMAND) {
                return Err(UUsageError::new(
                    125,
                    "A command must be given with an adjustment.",
                ));
            }
            match nstr.parse() {
                Ok(num) => num,
                Err(e) => {
                    return Err(USimpleError::new(
                        125,
                        format!("\"{}\" is not a valid number: {}", nstr, e),
                    ))
                }
            }
        }
        None => {
            if !matches.contains_id(options::COMMAND) {
                println!("{}", niceness);
                return Ok(());
            }
            10_i32
        }
    };

    niceness += adjustment;
    if unsafe { libc::setpriority(PRIO_PROCESS, 0, niceness) } == -1 {
        show_warning!("setpriority: {}", Error::last_os_error());
    }

    let cstrs: Vec<CString> = matches
        .get_many::<String>(options::COMMAND)
        .unwrap()
        .map(|x| CString::new(x.as_bytes()).unwrap())
        .collect();

    let mut args: Vec<*const c_char> = cstrs.iter().map(|s| s.as_ptr()).collect();
    args.push(ptr::null::<c_char>());
    unsafe {
        execvp(args[0], args.as_mut_ptr());
    }

    show_error!("execvp: {}", Error::last_os_error());
    let exit_code = if Error::last_os_error().raw_os_error().unwrap() as c_int == libc::ENOENT {
        127
    } else {
        126
    };
    set_exit_code(exit_code);
    Ok(())
}

pub fn uu_app() -> Command {
    Command::new(uucore::util_name())
        .about(ABOUT)
        .override_usage(format_usage(USAGE))
        .trailing_var_arg(true)
        .infer_long_args(true)
        .version(crate_version!())
        .arg(
            Arg::new(options::ADJUSTMENT)
                .short('n')
                .long(options::ADJUSTMENT)
                .help("add N to the niceness (default is 10)")
                .allow_hyphen_values(true),
        )
        .arg(
            Arg::new(options::COMMAND)
                .action(ArgAction::Append)
                .value_hint(clap::ValueHint::CommandName),
        )
}


text:
> Swap class names of elements using responsive attributes.

## Install

```shell
npm install @odopod/odo-responsive-classes --save
```

## Quick Start

```html
<div class="odo-responsive-classes" data-class.xs="green with-padding" data-class.sm="blue"></div>
```

## [Documentation][permalink]

Visit the [Odo component directory][permalink] for demos, code examples, and documentation.

[permalink]: http://code.odopod.com/odo-responsive-classes/


text:
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_DISTRIBUTED_MANAGER_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_DISTRIBUTED_MANAGER_H_

#include "tensorflow/c/eager/immediate_execution_context.h"
#include "tensorflow/c/eager/immediate_execution_distributed_manager.h"
#include "tensorflow/core/common_runtime/eager/context.h"
#include "tensorflow/core/platform/status.h"

namespace tensorflow {
#if !defined(IS_MOBILE_PLATFORM)
class EagerContext;
class ServerDef;

class EagerContextDistributedManager
    : public ImmediateExecutionDistributedManager {
 public:
  explicit EagerContextDistributedManager(EagerContext* context)
      : context_(context) {}

  Status SetOrUpdateServerDef(const ServerDef& server_def, bool reset_context,
                              int keep_alive_secs) override;

  Status EnableCollectiveOps(const ServerDef& server_def) override;

  Status CheckRemoteAlive(const std::string& remote_task_name,
                          bool* is_alive) override;

 private:
  EagerContext* context_;
};
#endif  // !IS_MOBILE_PLATFORM
}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_DISTRIBUTED_MANAGER_H_


text:
use header::EntityTag;

header! {
    #[doc="`If-Match` header, defined in"]
    #[doc="[RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1)"]
    #[doc=""]
    #[doc="The `If-Match` header field makes the request method conditional on"]
    #[doc="the recipient origin server either having at least one current"]
    #[doc="representation of the target resource, when the field-value is \"*\","]
    #[doc="or having a current representation of the target resource that has an"]
    #[doc="entity-tag matching a member of the list of entity-tags provided in"]
    #[doc="the field-value."]
    #[doc=""]
    #[doc="An origin server MUST use the strong comparison function when"]
    #[doc="comparing entity-tags for `If-Match`, since the client"]
    #[doc="intends this precondition to prevent the method from being applied if"]
    #[doc="there have been any changes to the representation data."]
    #[doc=""]
    #[doc="# ABNF"]
    #[doc="```plain"]
    #[doc="If-Match = \"*\" / 1#entity-tag"]
    #[doc="```"]
    #[doc=""]
    #[doc="# Example values"]
    #[doc="* `\"xyzzy\"`"]
    #[doc="* \"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""]
    (IfMatch, "If-Match") => {Any / (EntityTag)+}

    test_if_match {
        test_header!(
            test1,
            vec![b"\"xyzzy\""],
            Some(HeaderField::Items(
                vec![EntityTag::new(false, "xyzzy".to_string())])));
        test_header!(
            test2,
            vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""],
            Some(HeaderField::Items(
                vec![EntityTag::new(false, "xyzzy".to_string()),
                     EntityTag::new(false, "r2d2xxxx".to_string()),
                     EntityTag::new(false, "c3piozzzz".to_string())])));
        test_header!(test3, vec![b"*"], Some(IfMatch::Any));
    }
}

bench_header!(star, IfMatch, { vec![b"*".to_vec()] });
bench_header!(single , IfMatch, { vec![b"\"xyzzy\"".to_vec()] });
bench_header!(multi, IfMatch,
              { vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"".to_vec()] });


text: this file keeps the directory even if contents are ignored


text:
#pragma once
#include <aws/lex-models/LexModelBuildingService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace LexModelBuildingService
{
namespace Model
{
  enum class ExportType
  {
    NOT_SET,
    ALEXA_SKILLS_KIT,
    LEX
  };

namespace ExportTypeMapper
{
AWS_LEXMODELBUILDINGSERVICE_API ExportType GetExportTypeForName(const Aws::String& name);

AWS_LEXMODELBUILDINGSERVICE_API Aws::String GetNameForExportType(ExportType value);
} // namespace ExportTypeMapper
} // namespace Model
} // namespace LexModelBuildingService
} // namespace Aws


text:
<?php

namespace Magento\Customer\Api\Data;

/**
 * Interface for customer groups search results.
 * @api
 */
interface GroupSearchResultsInterface extends \Magento\Framework\Api\SearchResultsInterface
{
    /**
     * Get customer groups list.
     *
     * @return \Magento\Customer\Api\Data\GroupInterface[]
     */
    public function getItems();

    /**
     * Set customer groups list.
     *
     * @api
     * @param \Magento\Customer\Api\Data\GroupInterface[] $items
     * @return $this
     */
    public function setItems(array $items);
}


text:
package org.beigesoft.service.persist.xml;

import java.util.List;

public abstract class ASaxModelFiller<M> implements ISaxModelFiller {

  private M model;

  private final List<String> pathCurrent;

  private final String namePersistable;

  public ASaxModelFiller(String namePersistable, List<String> pathCurrent) {
    this.namePersistable = namePersistable;
    this.pathCurrent = pathCurrent;
  }

  @Override
  public void addElementToPath(String localName) {
    pathCurrent.add(localName);
  }

  @Override
  public void removeElementToPath(String localName) throws Exception {
    if(!pathCurrent.get(pathCurrent.size()-1).equals(localName)) {
      StringBuffer currPath = new StringBuffer();
      for(String nm : pathCurrent) {
        currPath.append("/" + nm);
      }
      throw new Exception("Inconsistent XML or algorithm error, current path is " + currPath +
          ", but ended element is " + localName);
    }
    pathCurrent.remove(pathCurrent.size()-1);
  }

  @Override
  public boolean handleStartElement(String localName) {
    return false;
  }

  @Override
  public boolean handleEndElement(String localName) throws Exception {
    return false;
  }

  public String toStringOrNull(String value) {
    if(value.equals("<Null/>")) {
      return null;
    }
    return value;
  }

  public Integer toIntegerOrNull(String value) {
    if(value.equals("<Null/>")) {
      return null;
    }
    return Integer.valueOf(value);
  }

  public void setModelAndPrepare(M model) {
    this.model = model;
  }

  public boolean isConsumableForElement(String elementName) {
    int idx = getPathCurrent().size() - 2;
    return getModel() != null && idx >= 0 && getNamePersistable().equals(getPathCurrent().get(idx));
  }

  public boolean isConsumableForAttribute(String elementName, String attrName) {
    return getModel() != null && getNamePersistable().equals(elementName);
  }

  public String makeString(String str, String value) {
    if(str == null) {
      return value;
    }
    else {
      return str + value;
    }
  }

  //SGS:
  public M getModel() {
    return model;
  }

  public List<String> getPathCurrent() {
    return pathCurrent;
  }

  public String getNamePersistable() {
    return namePersistable;
  }
}


text:
import os
import tkinter
from tkinter import *

root = Tk()

def runClient(event):
    root.destroy()
    os.system('client.bat')

def runUsers(event):
    root.destroy()
    os.system('users.bat')

btnClient = Button(root, text='Авторизация', )
btnClient.bind('<Button-1>', runClient)
btnClient.pack()

btnUsers = Button(root, text='Работа с пользователями')
btnUsers.bind('<Button-1>', runUsers)
btnUsers.pack()

root.mainloop()


text:
<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Rol extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    public static $rules = array(
        'name'    => 'required',
        // 'description' => 'required',
    );

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'roles';

    public function users()
    {
        return $this->hasMany('User','id_rol','id');
    }

}


text:
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Telegram.Bot.Converters;
using Telegram.Bot.Types.Enums;

namespace Telegram.Bot.Types.InputFiles
{
    /// <summary>
    /// Used for sending files to Telegram
    /// </summary>
    [JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
    [JsonConverter(typeof(InputFileConverter))]
    public class InputTelegramFile : InputFileStream
    {
        /// <summary>
        /// Id of a file that exists on Telegram servers
        /// </summary>
        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string? FileId { get; private protected set; }

        /// <summary>
        ///  Constructs an <see cref="InputTelegramFile"/> with a <see cref="FileType"/>
        /// </summary>
        protected InputTelegramFile(FileType fileType)
            : base(fileType)
        { }

        /// <summary>
        /// Constructs an <see cref="InputTelegramFile"/> from a <see cref="Stream"/> and a file name
        /// </summary>
        /// <param name="content">A <see cref="Stream"/> containing a file to send</param>
        /// <param name="fileName">A name of the file</param>
        public InputTelegramFile(Stream content, string? fileName = default)
            : base(content, fileName)
        { }

        /// <summary>
        /// Constructs an <see cref="InputTelegramFile"/> with a <paramref name="fileId"/>
        /// </summary>
        /// <param name="fileId">A file identifier</param>
        public InputTelegramFile(string fileId) : base(FileType.Id) => FileId = fileId;

        /// <summary>
        /// Constructs an <see cref="InputTelegramFile"/> from a <see cref="Stream"/>
        /// </summary>
        /// <param name="stream">A <see cref="Stream"/> containing a file to send</param>
        [return: NotNullIfNotNull("stream")]
        public static implicit operator InputTelegramFile?(Stream? stream) =>
            stream is null ? default : new InputTelegramFile(stream);

        /// <summary>
        /// Constructs an <see cref="InputTelegramFile"/> with a <paramref name="fileId"/>
        /// </summary>
        /// <param name="fileId">A file identifier</param>
        [return: NotNullIfNotNull("fileId")]
        public static implicit operator InputTelegramFile?(string? fileId) =>
            fileId is null ? default : new InputTelegramFile(fileId);
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>GIS on Dripping Data</title>
    <link>/tags/gis/</link>
    <description>Recent content in GIS on Dripping Data</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Fri, 26 May 2017 00:00:00 +0000</lastBuildDate><atom:link href="/tags/gis/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>King Tides Citizen Science Project</title>
      <link>/2017/05/26/king-tides-gis/</link>
      <pubDate>Fri, 26 May 2017 00:00:00 +0000</pubDate>

      <guid>/2017/05/26/king-tides-gis/</guid>
      <description>I read in the newspaper that the University of Hawaii was recruiting &ldquo;citizen scientists&rdquo; to help document the impact of this week&rsquo;s &ldquo;king tides&rdquo; on our coastline. I uploaded some photos to the website but also found that we could download the dataset. I took this as an opportunity to learn something about geographic information systems (GIS) and R, and the end result was a pretty nice map of all the places that were photographed this week.</description>
    </item>

  </channel>
</rss>


text:
package snapshot

import (
	"context"
	"sync"

	"github.com/containerd/containerd/leases"
	"github.com/sirupsen/logrus"
)

type sLM struct {
	manager leases.Manager
	s       *snapshotter

	mu         sync.Mutex
	byLease    map[string]map[string]struct{}
	bySnapshot map[string]map[string]struct{}
}

func newLeaseManager(s *snapshotter, lm leases.Manager) *sLM {
	return &sLM{
		s:       s,
		manager: lm,

		byLease:    map[string]map[string]struct{}{},
		bySnapshot: map[string]map[string]struct{}{},
	}
}

func (l *sLM) Create(ctx context.Context, opts ...leases.Opt) (leases.Lease, error) {
	return l.manager.Create(ctx, opts...)
}

func (l *sLM) Delete(ctx context.Context, lease leases.Lease, opts ...leases.DeleteOpt) error {
	if err := l.manager.Delete(ctx, lease, opts...); err != nil {
		return err
	}
	l.mu.Lock()
	if snaps, ok := l.byLease[lease.ID]; ok {
		for sID := range snaps {
			l.delRef(lease.ID, sID)
		}
	}
	l.mu.Unlock()
	return nil
}

func (l *sLM) List(ctx context.Context, filters ...string) ([]leases.Lease, error) {
	return l.manager.List(ctx, filters...)
}

func (l *sLM) AddResource(ctx context.Context, lease leases.Lease, resource leases.Resource) error {
	if err := l.manager.AddResource(ctx, lease, resource); err != nil {
		return err
	}
	if resource.Type == "snapshots/default" {
		l.mu.Lock()
		l.addRef(lease.ID, resource.ID)
		l.mu.Unlock()
	}
	return nil
}

func (l *sLM) DeleteResource(ctx context.Context, lease leases.Lease, resource leases.Resource) error {
	if err := l.manager.DeleteResource(ctx, lease, resource); err != nil {
		return err
	}
	if resource.Type == "snapshots/default" {
		l.mu.Lock()
		l.delRef(lease.ID, resource.ID)
		l.mu.Unlock()
	}
	return nil
}

func (l *sLM) ListResources(ctx context.Context, lease leases.Lease) ([]leases.Resource, error) {
	return l.manager.ListResources(ctx, lease)
}

func (l *sLM) addRef(lID, sID string) {
	load := false
	snapshots, ok := l.byLease[lID]
	if !ok {
		snapshots = map[string]struct{}{}
		l.byLease[lID] = snapshots
	}
	if _, ok := snapshots[sID]; !ok {
		snapshots[sID] = struct{}{}
	}
	leases, ok := l.bySnapshot[sID]
	if !ok {
		leases = map[string]struct{}{}
		l.byLease[sID] = leases
		load = true
	}
	if _, ok := leases[lID]; !ok {
		leases[lID] = struct{}{}
	}

	if load {
		l.s.getLayer(sID, true)
	}
}

func (l *sLM) delRef(lID, sID string) {
	snapshots, ok := l.byLease[lID]
	if !ok {
		delete(snapshots, sID)
		if len(snapshots) == 0 {
			delete(l.byLease, lID)
		}
	}
	leases, ok := l.bySnapshot[sID]
	if !ok {
		delete(leases, lID)
		if len(leases) == 0 {
			delete(l.bySnapshot, sID)
			if err := l.s.remove(context.TODO(), sID); err != nil {
				logrus.Warnf("failed to remove snapshot %v", sID)
			}
		}
	}
}


text:
package io.druid.java.util.metrics;

import io.druid.java.util.common.RE;

import java.lang.management.ManagementFactory;
import java.util.regex.Pattern;

/**
 * For systems that for whatever reason cannot use Sigar (through io.druid.java.util.metrics.SigarPidDiscoverer ),
 * this attempts to get the PID from the JVM "name".
 */
public class JvmPidDiscoverer implements PidDiscoverer
{
  private static final JvmPidDiscoverer INSTANCE = new JvmPidDiscoverer();

  public static JvmPidDiscoverer instance()
  {
    return INSTANCE;
  }

  /**
   * use {JvmPidDiscoverer.instance()}
   */
  private JvmPidDiscoverer()
  {
  }

  /**
   * Returns the PID as a best guess. This uses methods that are not guaranteed to actually be the PID.
   * <p>
   * TODO: switch to ProcessHandle.current().getPid() for java9 potentially
   *
   * @return the PID of the current jvm if available
   *
   * @throws RuntimeException if the pid cannot be determined
   */
  @Override
  public long getPid()
  {
    return Inner.PID;
  }

  private static class Inner
  {
    private static final long PID;

    static {
      final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
      final String[] nameSplits = jvmName.split(Pattern.quote("@"));
      if (nameSplits.length != 2) {
        throw new RE("Unable to determine pid from [%s]", jvmName);
      }
      try {
        PID = Long.parseLong(nameSplits[0]);
      }
      catch (NumberFormatException nfe) {
        throw new RE(nfe, "Unable to determine pid from [%s]", jvmName);
      }
    }
  }
}


text:
using System;

namespace Gnu.MP.BrickCoinProtocol
{
	public class SequenceLock
	{
		public SequenceLock(int minHeight, DateTimeOffset minTime)
		{
			MinHeight = minHeight;
			MinTime = minTime;
		}
		public SequenceLock(int minHeight, long minTime)
			: this(minHeight, Utils.UnixTimeToDateTime(minTime))
		{
		}
		public int MinHeight
		{
			get;
			set;
		}
		public DateTimeOffset MinTime
		{
			get;
			set;
		}

		public bool Evaluate(ChainedBlock block)
		{
			var nBlockTime = block.Previous == null ? Utils.UnixTimeToDateTime(0) : block.Previous.GetMedianTimePast();
			return this.MinHeight < block.Height && this.MinTime < nBlockTime;
		}
	}
}


text:
module.exports = {
    usage: "Tell **everyone** you'd like to **play a game**. May **specify a game** if desired. Uses an **@everyone mention** if the user has permission to do so.\n\n`letsplay [game] or [none]`",
    dm: false,
    delete: true,
    cooldown: 30,
    process: (msg, args) => {
        return new Promise(resolve => {
            //If args sent use those as the game otherwise just have it be 'a game'
            args = args ? args : "a game";
            if (msg.channel.permissionsOf(msg.author.id).has('mentionEveryone')) resolve({
                message: `🎮 @everyone, **${msg.author.username}** would like to play ${args}! 🎮`,
                disableEveryone: false
            })
            else resolve({
                message: `🎮 Everyone, **${msg.author.username}** would like to play ${args}! 🎮`
            })
        });
    }
}


text:
package ru.zconstz.simuctor

import akka.actor.Actor

class Animal extends Actor {

  def receive = {
    case GameTick => {

    }
  }
}


text:
package org.springframework.boot.actuate.health;

import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import org.springframework.boot.actuate.endpoint.SecurityContext;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.Selector.Match;
import org.springframework.boot.actuate.endpoint.http.ApiVersion;
import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse;
import org.springframework.boot.actuate.endpoint.web.annotation.EndpointWebExtension;

/**
 * {@link EndpointWebExtension @EndpointWebExtension} for the {@link HealthEndpoint}.
 *
 * @author Christian Dupuis
 * @author Dave Syer
 * @author Andy Wilkinson
 * @author Phillip Webb
 * @author Eddú Meléndez
 * @author Madhura Bhave
 * @author Stephane Nicoll
 * @author Scott Frederick
 * @since 2.0.0
 */
@EndpointWebExtension(endpoint = HealthEndpoint.class)
public class HealthEndpointWebExtension extends HealthEndpointSupport<HealthContributor, HealthComponent> {

	private static final String[] NO_PATH = {};

	/**
	 * Create a new {@link HealthEndpointWebExtension} instance.
	 * @param registry the health contributor registry
	 * @param groups the health endpoint groups
	 */
	public HealthEndpointWebExtension(HealthContributorRegistry registry, HealthEndpointGroups groups) {
		super(registry, groups);
	}

	@ReadOperation
	public WebEndpointResponse<HealthComponent> health(ApiVersion apiVersion, SecurityContext securityContext) {
		return health(apiVersion, securityContext, false, NO_PATH);
	}

	@ReadOperation
	public WebEndpointResponse<HealthComponent> health(ApiVersion apiVersion, SecurityContext securityContext,
			@Selector(match = Match.ALL_REMAINING) String... path) {
		return health(apiVersion, securityContext, false, path);
	}

	public WebEndpointResponse<HealthComponent> health(ApiVersion apiVersion, SecurityContext securityContext,
			boolean showAll, String... path) {
		HealthResult<HealthComponent> result = getHealth(apiVersion, securityContext, showAll, path);
		if (result == null) {
			return (Arrays.equals(path, NO_PATH))
					? new WebEndpointResponse<>(DEFAULT_HEALTH, WebEndpointResponse.STATUS_OK)
					: new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND);
		}
		HealthComponent health = result.getHealth();
		HealthEndpointGroup group = result.getGroup();
		int statusCode = group.getHttpCodeStatusMapper().getStatusCode(health.getStatus());
		return new WebEndpointResponse<>(health, statusCode);
	}

	@Override
	protected HealthComponent getHealth(HealthContributor contributor, boolean includeDetails) {
		return ((HealthIndicator) contributor).getHealth(includeDetails);
	}

	@Override
	protected HealthComponent aggregateContributions(ApiVersion apiVersion, Map<String, HealthComponent> contributions,
			StatusAggregator statusAggregator, boolean showComponents, Set<String> groupNames) {
		return getCompositeHealth(apiVersion, contributions, statusAggregator, showComponents, groupNames);
	}

}


text:
package org.apache.activemq.artemis.cli.commands.queue;

import io.airlift.airline.Command;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.management.ManagementHelper;
import org.apache.activemq.artemis.cli.commands.ActionContext;

@Command(name = "create", description = "create a queue or topic")
public class CreateQueue extends QueueAbstract {

   @Override
   public Object execute(ActionContext context) throws Exception {
      super.execute(context);
      createQueue(context);
      return null;
   }

   private void createQueue(final ActionContext context) throws Exception {
      performCoreManagement(new ManagementCallback<ClientMessage>() {
         @Override
         public void setUpInvocation(ClientMessage message) throws Exception {
            ManagementHelper.putOperationInvocation(message, "broker", "createQueue", getAddress(true), getRoutingType(), getName(), getFilter(), isDurable(), getMaxConsumers(-1), isPurgeOnNoConsumers(true), isAutoCreateAddress());
         }

         @Override
         public void requestSuccessful(ClientMessage reply) throws Exception {
            final String result = ManagementHelper.getResult(reply, String.class) + " created successfully.";
            context.out.println(result);
         }

         @Override
         public void requestFailed(ClientMessage reply) throws Exception {
            String errMsg = (String) ManagementHelper.getResult(reply, String.class);
            context.err.println("Failed to create queue " + getName() + ". Reason: " + errMsg);
         }
      });
   }
}


text:
typedef struct TCRange
{
    float low;
    float high;
} TCRange;

static TCRange TCRangeMake(float low, float high)
{
    TCRange range; range.low = low; range.high = high; return range;
}

typedef struct TCDimension
{
    NSInteger rows;
    NSInteger cols;
} TCDimension;

static TCDimension TCDimensionMake(int rows, int cols)
{
    TCDimension dim; dim.rows = rows; dim.cols = cols; return dim;
}

typedef struct TCIndex {
    NSInteger l;
    NSInteger i;
    NSInteger j;
} TCIndex;

static TCIndex TCIndexMake(NSInteger l, NSInteger i, NSInteger j)
{
    TCIndex index;
    index.l = l;
    index.i = i;
    index.j = j;

    return index;
}


text:
int
REF((V != 0) => ? AUTHORIZED([CONN([conn])]))
check_authorization(struct mg_connection   * OK OK_CONN conn,
                    const NULLTERMSTR char * I STRINGPTR REF(URI([V]) = URI([conn])) path)
  OKEXTERN;

int REF((V != 0) => OK_PUT(conn))
is_authorized_for_put(struct mg_connection * OK OK_CONN conn)
  OKEXTERN;

void
send_authorization_request(struct mg_connection * OK M conn)
  OKEXTERN;


text:
using System;

class CheckElemInArr
{
    static void Main()
    {
        /*
         Problem 5. Larger than neighbours
            Write a method that checks if the element at given position in given array of integers is larger than its two neighbours (when such exist).
         */
        int[] arr = { 2, 3, 4, 3, 7, 5, 9, 1, 3, 2, 3, 1 };
        bool check = CheckElementAtPosition(arr, 10);
        Console.WriteLine(check);
    }

    static bool CheckElementAtPosition(int[] arr, int position)
    {
        if (position == 0 && arr[position] > arr[position + 1])
        {
            return true;
        }
        else if (arr[position] > arr[position - 1] && arr[position] > arr[position + 1])
        {
            return true;
        }
        else if (arr[arr.Length - 1] > arr[arr.Length - 2])
        {
            return true;
        }

        return false;
    }
}


text:
"enable aexpr";

import AbstractAstNode from './abstract-ast-node.js'

export default class AstNodeFunctionDeclaration extends AbstractAstNode {
  async initialize() {
    await super.initialize();
    this.windowTitle = "AstNodeFunctionDeclaration";
  }

  get generator() { return this.get('#generator'); }
  get async() { return this.get('#async'); }

  async updateProjection() {
    // generator: boolean;
    this.generator.classList.toggle('hidden', !this.node.generator);

    // async: boolean;
    this.async.classList.toggle('hidden', !this.node.async);

    if (this.node.id || this.path.parentPath.type !== 'ExportDefaultDeclaration') {
      await this.createSubElementForPath(this.path.get('id'), 'id');
    }

    await this.createSubElementForPaths(this.path.get('params'), 'params');
    await this.createSubElementForPath(this.path.get('body'), 'body');
  }

}


text:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User, Group

class Command(BaseCommand):
    can_import_settings = True

    def handle(self, *args, **options):
        if len(args) < 1:
            print 'Specify email address'
            return
        email = args[0]
        users = User.objects.filter(email=email)
        print email, ':',
        for user in users:
            print user.username,
        print ''


text:
define(["require", "exports", './route-filters'], function (require, exports, route_filters_1) {
    var RouterConfiguration = (function () {
        function RouterConfiguration() {
            this.instructions = [];
            this.options = {};
            this.pipelineSteps = [];
        }
        RouterConfiguration.prototype.addPipelineStep = function (name, step) {
            this.pipelineSteps.push({ name: name, step: step });
        };
        RouterConfiguration.prototype.map = function (route) {
            if (Array.isArray(route)) {
                route.forEach(this.map.bind(this));
                return this;
            }
            return this.mapRoute(route);
        };
        RouterConfiguration.prototype.mapRoute = function (config) {
            this.instructions.push(function (router) {
                var routeConfigs = [];
                if (Array.isArray(config.route)) {
                    for (var i = 0, ii = config.route.length; i < ii; ++i) {
                        var current = Object.assign({}, config);
                        current.route = config.route[i];
                        routeConfigs.push(current);
                    }
                }
                else {
                    routeConfigs.push(Object.assign({}, config));
                }
                var navModel;
                for (var i = 0, ii = routeConfigs.length; i < ii; ++i) {
                    var routeConfig = routeConfigs[i];
                    routeConfig.settings = routeConfig.settings || {};
                    if (!navModel) {
                        navModel = router.createNavModel(routeConfig);
                    }
                    router.addRoute(routeConfig, navModel);
                }
            });
            return this;
        };
        RouterConfiguration.prototype.mapUnknownRoutes = function (config) {
            this.unknownRouteConfig = config;
            return this;
        };
        RouterConfiguration.prototype.exportToRouter = function (router) {
            var instructions = this.instructions;
            for (var i = 0, ii = instructions.length; i < ii; ++i) {
                instructions[i](router);
            }
            if (this.title) {
                router.title = this.title;
            }
            if (this.unknownRouteConfig) {
                router.handleUnknownRoutes(this.unknownRouteConfig);
            }
            router.options = this.options;
            var pipelineSteps = this.pipelineSteps;
            if (pipelineSteps.length) {
                if (!router.isRoot) {
                    throw new Error('Pipeline steps can only be added to the root router');
                }
                var filterContainer = router.container.get(route_filters_1.RouteFilterContainer);
                for (var i = 0, ii = pipelineSteps.length; i < ii; ++i) {
                    var _a = pipelineSteps[i], name_1 = _a.name, step = _a.step;
                    filterContainer.addStep(name_1, step);
                }
            }
        };
        return RouterConfiguration;
    })();
    exports.RouterConfiguration = RouterConfiguration;
});


text:
{-# LANGUAGE OverlappingInstances, UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  HJScript.Objects.Math
-- License     :  BSD-style
-- Maintainer  :  Joel Bjornson joel.bjornson@gmail.com,
--                Niklas Broberg nibro@cs.chalmers.se
-- Stability   :  experimental
-----------------------------------------------------------------------------
module HJScript.Objects.Math
  (
    Math(..),
    abs,
    acos,
    asin,
    atan,
    cos,
    exp,
    floor,
    log,
    max,
    min,
    pow,
    random,
    round,
    sin,
    sqrt,
    tan

  ) where

import HJScript.Lang
import Prelude hiding ( abs,acos,asin,atan,cos,exp,floor,log,
                        max,min,round,sin,sqrt,tan)

-- | Math Class
data Math = Math deriving Show
instance IsClass Math
instance IsDeref Math

callMathMeth :: Num t => String -> Exp t -> JFloat
callMathMeth name exp = callMethod name exp Math

abs :: Num t => Exp t -> JFloat
abs = callMathMeth "abs"

acos ::  Num t => Exp t -> JFloat
acos = callMathMeth "acos"

asin ::  Num t => Exp t -> JFloat
asin = callMathMeth "asin"

atan :: Num t => Exp t -> JFloat
atan = callMathMeth "atan"

cos ::  Num t => Exp t -> JFloat
cos = callMathMeth "cos"

exp ::  Num t => Exp t -> JFloat
exp = callMathMeth "exp"

floor ::  Num t => Exp t -> JFloat
floor = callMathMeth "floor"

log ::  Num t => Exp t -> JFloat
log = callMathMeth "log"

max ::  Num t => Exp t -> JFloat
max = callMathMeth "max"

min ::  Num t => Exp t -> JFloat
min = callMathMeth "min"

pow ::  Num t => Exp t -> JFloat
pow = callMathMeth "pow"

random ::  Num t => Exp t -> JFloat
random = callMathMeth "random"

round ::  Num t => Exp t -> JFloat
round = callMathMeth "round"

sin ::  Num t => Exp t -> JFloat
sin = callMathMeth "sin"

sqrt ::Num t => Exp t -> JFloat
sqrt = callMathMeth "sqrt"

tan ::  Num t => Exp t -> JFloat
tan = callMathMeth "tan"


text:
#include <aws/route53domains/model/ListDomainsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Route53Domains::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListDomainsRequest::ListDomainsRequest() :
    m_filterConditionsHasBeenSet(false),
    m_sortConditionHasBeenSet(false),
    m_markerHasBeenSet(false),
    m_maxItems(0),
    m_maxItemsHasBeenSet(false)
{
}

Aws::String ListDomainsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_filterConditionsHasBeenSet)
  {
   Array<JsonValue> filterConditionsJsonList(m_filterConditions.size());
   for(unsigned filterConditionsIndex = 0; filterConditionsIndex < filterConditionsJsonList.GetLength(); ++filterConditionsIndex)
   {
     filterConditionsJsonList[filterConditionsIndex].AsObject(m_filterConditions[filterConditionsIndex].Jsonize());
   }
   payload.WithArray("FilterConditions", std::move(filterConditionsJsonList));

  }

  if(m_sortConditionHasBeenSet)
  {
   payload.WithObject("SortCondition", m_sortCondition.Jsonize());

  }

  if(m_markerHasBeenSet)
  {
   payload.WithString("Marker", m_marker);

  }

  if(m_maxItemsHasBeenSet)
  {
   payload.WithInteger("MaxItems", m_maxItems);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection ListDomainsRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Route53Domains_v20140515.ListDomains"));
  return headers;

}


text:
SOURCES    = $(wildcard src/*.c)
TEMPLATES  = $(wildcard src/*.jinja)
EXECUTABLE = build/a.out

# Add rendered .c templates to sources list
SOURCES += $(filter %.c, $(basename $(TEMPLATES)))

# Resolve build dir from executable
BUILDDIR = $(dir $(EXECUTABLE))

# Resolve object files
OBJECTS = $(addprefix $(BUILDDIR), $(SOURCES:.c=.o))

# Resolve .d files which list what files the object
# and template files depend on
OBJECTS_D   = $(OBJECTS:.o=.d)
TEMPLATES_D = $(addsuffix .d,$(basename $(TEMPLATES)))

$(EXECUTABLE) : $(OBJECTS)
	$(CC) $^ -o $@

$(BUILDDIR)%.o : %.c | $(filter %.h, $(basename $(TEMPLATES)))
	@mkdir -p $(dir $@)
	$(CC) -MMD -MP $< -c -o $@

%.c : %.c.jinja
	yasha -MD $< -o $@

%.h : %.h.jinja
	yasha -MD $< -o $@

# Make sure that the following built-in implicit rule is cancelled
%.o : %.c

# Pull in dependency info for existing .o and template files
-include $(OBJECTS_D) $(TEMPLATES_D)

# Prevent Make to consider rendered templates as intermediate file
.secondary : $(basename $(TEMPLATES))

clean :
ifeq ($(BUILDDIR),./)
	-rm -f $(EXECUTABLE)
	-rm -f $(OBJECTS)
	-rm -f $(OBJECTS_D)
else
	-rm -rf $(BUILDDIR)
endif
	-rm -f $(TEMPLATES_D)
	-rm -f $(basename $(TEMPLATES))

.phony : clean


text:
$("document").ready(function ()
{
    collapseNavbar();
    // jQuery to collapse the navbar on scroll
    function collapseNavbar() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        } else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    }

    $(window).scroll(collapseNavbar);
    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function (e) {
        if (hasClass(e.target, "nav-page")) {
            $('.navbar-toggle:visible').click();
        }
    });
    function hasClass(elem, className) {
        return elem.className.split(' ').indexOf(className) > -1;
    }

    document.addEventListener("click", function (e)
    {
        if(hasClass(e.target, "navbar-toggle") || hasClass(e.target, "headerBTN"))
        {
            if (hasClass(e.target, "headerBTN"))
                var id = $(e.target).closest(".navbar-toggle").attr("id");
            else
                var id = e.target.id;
            var menuitems = document.getElementsByClassName("navbar-toggle");
            for(var i = 0; i < menuitems.length; i++)
            {
                if ($(menuitems[i]).attr("id") != id)
                {
                    var target = $(menuitems[i]).attr("data-target");
                    if ($(target).is(":visible"))
                        $(menuitems[i]).click();
                }
            }
            $("#" + id).click();
        }
    });
});