text:
import GhostContentAPI from '@tryghost/content-api'
import { GHOST_API_URL_DEFAULT, GHOST_API_KEY_DEFAULT } from './defaults.js'

const GHOST_API_URL = process.env.GHOST_API_URL || GHOST_API_URL_DEFAULT
const GHOST_API_KEY = process.env.GHOST_API_KEY || GHOST_API_KEY_DEFAULT

const api = new GhostContentAPI({
  url: GHOST_API_URL,
  key: GHOST_API_KEY,
  version: 'v3.0',
})

const is404 = (error) => /not found/i.test(error.message)

export async function getPreviewPostBySlug(slug) {
  const params = {
    slug,
    fields: 'slug',
    limit: 'all',
  }

  try {
    const post = await api.posts.read(params)
    return post
  } catch (error) {
    // Don't throw if an slug doesn't exist
    if (is404(error)) return
    throw error
  }
}

export async function getAllPostsWithSlug() {
  const params = {
    fields: 'slug',
    limit: 'all',
  }
  const posts = await api.posts.browse(params)
  return posts
}

export async function getAllPostsForHome(preview) {
  const params = {
    limit: 'all',
    include: 'authors',
    order: 'published_at DESC',
    ...(preview && { status: 'all' }),
  }
  const posts = await api.posts.browse(params)
  return posts
}

export async function getPostAndMorePosts(slug, preview) {
  const singleObjectParams = {
    slug,
    include: 'authors',
    ...(preview && { status: 'all' }),
  }
  const moreObjectParams = {
    limit: 3,
    include: 'authors',
    ...(preview && { status: 'all' }),
  }
  const post = await api.posts.read(singleObjectParams).catch((error) => {
    // Don't throw if an slug doesn't exist
    if (is404(error)) return
    throw error
  })
  const morePosts = (await api.posts.browse(moreObjectParams))
    ?.filter(({ slug }) => post.slug !== slug)
    .slice(0, 2)

  return {
    post,
    morePosts,
  }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import { Router, Route, IndexRoute, browserHistory, Redirect } from 'react-router';

import {
  App,
  HomePage,
  DashboardContainer,
  LoginPage,
  DashboardHomePage,
  DashboardUserForm,
  DashboardUsersPage,
  DashboardPostsPage,
  DashboardPostPage,
  PostPage,
  DashboardContentBlocks,
  DashboardAssetsPage,
  DashboardAssetPage,
  PostFeedPage
} from 'grommet-cms/containers';

export const getRoutes = (store) => {
  const authRequired = (nextState, replace) => {
    const state = store.getState();

    if (!state.login.loggedIn) {
      // Not authenticated, redirect to login page.
      replace({
        state: {
          nextPathname: nextState.location.pathname
        },
        pathname: '/dashboard'
      });
    }
  };

  return (
    <Router history={browserHistory}>
      <Route path='/dashboard' component={DashboardContainer}>
        <IndexRoute component={LoginPage} />
        <Route path="assets" component={DashboardAssetsPage} onEnter={authRequired} />
        <Route path="asset/:id" component={DashboardAssetPage} onEnter={authRequired} />
        <Route path="homepage" component={DashboardHomePage} onEnter={authRequired} />
        <Route path="users" component={DashboardUsersPage} onEnter={authRequired} />
        <Route path='user/create' component={DashboardUserForm} onEnter={authRequired} />
        <Route path='posts' component={DashboardPostsPage} onEnter={authRequired} />
        <Route path='post/:id' component={DashboardPostPage} onEnter={authRequired} />
        <Redirect from='post/:id' to='/posts/post/:id' />
      </Route>

      <Route path="/" component={App}>
        <IndexRoute component={HomePage} />
        <Route path="post/:slug" component={PostPage} />
        <Route path="blocks" component={DashboardContentBlocks} />
        <Route path="/posts">
          <IndexRoute component={PostFeedPage} />
          <Route path="post/:slug" component={PostPage} />
        </Route>
      </Route>
    </Router>
  );
};


text:
package io.github.cidisk.indexcrawler.parser;

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

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class HtmlContentHandler extends DefaultHandler {

  private final int MAX_ANCHOR_LENGTH = 100;

  private enum Element {
    A, AREA, LINK, IFRAME, FRAME, EMBED, IMG, BASE, META, BODY
  }

  private static class HtmlFactory {
    private static Map<String, Element> name2Element;

    static {
      name2Element = new HashMap<>();
      for (Element element : Element.values()) {
        name2Element.put(element.toString().toLowerCase(), element);
      }
    }

    public static Element getElement(String name) {
      return name2Element.get(name);
    }
  }

  private String base;
  private String metaRefresh;
  private String metaLocation;
  private Map<String, String> metaTags = new HashMap<>();

  private boolean isWithinBodyElement;
  private StringBuilder bodyText;

  private List<ExtractedUrlAnchorPair> outgoingUrls;

  private ExtractedUrlAnchorPair curUrl = null;
  private boolean anchorFlag = false;
  private StringBuilder anchorText = new StringBuilder();

  public HtmlContentHandler() {
    isWithinBodyElement = false;
    bodyText = new StringBuilder();
    outgoingUrls = new ArrayList<>();
  }

  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    Element element = HtmlFactory.getElement(localName);

    if (element == Element.A || element == Element.AREA || element == Element.LINK) {
      String href = attributes.getValue("href");
      if (href != null) {
        anchorFlag = true;
        curUrl = new ExtractedUrlAnchorPair();
        curUrl.setHref(href);
        curUrl.setTag(localName);
        outgoingUrls.add(curUrl);
      }
      return;
    }

    if (element == Element.IMG) {
      String imgSrc = attributes.getValue("src");
      if (imgSrc != null) {
        curUrl = new ExtractedUrlAnchorPair();
        curUrl.setHref(imgSrc);
        curUrl.setTag(localName);
        outgoingUrls.add(curUrl);
      }
      return;
    }

    if (element == Element.IFRAME || element == Element.FRAME || element == Element.EMBED) {
      String src = attributes.getValue("src");
      if (src != null) {
        curUrl = new ExtractedUrlAnchorPair();
        curUrl.setHref(src);
        curUrl.setTag(localName);
        outgoingUrls.add(curUrl);
      }
      return;
    }

    if (element == Element.BASE) {
      if (base != null) { // We only consider the first occurrence of the Base element.
        String href = attributes.getValue("href");
        if (href != null) {
          base = href;
        }
      }
      return;
    }

    if (element == Element.META) {
      String equiv = attributes.getValue("http-equiv");
      if (equiv == null) { // This condition covers several cases of XHTML meta
        equiv = attributes.getValue("name");
      }

      String content = attributes.getValue("content");
      if (equiv != null && content != null) {
        equiv = equiv.toLowerCase();
        metaTags.put(equiv, content);

        // http-equiv="refresh" content="0;URL=http://foo.bar/..."
        if (equiv.equals("refresh") && (metaRefresh == null)) {
          int pos = content.toLowerCase().indexOf("url=");
          if (pos != -1) {
            metaRefresh = content.substring(pos + 4);
          }
          curUrl = new ExtractedUrlAnchorPair();
          curUrl.setHref(metaRefresh);
          curUrl.setTag(localName);
          outgoingUrls.add(curUrl);
        }

        // http-equiv="location" content="http://foo.bar/..."
        if (equiv.equals("location") && (metaLocation == null)) {
          metaLocation = content;
          curUrl = new ExtractedUrlAnchorPair();
          curUrl.setHref(metaRefresh);
          curUrl.setTag(localName);
          outgoingUrls.add(curUrl);
        }
      }
      return;
    }

    if (element == Element.BODY) {
      isWithinBodyElement = true;
    }
  }

  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    Element element = HtmlFactory.getElement(localName);
    if (element == Element.A || element == Element.AREA || element == Element.LINK) {
      anchorFlag = false;
      if (curUrl != null) {
        String anchor = anchorText.toString().replaceAll("\n", " ").replaceAll("\t", " ").trim();
        if (!anchor.isEmpty()) {
          if (anchor.length() > MAX_ANCHOR_LENGTH) {
            anchor = anchor.substring(0, MAX_ANCHOR_LENGTH) + "...";
          }
          curUrl.setTag(localName);
          curUrl.setAnchor(anchor);
        }
        anchorText.delete(0, anchorText.length());
      }
      curUrl = null;
    }
    if (element == Element.BODY) {
      isWithinBodyElement = false;
    }
  }

  @Override
  public void characters(char ch[], int start, int length) throws SAXException {
    if (isWithinBodyElement) {
      bodyText.append(ch, start, length);

      if (anchorFlag) {
        anchorText.append(new String(ch, start, length));
      }
    }
  }

  public String getBodyText() {
    return bodyText.toString();
  }

  public List<ExtractedUrlAnchorPair> getOutgoingUrls() {
    return outgoingUrls;
  }

  public String getBaseUrl() {
    return base;
  }

  public Map<String, String> getMetaTags() {
    return metaTags;
  }
}


text:
"""
Created on Tue Jun  9 11:51:28 2015

@author: ajaver
"""

import time
import datetime
import numpy as np

def _tictoc():
    tic = time.time()

    def _toc():
        print('Elapse time %f' % (time.time() - tic))
    return _toc

class TimeCounter:

    def __init__(self, task_str='', tot_frames=None):
        self.initial_time = time.time()
        self.last_frame = 0
        self.task_str = task_str
        self.fps_time = time.time()
        self.tot_frames = tot_frames

    def get_str(self, frame_number):
        # calculate the progress and put it in a string
        time_str = str(
            datetime.timedelta(
                seconds=round(
                    time.time() -
                    self.initial_time)))

        try:
            fps = (frame_number - self.last_frame + 1) / \
                (time.time() - self.fps_time)
        except ZeroDivisionError:
            fps = np.nan

        progress_str = '%s Total time = %s, fps = %2.1f; Frame %i'\
            % (self.task_str, time_str, fps, frame_number)
        self.fps_time = time.time()
        self.last_frame = frame_number
        if self.tot_frames is not None:
            progress_str += ' of %i' % self.tot_frames

        return progress_str

    def get_time_str(self):
        return str(
            datetime.timedelta(
                seconds=round(
                    time.time() -
                    self.initial_time)))


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
(C) Copyright 2015 Somonar B.V.

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.

 -->

<menus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ofbiz.apache.org/dtds/widget-menu.xsd">
    <menu name="MainAppBar" title="${uiLabelMap.${activeApp}Application}" extends="CommonAppBarMenu" extends-resource="component://common/widget/CommonMenus.xml">
        <menu-item name="main" title="${uiLabelMap.CommonMain}"><link target="main"/></menu-item>
        <menu-item name="configuration" title="${uiLabelMap.CommonConfiguration}">
            <condition>
                <if-has-permission permission="${activeApp}" action="_ADMIN"/>
            </condition>
            <link target="configuration"/>
        </menu-item>
    </menu>
</menus>


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

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

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

using System;
using System.Collections.Generic;
using System.Text;
using GraphSearch;

namespace RenderConfig.Core
{
    public class RenderConfigConfig : ICloneable
    {
        private string configFile;
        private string configuration;
        private string outputDirectory;
        private Boolean deleteOutputDirectory = true;
        private Boolean cleanOutput = false;
        private Boolean breakOnNoMatch = false;
        private string inputDirectory;
        private Boolean preserveSourceStructure;
        private Boolean subDirectoryEachConfiguration = true;
        private Boolean stampRenderData = false;

        /// <summary>
        /// Gets or sets a value indicating whether the user wants to stamp a comment into the rendered file.
        /// </summary>
        /// <value><c>true</c> if [stamp render data]; otherwise, <c>false</c>.</value>
        public Boolean StampRenderData
        {
            get { return stampRenderData; }
            set { stampRenderData = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether each configuration passed in should be output to a sub-drectory.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if [sub directory each configuration]; otherwise, <c>false</c>.
        /// </value>
        public Boolean SubDirectoryEachConfiguration
        {
            get { return subDirectoryEachConfiguration; }
            set { subDirectoryEachConfiguration = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to [preserve source structure] when copying files.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if [preserve source structure]; otherwise, <c>false</c>.
        /// </value>
        public Boolean PreserveSourceStructure
        {
            get { return preserveSourceStructure; }
            set { preserveSourceStructure = value; }
        }

        /// <summary>
        /// Gets or sets the input directory.  This will rebase all files to this directory.
        /// </summary>
        /// <value>The input directory.</value>
        public string InputDirectory
        {
            get { return inputDirectory; }
            set { inputDirectory = value; }
        }

        /// <summary>
        /// Gets or sets the config file to parse.
        /// </summary>
        /// <value>The config file.</value>
        public string ConfigFile
        {
            get { return configFile; }
            set { configFile = value; }
        }

        /// <summary>
        /// Gets or sets the configuration we want to output.  Must exist in the configuration file.
        /// </summary>
        /// <value>The configuration.</value>
        public string Configuration
        {
            get { return configuration; }
            set { configuration = value; }
        }

        /// <summary>
        /// Gets or sets the config output directory.
        /// </summary>
        /// <value>The config directory.</value>
        public string OutputDirectory
        {
            get { return outputDirectory; }
            set { outputDirectory = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to [delete output directory].
        /// </summary>
        /// <value>
        /// 	<c>true</c> if [delete output directory]; otherwise, <c>false</c>.
        /// </value>
        public bool DeleteOutputDirectory
        {
            get { return deleteOutputDirectory; }
            set { deleteOutputDirectory = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to clean the output of the applied xml modifications.
        /// </summary>
        /// <value><c>true</c> if [clean ouptut]; otherwise, <c>false</c>.</value>
        public bool CleanOutput
        {
            get { return cleanOutput; }
            set { cleanOutput = value; }
        }

        /// <summary>
        /// Forces the RenderConfig task to fail if it does not find a match for a particular XPath change
        /// </summary>
        public bool BreakOnNoMatch
        {
            get { return breakOnNoMatch; }
            set { breakOnNoMatch = value; }
        }

        #region ICloneable Members

        public object Clone()
        {
            return this.MemberwiseClone(); ;
        }

        #endregion
    }
}


text:
namespace blimp {
namespace client {

void BlimpDisplayManagerDelegateMain::OnClosed() {
  base::MessageLoop::current()->QuitNow();
}

}  // namespace client
}  // namespace blimp


text:
- [Laravel 4.2](#laravel-4.2)
- [Laravel 4.1](#laravel-4.1)

## Laravel 4.2

The full change list for this release by running the `php artisan changes` command from a 4.2 installation, or by [viewing the change file on Github](https://github.com/laravel/framework/blob/4.2/src/Illuminate/Foundation/changes.json). These notes only cover the major enhancements and changes for the release.

> **Note:** During the 4.2 release cycle, many small bug fixes and enhancements were incorporated into the various Laravel 4.1 point releases. So, be sure to check the change list for Laravel 4.1 as well!

### PHP 5.4 Requirement

Laravel 4.2 requires PHP 5.4 or greater. This PHP upgrade requirements allows us to use new PHP features such as traits to provide a more expressive interfaces for tools like [Laravel Cashier](billing.md). PHP 5.4 also brings significant speed and performance improvements over PHP 5.3.

### Laravel Forge

Laravel Forge, a new web based application, provides a simple way to create and manage PHP servers on the cloud of your choice, including Linode, DigitalOcean, Rackspace, and Amazon EC2. Supporting automated Nginx configuration, SSH key access, Cron job automation, server monitoring via NewRelic & Papertrail, "Push To Deploy", Laravel queue worker configuration, and more, Forge provides the simplest and most affordable way to launch all of your Laravel applications.

The default Laravel 4.2 installation's `app/config/database.php` configuration file is now configured for Forge usage by default, allowing for more convenient deployment of fresh applications onto the platform.

More information about Laravel Forge can be found on the [official Forge website](https://forge.laravel.com).

### Laravel Homestead

Laravel Homestead is an official Vagrant environment for developing robust Laravel and PHP applications. The vast majority of the boxes provisioning needs are handled before the box is packaged for distribution, allowing the box to boot extremely quickly. Homestead includes Nginx 1.6, PHP 5.5.12, MySQL, Postgres, Redis, Memcached, Beanstalk, Node, Gulp, Grunt, & Bower. Homestaed includes a simple `Homestead.yaml` configuration file or managing multiple Laravel applications on a single box.

The default Laravel 4.2 installation now includes an `app/config/local/database.php` configuration file that is configured to use the Homestead database out of the box, making Laravel initial installation and configuration more convenient.

The official documentation has also been updated to include [Homestead documentation](homestead.md).

### Laravel Cashier

Laravel Cashier is a simple, expressive library for managing subscription billing with Stripe. With the introduction of Laravel 4.2, we are including Cashier documentation along with the main Laravel documentation, though installation of the component itself is still optional. This release of Cashier brings numerous bug fixes, multi-currency support, and compatibility with the latest Stripe API.

### Daemon Queue Workers

The Artisan `queue:work` command now supports a `--daemon` option to start a worker in "deamon mode", meaning the worker will continue to process jobs without ever re-booting the framework. This results in a significant reduction in CPU usage at the cost of a slightly more complex application deployment process.

More information about daemon queue workers can be found in the [queue documentation](queue#daemon-queue-workers.md).

### Mail API Drivers

Laravel 4.2 introduces new Mailgun and Mandrill API drivers for the `Mail` functions. For many applications, this provides a faster and more reliable method of sending e-mails than the SMTP options. The new drivers utilize the Guzzle 4 HTTP library.

### Soft Deleting Traits

A much cleaner architecture for "soft deletes" and other "global scopes" has been introduced via PHP 5.4 traits. This new architecture allows for the easier construction of similar global traits, and a cleaner separation of concerns within the framework itself.

More information on the new `SoftDeletingTrait` may be found in the [Eloquent documentation](eloquent#soft-deleting.md).

### Convenient Auth & Remindable Traits

The default Laravel 4.2 installation now uses simple traits for including the needed properties for the authentication and password reminder user interfaces. This provides a much cleaner default `User` model file out of the box.

### "Simple Paginate"

A new `simplePaginate` method was added to the query and Eloquent builder which allows for more efficient queries when using simple "Next" and "Previous" links in your pagination view.

### Migration Confirmation

In production, destructive migration operations will now ask for confirmation. Commands may be forced to run without any prompts using the `--force` command.

## Laravel 4.1

### Full Change List

The full change list for this release by running the `php artisan changes` command from a 4.1 installation, or by [viewing the change file on Github](https://github.com/laravel/framework/blob/4.1/src/Illuminate/Foundation/changes.json). These notes only cover the major enhancements and changes for the release.

### New SSH Component

An entirely new `SSH` component has been introduced with this release. This feature allows you to easily SSH into remote servers and run commands. To learn more, consult the [SSH component documentation](ssh.md).

The new `php artisan tail` command utilizes the new SSH component. For more information, consult the `tail` [command documentation](http://laravel.com/docs/ssh#tailing-remote-logs).

### Boris In Tinker

The `php artisan tinker` command now utilizes the [Boris REPL](https://github.com/d11wtq/boris) if your system supports it. The `readline` and `pcntl` PHP extensions must be installed to use this feature. If you do not have these extensions, the shell from 4.0 will be used.

### Eloquent Improvements

A new `hasManyThrough` relationship has been added to Eloquent. To learn how to use it, consult the [Eloquent documentation](eloquent#has-many-through.md).

A new `whereHas` method has also been introduced to allow [retrieving models based on relationship constraints](eloquent#querying-relations.md).

### Database Read / Write Connections

Automatic handling of separate read / write connections is now available throughout the database layer, including the query builder and Eloquent. For more information, consult [the documentation](database#read-write-connections.md).

### Queue Priority

Queue priorities are now supported by passing a comma-delimited list to the `queue:listen` command.

### Failed Queue Job Handling

The queue facilities now include automatic handling of failed jobs when using the new `--tries` switch on `queue:listen`. More information on handling failed jobs can be found in the [queue documentation](queues#failed-jobs.md).

### Cache Tags

Cache "sections" have been superseded by "tags". Cache tags allow you to assign multiple "tags" to a cache item, and flush all items assigned to a single tag. More information on using cache tags may be found in the [cache documentation](cache#cache-tags.md).

### Flexible Password Reminders

The password reminder engine has been changed to provide greater developer flexibility when validating passwords, flashing status messages to the session, etc. For more information on using the enhanced password reminder engine, [consult the documentation](security#password-reminders-and-reset.md).

### Improved Routing Engine

Laravel 4.1 features a totally re-written routing layer. The API is the same; however, registering routes is a full 100% faster compared to 4.0. The entire engine has been greatly simplified, and the dependency on Symfony Routing has been minimized to the compiling of route expressions.

### Improved Session Engine

With this release, we're also introducing an entirely new session engine. Similar to the routing improvements, the new session layer is leaner and faster. We are no longer using Symfony's (and therefore PHP's) session handling facilities, and are using a custom solution that is simpler and easier to maintain.

### Doctrine DBAL

If you are using the `renameColumn` function in your migrations, you will need to add the `doctrine/dbal` dependency to your `composer.json` file. This package is no longer included in Laravel by default.


text:
static const char* EDDYSTONE_URL_BEACON_PREFIX_SUBSTITUTIONS[] = {
  "http://www.",
  "https://www.",
  "http://",
  "https://",
  "urn:uuid:"
};

static const char* EDDYSTONE_URL_BEACON_SUFFIX_SUBSTITUTIONS[] = {
  ".com/",
  ".org/",
  ".edu/",
  ".net/",
  ".info/",
  ".biz/",
  ".gov/",
  ".com",
  ".org",
  ".edu",
  ".net",
  ".info",
  ".biz",
  ".gov"
};

EddystoneBeacon::EddystoneBeacon(unsigned char req, unsigned char rdy, unsigned char rst) :
  BLEPeripheral(req, rdy, rst),
  _bleService("feaa"),
  _bleCharacteristic("feab", BLERead | BLEBroadcast, MAX_SERVICE_DATA_SIZE)
{
  this->setConnectable(false);

  this->addAttribute(this->_bleService);
  this->addAttribute(this->_bleCharacteristic);
}

void EddystoneBeacon::begin(char power, const BLEUuid& uid) {
  unsigned char serviceData[MAX_SERVICE_DATA_SIZE];

  this->_power = power;

  memset(serviceData, 0x00, sizeof(serviceData));
  serviceData[0] = FLAGS_UID;
  serviceData[1] = this->_power;

  const unsigned char* uidData = uid.data();
  for (int i = 0; i < 16; i++) {
    serviceData[i + 2] = uidData[15 - i];
  }

  serviceData[18] = 0x00; // Reserved for future use, must be: 0x00
  serviceData[19] = 0x00; // Reserved for future use, must be: 0x00

  this->_bleCharacteristic.setValue(serviceData, sizeof(serviceData));

  this->setAdvertisedServiceUuid(this->_bleService.uuid());

  BLEPeripheral::begin();

  this->_bleCharacteristic.broadcast();
}

void EddystoneBeacon::begin(char power, const char* uri) {
  this->_power = power;
  this->setURI(uri);

  this->setAdvertisedServiceUuid(this->_bleService.uuid());

  BLEPeripheral::begin();

  this->_bleCharacteristic.broadcast();
}

void EddystoneBeacon::setURI(const char* uri) {
  unsigned char serviceData[MAX_SERVICE_DATA_SIZE];

  serviceData[0] = FLAGS_URL;
  serviceData[1] = this->_power;
  unsigned char compressedURIlength = this->compressURI(uri, (char *)&serviceData[2], sizeof(serviceData) - 2);

  this->_bleCharacteristic.setValue(serviceData, 2 + compressedURIlength);
}

unsigned char EddystoneBeacon::compressURI(const char* uri, char *compressedUri, unsigned char compressedUriSize) {
  String uriString = uri;

  // replace prefixes
  for (unsigned int i = 0; i < (sizeof(EDDYSTONE_URL_BEACON_PREFIX_SUBSTITUTIONS) / sizeof(char *)); i++) {
    String replacement = " ";
    replacement[0] = (char)(i | 0x80); // set high bit, String.replace does not like '\0' replacement

    uriString.replace(EDDYSTONE_URL_BEACON_PREFIX_SUBSTITUTIONS[i], replacement);
  }

  // replace suffixes
  for (unsigned int i = 0; i < (sizeof(EDDYSTONE_URL_BEACON_SUFFIX_SUBSTITUTIONS) / sizeof(char *)); i++) {
    String replacement = " ";
    replacement[0] = (char)(i | 0x80); // set high bit, String.replace does not like '\0' replacement

    uriString.replace(EDDYSTONE_URL_BEACON_SUFFIX_SUBSTITUTIONS[i], replacement);
  }

  unsigned char i = 0;
  for (i = 0; i < uriString.length() && i < compressedUriSize; i++) {
    compressedUri[i] = (uriString[i] & 0x7f); // assign byte after clearing hight bit
  }

  return i;
}

void EddystoneBeacon::loop() {
  this->poll();
}


text:
'''allow the use of MBCS paths with problematic encodings

Some MBCS encodings are not good for some path operations (i.e.
splitting path, case conversion, etc.) with its encoded bytes. We call
such a encoding (i.e. shift_jis and big5) as "problematic encoding".
This extension can be used to fix the issue with those encodings by
wrapping some functions to convert to Unicode string before path
operation.

This extension is useful for:

- Japanese Windows users using shift_jis encoding.
- Chinese Windows users using big5 encoding.
- All users who use a repository with one of problematic encodings on
  case-insensitive file system.

This extension is not needed for:

- Any user who use only ASCII chars in path.
- Any user who do not use any of problematic encodings.

Note that there are some limitations on using this extension:

- You should use single encoding in one repository.

By default, win32mbcs uses encoding.encoding decided by Mercurial.
You can specify the encoding by config option::

 [win32mbcs]
 encoding = sjis

It is useful for the users who want to commit with UTF-8 log message.
'''

import os, sys
from mercurial.i18n import _
from mercurial import util, encoding

_encoding = None                                # see reposetup()

def decode(arg):
    if isinstance(arg, str):
        uarg = arg.decode(_encoding)
        if arg == uarg.encode(_encoding):
            return uarg
        raise UnicodeError("Not local encoding")
    elif isinstance(arg, tuple):
        return tuple(map(decode, arg))
    elif isinstance(arg, list):
        return map(decode, arg)
    elif isinstance(arg, dict):
        for k, v in arg.items():
            arg[k] = decode(v)
    return arg

def encode(arg):
    if isinstance(arg, unicode):
        return arg.encode(_encoding)
    elif isinstance(arg, tuple):
        return tuple(map(encode, arg))
    elif isinstance(arg, list):
        return map(encode, arg)
    elif isinstance(arg, dict):
        for k, v in arg.items():
            arg[k] = encode(v)
    return arg

def appendsep(s):
    # ensure the path ends with os.sep, appending it if necessary.
    try:
        us = decode(s)
    except UnicodeError:
        us = s
    if us and us[-1] not in ':/\\':
        s += os.sep
    return s

def wrapper(func, args, kwds):
    # check argument is unicode, then call original
    for arg in args:
        if isinstance(arg, unicode):
            return func(*args, **kwds)

    try:
        # convert arguments to unicode, call func, then convert back
        return encode(func(*decode(args), **decode(kwds)))
    except UnicodeError:
        raise util.Abort(_("[win32mbcs] filename conversion failed with"
                         " %s encoding\n") % (_encoding))

def wrapperforlistdir(func, args, kwds):
    # Ensure 'path' argument ends with os.sep to avoids
    # misinterpreting last 0x5c of MBCS 2nd byte as path separator.
    if args:
        args = list(args)
        args[0] = appendsep(args[0])
    if 'path' in kwds:
        kwds['path'] = appendsep(kwds['path'])
    return func(*args, **kwds)

def wrapname(name, wrapper):
    module, name = name.rsplit('.', 1)
    module = sys.modules[module]
    func = getattr(module, name)
    def f(*args, **kwds):
        return wrapper(func, args, kwds)
    try:
        f.__name__ = func.__name__                # fail with python23
    except Exception:
        pass
    setattr(module, name, f)

# List of functions to be wrapped.
# NOTE: os.path.dirname() and os.path.basename() are safe because
#       they use result of os.path.split()
funcs = '''os.path.join os.path.split os.path.splitext
 os.path.splitunc os.path.normpath os.path.normcase os.makedirs
 mercurial.util.endswithsep mercurial.util.splitpath mercurial.util.checkcase
 mercurial.util.fspath mercurial.util.pconvert mercurial.util.normpath'''

# codec and alias names of sjis and big5 to be faked.
problematic_encodings = '''big5 big5-tw csbig5 big5hkscs big5-hkscs
 hkscs cp932 932 ms932 mskanji ms-kanji shift_jis csshiftjis shiftjis
 sjis s_jis shift_jis_2004 shiftjis2004 sjis_2004 sjis2004
 shift_jisx0213 shiftjisx0213 sjisx0213 s_jisx0213 950 cp950 ms950 '''

def reposetup(ui, repo):
    # TODO: decide use of config section for this extension
    if not os.path.supports_unicode_filenames:
        ui.warn(_("[win32mbcs] cannot activate on this platform.\n"))
        return
    # determine encoding for filename
    global _encoding
    _encoding = ui.config('win32mbcs', 'encoding', encoding.encoding)
    # fake is only for relevant environment.
    if _encoding.lower() in problematic_encodings.split():
        for f in funcs.split():
            wrapname(f, wrapper)
        wrapname("mercurial.osutil.listdir", wrapperforlistdir)
        ui.debug("[win32mbcs] activated with encoding: %s\n"
                 % _encoding)


text:
<?php

declare (strict_types = 1); // @codeCoverageIgnore

namespace Recoil\Amqp\Exception;

use Exception;
use RuntimeException;

/**
 * An exception used to indicate problems establishing or using an AMQP channel.
 */
final class ChannelException extends RuntimeException implements RecoilAmqpException
{
    /**
     * Create an exception that indicates an attempt to use a channel that has
     * already been closed.
     *
     * @param int            $channelId The channel ID.
     * @param Exception|null $previous  The exception that caused this exception, if any.
     */
    public static function notOpen(
        int $channelId,
        Exception $previous = null
    ) : ChannelException {
        return new self(
            \sprintf(
                'Unable to use channel #%d, it is closed.',
                $channelId
            ),
            0,
            $previous
        );
    }

    /**
     * Create an exception that indicates the maximum number of channels are
     * already in use.
     *
     * @param Exception|null $previous The exception that caused this exception, if any.
     */
    public static function noAvailableChannels(
        Exception $previous = null
    ) : ChannelException {
        return new self(
            'Unable to open new channel, the maximum number of channels has been reached.',
            0,
            $previous
        );
    }

    /**
     * Create an exception that indicates an unexpected closure of an AMQP channel.
     *
     * @param int            $channelId The channel ID.
     * @param Exception|null $previous  The exception that caused this exception, if any.
     */
    public static function closedUnexpectedly(
        int $channelId,
        Exception $previous = null
    ) : ChannelException {
        return new self(
            \sprintf(
                'Channel #%d was closed unexpectedly.',
                $channelId
            ),
            0,
            $previous
        );
    }
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\ActiveForm;

/* @var $this yii\web\View */
/* @var $searchModel app\models\TeacherWorkSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->params['breadcrumbs'][] = ['label' => '我的课程', 'url' => ['teacher-course/index']];
$this->title = '删除留言';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php if (Yii::$app->session->hasFlash('info')): ?>

    <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
    <?= Yii::$app->session->getFlash('info') ?>

    <?php endif; ?>
    <?php  //echo $this->render('_search', ['model' => $searchModel]); ?>
        <?php $form = ActiveForm::begin([
        'id' => 'list-form',
        'options' => ['class' => 'form-horizontal'],
        'fieldConfig' => [
            'template' => "{label}\n
{input}
\n
{error}
",
            'labelOptions' => ['class' => 'col-lg-1 control-label'],
        ],
    ]); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
       // 'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\CheckboxColumn'],

            'message_title',
            'message_content',
            [
                'class' => 'yii\grid\ActionColumn','header' => '操作',
               'template' => '{delete}',
            ],
        ],
    ]); ?>
    <?=Html::submitButton('确认选中项', ['class' => 'btn btn-info','name' => 'submit-button']);?>
    <?= Html::resetButton('删除选中项', ['class' => 'btn btn-info','name' => 'reset-button']);?>
     <?php ActiveForm::end(); ?>


text:
namespace core {

namespace {

using base::Value;

static const char kNewline[] = "\n";
static const char kIndent[] = "  ";
static const char kNull[] = "null";
static const char kTrue[] = "true";
static const char kFalse[] = "false";
static const char kCommentPrefix[] = "//";

static const char* kStructureOpenings[] = { "[", "{", NULL };
static const char* kStructureClosings[] = { "]", "}", NULL };

}  // namespace

struct JSONFileWriter::Helper {
  template<typename KeyType>
  static bool OutputKey(KeyType key, JSONFileWriter* json_file_writer) {
    DCHECK(json_file_writer != NULL);

    if (!json_file_writer->ReadyForKey())
      return false;

    if (!json_file_writer->AlignForValueOrKey())
      return false;

    std::string formatted_key = base::GetQuotedJSONString(key.as_string());
    if (!json_file_writer->Printf("%s:", formatted_key.c_str()))
      return false;

    // If we're pretty printing, then also output a space between the key and
    // the value.
    if (json_file_writer->pretty_print_ && !json_file_writer->PutChar(' '))
      return false;

    // Indicate that we've output a key and require a value.
    json_file_writer->stack_.push_back(StackElement(kDictKey));
    return true;
  }

  template<typename ValueType, typename PrintFunctionPointer>
  static bool OutputValue(ValueType value,
                          PrintFunctionPointer print_function,
                          JSONFileWriter* json_file_writer) {
    DCHECK(print_function != NULL);
    DCHECK(json_file_writer != NULL);

    if (!json_file_writer->ReadyForValue())
      return false;
    if (!json_file_writer->AlignForValueOrKey())
      return false;
    if (!(json_file_writer->*print_function)(value))
      return false;
    json_file_writer->FlushValue(true);
    return true;
  }
};

JSONFileWriter::JSONFileWriter(FILE* file, bool pretty_print)
    : file_(file),
      pretty_print_(pretty_print),
      finished_(false),
      at_col_zero_(true),
      indent_depth_(0) {
  DCHECK(file != NULL);
}

JSONFileWriter::~JSONFileWriter() {
  Flush();
}

bool JSONFileWriter::OutputComment(const base::StringPiece& comment) {
  // If we are in the middle of writing a dictionary key/value pair
  // (have the key, not the value), then we can't write a comment.
  if (RequireKeyValue())
    return false;

  // If we're not pretty-printing, this is a no-op.
  if (!pretty_print_)
    return true;

  // Trailing comments can be written directly.
  if (finished_) {
    if (!OutputNewline() || !Printf("%s", kCommentPrefix))
      return false;
    if (comment.length() > 0 &&
        !Printf(" %.*s", comment.length(), comment.data())) {
      return false;
    }
    return true;
  }

  // Store the comment for output before the next value.
  comments_.push_back(comment.as_string());

  return true;
}

bool JSONFileWriter::OutputComment(const base::StringPiece16& comment) {
  std::string utf8;
  if (!base::WideToUTF8(comment.data(), comment.length(), &utf8))
    return false;
  return OutputComment(utf8);
}

bool JSONFileWriter::OutputTrailingComment(const base::StringPiece& comment) {
  // A trailing comment can only go out after a value has been written.
  if (!stack_.empty()) {
    if (stack_.back().type_ == kDictKey)
      return false;

    if (stack_.back().has_entries_ == false)
      return false;
  } else {
    // If the stack is empty, then a value has only been written if we are
    // finished.
    if (!finished_)
      return false;
  }

  // No comment? Do nothing!
  if (comment.length() == 0)
    return true;

  // If we already have a trailing comment, bail!
  if (!trailing_comment_.empty())
    return false;

  // Save the comment for output when we're ready. We do this even when not
  // pretty-printing so that the state machine functions identically in either
  // case.
  trailing_comment_.assign(comment.begin(), comment.end());

  // Are we finished? Immediately write the comment, but leave
  // trailing_comment_ populated so that repeated calls will fail.
  if (finished_ &&
      !Printf("  %s %s", kCommentPrefix, trailing_comment_.c_str())) {
    return false;
  }

  return true;
}

bool JSONFileWriter::OutputTrailingComment(const base::StringPiece16& comment) {
  std::string utf8;
  if (!base::WideToUTF8(comment.data(), comment.length(), &utf8))
    return false;
  return OutputTrailingComment(utf8);
}

bool JSONFileWriter::PrintBoolean(bool value) {
  return Printf("%s", value ? kTrue : kFalse);
}

bool JSONFileWriter::PrintInteger(int value) {
  return Printf("%d", value);
}

bool JSONFileWriter::PrintDouble(double value) {
  base::FundamentalValue fundamental_value(value);
  return PrintValue(&fundamental_value);
}

bool JSONFileWriter::PrintString(const base::StringPiece& value) {
  return Printf("%s", base::GetQuotedJSONString(value.as_string()).c_str());
}

bool JSONFileWriter::PrintNull(int value_unused) {
  return Printf("%s", kNull);
}

bool JSONFileWriter::PrintValue(const Value* value) {
  DCHECK(value != NULL);

  switch (value->GetType()) {
    case Value::TYPE_LIST:
    case Value::TYPE_DICTIONARY: {
      // TODO(chrisha): Eventually, these should be implemented.
      LOG(ERROR) << "JSON Lists and Dictionaries are currently unsupported.";
      return false;
    }

    // All simple types.
    case Value::TYPE_BOOLEAN:
    case Value::TYPE_INTEGER:
    case Value::TYPE_DOUBLE:
    case Value::TYPE_NULL:
    case Value::TYPE_STRING:
    case Value::TYPE_BINARY: {
      std::string str;
      base::JSONWriter::Write(value, &str);
      return Printf("%s", str.c_str());
    }

    default: {
      NOTREACHED() << "Unexpected JSON type: " << value->GetType();
      return false;
    }
  }
}

bool JSONFileWriter::Printf(const char* format, ...) {
  va_list args;
  va_start(args, format);
  int chars_written = vfprintf(file_, format, args);
  va_end(args);
  if (chars_written > 0)
    at_col_zero_ = false;
  return chars_written >= 0;
}

bool JSONFileWriter::PutChar(char c) {
  if (fputc(c, file_) != c)
    return false;
  at_col_zero_ = false;
  return true;
}

bool JSONFileWriter::OpenList() {
  return OpenStructure(kList);
}

bool JSONFileWriter::CloseList() {
  return CloseStructure(kList);
}

bool JSONFileWriter::OpenDict() {
  return OpenStructure(kDict);
}

bool JSONFileWriter::CloseDict() {
  return CloseStructure(kDict);
}

bool JSONFileWriter::OutputKey(const base::StringPiece& key) {
  return Helper::OutputKey(key, this);
}

bool JSONFileWriter::OutputKey(const base::StringPiece16& key) {
  return Helper::OutputKey(key, this);
}

bool JSONFileWriter::Flush() {
  // Already finished? This is a no-op.
  if (finished_)
    return true;

  // Are we waiting on a required value?
  if (RequireKeyValue())
    return false;

  // Otherwise, simply close off the structures one by one.
  while (!stack_.empty()) {
    if (!CloseStructure(stack_.back().type_))
      return false;
  }

  return true;
}

bool JSONFileWriter::OutputBoolean(bool value) {
  return Helper::OutputValue(
      value, &JSONFileWriter::PrintBoolean, this);
}

bool JSONFileWriter::OutputInteger(int value) {
  return Helper::OutputValue(
      value, &JSONFileWriter::PrintInteger, this);
}

bool JSONFileWriter::OutputDouble(double value) {
  return Helper::OutputValue(
      value, &JSONFileWriter::PrintDouble, this);
}

bool JSONFileWriter::OutputString(const base::StringPiece& value) {
  return Helper::OutputValue(
      value, &JSONFileWriter::PrintString, this);
}

bool JSONFileWriter::OutputString(const base::StringPiece16& value) {
  std::string utf8;
  if (!base::WideToUTF8(value.data(), value.length(), &utf8))
    return false;
  return OutputString(utf8);
}

bool JSONFileWriter::OutputNull() {
  int unused = 0;
  return Helper::OutputValue(
      unused, &JSONFileWriter::PrintNull, this);
}

bool JSONFileWriter::OutputValue(const Value* value) {
  return Helper::OutputValue(
      value, &JSONFileWriter::PrintValue, this);
}

bool JSONFileWriter::OutputIndent() {
  if (!pretty_print_)
    return true;

  // We bypass Printf and manually update at_col_zero_ here for efficiency.
  if (indent_depth_ > 0)
    at_col_zero_ = false;
  for (size_t i = 0; i < indent_depth_; ++i) {
    if (fprintf(file_, "%s", kIndent) < 0)
      return false;
  }
  return true;
}

bool JSONFileWriter::OutputNewline() {
  if (!pretty_print_ || at_col_zero_)
    return true;

  // Bypass Printf and manually at_col_zero_ for efficiency.
  if (fprintf(file_, "%s", kNewline) < 0)
    return false;
  at_col_zero_ = true;

  return true;
}

bool JSONFileWriter::OutputComments() {
  if (comments_.empty())
    return true;

  // Comments are only stored if we're pretty-printing.
  DCHECK(pretty_print_);

  bool indented = at_col_zero_ == false;

  for (size_t i = 0; i < comments_.size(); ++i) {
    // Indent if need be.
    if (at_col_zero_ && !OutputIndent())
      return false;

    // Output the comment prefix.
    if (!Printf("%s", kCommentPrefix))
      return false;

    // Output the comment if there's any content.
    if (!comments_[i].empty() &&
        !Printf(" %s", comments_[i].c_str()))
      return false;

    if (!OutputNewline())
      return false;
  }

  // If we were indented when entering, indent on the way out.
  if (indented && !OutputIndent())
    return false;

  // Clear the comments.
  comments_.clear();

  return true;
}

bool JSONFileWriter::OutputTrailingComment() {
  if (trailing_comment_.empty())
    return true;

  // If we're pretty-printing, output the comment.
  if (pretty_print_ &&
      !Printf("  %s %s", kCommentPrefix, trailing_comment_.c_str())) {
    return false;
  }

  trailing_comment_.clear();

  return true;
}

bool JSONFileWriter::AlignForValueOrKey() {
  // Are we a dictionary key waiting for a value? If so, there's nothing to
  // do as the alignment was taken care of when the key was written.
  if (RequireKeyValue())
    return true;

  // Are we in a structure, and not the first entry? Then we need to
  // output a trailing comma.
  if (!stack_.empty() && !FirstEntry() && !PutChar(','))
    return false;

  // Are we not pretty-printing? Then we're done!
  if (!pretty_print_)
    return true;

  if (!OutputTrailingComment())
    return false;

  // Go to a new line if need be.
  if (!OutputNewline())
    return false;

  if (!OutputIndent())
    return false;

  return OutputComments();
}

bool JSONFileWriter::FirstEntry() const {
  if (stack_.empty())
    return true;
  return !stack_.back().has_entries_;
}

bool JSONFileWriter::ReadyForKey() const {
  if (stack_.empty())
    return false;
  return stack_.back().type_ == kDict;
}

bool JSONFileWriter::ReadyForValue() const {
  if (finished_)
    return false;
  if (stack_.empty())
    return true;
  return stack_.back().type_ != kDict;
}

bool JSONFileWriter::RequireKeyValue() const {
  if (stack_.empty())
    return false;
  return stack_.back().type_ == kDictKey;
}

bool JSONFileWriter::CanClose(StructureType type) const {
  // You can never 'close' a dict key.
  if (stack_.empty() || type == kDictKey)
    return false;
  return stack_.back().type_ == type;
}

bool JSONFileWriter::OpenStructure(StructureType type) {
  DCHECK_GT(arraysize(kStructureOpenings), static_cast<size_t>(type));
  DCHECK(kStructureOpenings[type] != NULL);

  if (!ReadyForValue() ||
      !AlignForValueOrKey() ||
      !Printf("%s", kStructureOpenings[type])) {
    return false;
  }

  // Opening a new structure is like writing a new value, but the value has
  // not been *finished*.
  FlushValue(false);

  stack_.push_back(StackElement(type));
  ++indent_depth_;

  return true;
}

bool JSONFileWriter::CloseStructure(StructureType type) {
  DCHECK_GT(arraysize(kStructureClosings), static_cast<size_t>(type));
  DCHECK(kStructureClosings[type] != NULL);

  if (!CanClose(type) ||
      !OutputTrailingComment() ||
      !OutputNewline() ||
      !OutputComments()) {
    return false;
  }

  stack_.pop_back();
  --indent_depth_;
  if (pretty_print_ && !OutputIndent())
    return false;

  if (!Printf("%s", kStructureClosings[type])) {
    return false;
  }

  // If this closed the last open structure, then the JSON file is finished.
  if (stack_.empty())
    finished_ = true;

  return true;
}

void JSONFileWriter::FlushValue(bool value_completed) {
  // The value was successfully written, so if we were in a dictionary waiting
  // for a value, pop the kDictKey entry off the stack.
  if (RequireKeyValue())
    stack_.pop_back();

  // If the stack is not empty, indicate that a value has been written to
  // the open structure.
  if (!stack_.empty()) {
    stack_.back().has_entries_ = true;
  } else {
    if (value_completed) {
      // If the stack is empty then having a written a single value means the
      // JSON file is finished.
      finished_ = true;
    }
  }
}

void JSONFileWriter::CompileAsserts() {
  COMPILE_ASSERT(
      arraysize(kStructureOpenings) == JSONFileWriter::kMaxStructureType,
      StructureOpenings_not_in_sync_with_StructureType_enum);
  COMPILE_ASSERT(
      arraysize(kStructureClosings) == JSONFileWriter::kMaxStructureType,
      StructureClosings_not_in_sync_with_StructureType_enum);
}

}  // namespace core


text:
<?xml version="1.0"?>

<iati-activities>
  <iati-activity>

    <!-- full version -->
    <activity-status xml:lang="en" code="X">X</activity-status>

    <!-- omitting optional attributes version -->
    <activity-status>X</activity-status>

  </iati-activity>
</iati-activities>


text:
****************
Job DSL Examples
****************

About Job DSL Syntax
====================
* ``job`` - only required expression

.. code-block:: groovy

    job('my-job-name')

Job
====
.. code-block:: groovy

    job(String name, Closure closure = null)
    freeStyleJob(String name, Closure closure = null)
    buildFlowJob(String name, Closure closure = null)
    ivyJob(String name, Closure closure = null)
    matrixJob(String name, Closure closure = null)
    mavenJob(String name, Closure closure = null)
    multiJob(String name, Closure closure = null)
    workflowJob(String name, Closure closure = null)
    multibranchWorkflowJob(String name, Closure closure = null)

.. code-block:: groovy

    def myJob = freeStyleJob('SimpleJob')
    myJob.with {
        description 'A Simple Job'
    }

View
====
.. code-block:: groovy

    listView(String name, Closure closure = null)
    sectionedView(String name, Closure closure = null)
    nestedView(String name, Closure closure = null)
    deliveryPipelineView(String name, Closure closure = null)
    buildPipelineView(String name, Closure closure = null)
    buildMonitorView(String name, Closure closure = null)
    categorizedJobsView(String name, Closure closure = null)

Folder
======
.. code-block:: groovy

    folder(String name, Closure closure = null)

.. code-block:: groovy

    folder('project-a')
    freeStyleJob('project-a/compile')
    listView('project-a/pipeline')
    folder('project-a/testing')

Config
======
.. code-block:: groovy

    configFiles(Closure configFilesClosure = null)

Queue
=====
.. code-block:: groovy

    queue(String jobName)
    queue(Job job)

Reading from workspace
======================
.. code-block:: groovy

    InputStream streamFileFromWorkspace(String filePath)
    String readFileFromWorkspace(String filePath)
    String readFileFromWorkspace(String jobName, String filePath)

.. code-block:: groovy

    job('my-build') {
        steps {
            shell(readFileFromWorkspace('build.sh'))
        }
    }

.. code-block:: groovy

    job('my-tests') {
        description(readFileFromWorkspace('acme-tests', 'README.txt'))
    }

Logging
=======
.. code-block:: groovy

    out.println('Hello from a Job DSL script!')
    println('Hello from a Job DSL script!')

.. code-block:: groovy

    import java.util.logging.Logger

    Logger logger = Logger.getLogger('org.example.jobdsl')
    logger.info('Hello from a Job DSL script!')

Configure
=========
    .. code-block:: groovy

        job('my-job') {
            ...
            configure { project ->
                project / buildWrappers / EnvInjectPasswordWrapper {
                    injectGlobalPasswords(true)
                }
            }
        }

Examples
========

Example 1
---------
.. code-block:: groovy

    job('my-job') {
        scm {
            git('https://github.com/AstroTech/ecosystem-example-java.git')
        }
        triggers {
            scm('H/15 * * * *')
        }
        steps {
            maven('-e clean test')
        }
    }

Example 2
---------
.. code-block:: groovy

    def project = 'AstroTech/ecosystem-example-java'
    def branchApi = new URL("https://api.github.com/repos/${project}/branches")
    def branches = new groovy.json.JsonSlurper().parse(branchApi.newReader())

    branches.each {
        def branchName = it.name
        def jobName = "${project}-${branchName}".replaceAll('/','-')

        job(jobName) {
            scm {
                git("git://github.com/${project}.git", branchName)
            }
            steps {
                maven("test -Dproject.name=${project}/${branchName}")
            }
        }
    }

Example 3
---------
.. code-block:: groovy

    def giturl = 'https://github.com/AstroTech/ecosystem-example-java.git'

    for(i in 0..10) {
        job("my-job-${i}") {
            scm {
                git(giturl)
            }
            steps {
                maven("test -Dtest.suite=${i}")
            }
        }
    }

Further Reading
===============
* https://oss.cloudogu.com/jenkins/pipeline-syntax/html

Assignments
===========

Jenkinsfile and Pipeline DSL
----------------------------
#. Przepisz całą konfigurację wykorzystując *Pipeline DSL* zapisany w *Jenkinsfile*


text:
<?php

namespace ConfRunner\Execution;

class ProcessExecution
{

    protected $process;

    protected $stages;

    protected $id;

    public function setProcess($process)
    {
      $this->process = $process;
      $this->stages = [];
      $stages = $process->getStages();
      if (!empty($stages)) {
        foreach ($stages as $stage) {
          $this->stages []= new StageExecution($stage, $this);
        }
      }
      return $this;
    }

    public function getProcess()
    {
      return $this->process;
    }

    public function setId($id)
    {
      $this->id = $id;
      return $this;
    }

    public function getId()
    {
      return $this->id;
    }

    public function getPendingStage()
    {
       if (empty($this->stages)) {
          return NULL;
       }
       foreach ($this->stages as $stage) {
          if (!$stage->isComplete()) {
            return $stage;
          }
       }
    }

    public function setStages($stages){
      $this->stages = $stages;
      return $this;
    }

    public function getStages()
    {
      return $this->stages;
    }
}


text:
package jetbrains.exodus.env;

import jetbrains.exodus.ArrayByteIterable;
import jetbrains.exodus.ByteIterable;
import jetbrains.exodus.log.Log;
import jetbrains.exodus.log.Loggable;
import jetbrains.exodus.log.RandomAccessLoggable;
import jetbrains.exodus.tree.IExpirationChecker;
import jetbrains.exodus.tree.ITree;
import jetbrains.exodus.tree.TreeMetaInfo;
import jetbrains.exodus.tree.btree.BTree;
import jetbrains.exodus.tree.btree.BTreeBalancePolicy;
import jetbrains.exodus.tree.btree.BTreeEmpty;
import jetbrains.exodus.tree.patricia.PatriciaTree;
import jetbrains.exodus.tree.patricia.PatriciaTreeEmpty;
import jetbrains.exodus.tree.patricia.PatriciaTreeWithDuplicates;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Iterator;

@SuppressWarnings({"ClassNameSameAsAncestorName"})
public class StoreImpl implements Store {

    @NotNull
    private static final ArrayByteIterable NULL_CACHED_VALUE = new ArrayByteIterable(ByteIterable.EMPTY);

    @NotNull
    private final EnvironmentImpl environment;
    @NotNull
    private final String name;
    @NotNull
    private final TreeMetaInfo metaInfo;

    StoreImpl(@NotNull final EnvironmentImpl env, @NotNull final String name, @NotNull final TreeMetaInfo metaInfo) {
        this.environment = env;
        this.name = name;
        this.metaInfo = metaInfo;
    }

    @NotNull
    @Override
    public EnvironmentImpl getEnvironment() {
        return environment;
    }

    @Override
    @Nullable
    public ByteIterable get(@NotNull final Transaction txn, @NotNull final ByteIterable key) {
        final ITree tree = ((TransactionBase) txn).getTree(this);
        final long treeRootAddress = tree.getRootAddress();
        final StoreGetCache storeGetCache;
        // if neither tree is empty nor mutable and StoreGetCache is on
        if (treeRootAddress != Loggable.NULL_ADDRESS && (storeGetCache = environment.getStoreGetCache()) != null) {
            ByteIterable result = storeGetCache.tryKey(treeRootAddress, key);
            if (result != null) {
                return result == NULL_CACHED_VALUE ? null : result;
            }
            tree.setTreeNodesCache(environment.getTreeNodesCache());
            result = tree.get(key);
            storeGetCache.cacheObject(treeRootAddress, key, result == null ? NULL_CACHED_VALUE : new ArrayByteIterable(result));
            return result;
        }
        return tree.get(key);
    }

    @Override
    public boolean exists(@NotNull final Transaction txn,
                          @NotNull final ByteIterable key,
                          @NotNull final ByteIterable data) {
        return ((TransactionBase) txn).getTree(this).hasPair(key, data);
    }

    @Override
    public boolean put(@NotNull final Transaction txn,
                       @NotNull final ByteIterable key,
                       @NotNull final ByteIterable value) {
        return EnvironmentImpl.throwIfReadonly(txn, "Can't put in read-only transaction").getMutableTree(this).put(key, value);
    }

    @Override
    public void putRight(@NotNull final Transaction txn,
                         @NotNull final ByteIterable key,
                         @NotNull final ByteIterable value) {
        EnvironmentImpl.throwIfReadonly(txn, "Can't put in read-only transaction").getMutableTree(this).putRight(key, value);
    }

    @Override
    public boolean add(@NotNull final Transaction txn,
                       @NotNull final ByteIterable key,
                       @NotNull final ByteIterable value) {
        return EnvironmentImpl.throwIfReadonly(txn, "Can't add in read-only transaction").getMutableTree(this).add(key, value);
    }

    @Override
    public long count(@NotNull Transaction txn) {
        return ((TransactionBase) txn).getTree(this).getSize();
    }

    @Override
    public Cursor openCursor(@NotNull final Transaction txn) {
        return new CursorImpl(this, (TransactionBase) txn);
    }

    @Override
    public boolean delete(@NotNull final Transaction txn,
                          @NotNull final ByteIterable key) {
        return EnvironmentImpl.throwIfReadonly(txn, "Can't delete in read-only transaction").getMutableTree(this).delete(key);
    }

    @Override
    @NotNull
    public String getName() {
        return name;
    }

    @Override
    public boolean isNew(@NotNull final Transaction txn) {
        return !txn.isReadonly() && ((TransactionImpl) txn).isStoreNew(name);
    }

    @Override
    public void persistCreation(@NotNull final Transaction txn) {
        EnvironmentImpl.throwIfReadonly(txn, "Read-only transaction is not enough").storeCreated(this);
    }

    @Override
    public void close() {
    }

    @Override
    @NotNull
    public StoreConfig getConfig() {
        return TreeMetaInfo.toConfig(metaInfo);
    }

    @NotNull
    TreeMetaInfo getMetaInfo() {
        return metaInfo;
    }

    public void reclaim(@NotNull final Transaction transaction,
                        @NotNull final RandomAccessLoggable loggable,
                        @NotNull final Iterator<RandomAccessLoggable> loggables,
                        @NotNull final IExpirationChecker expirationChecker) {
        final TransactionImpl txn = EnvironmentImpl.throwIfReadonly(transaction, "Can't reclaim in read-only transaction");
        final boolean wasTreeCreated = txn.hasTreeMutable(this);
        if (!txn.getMutableTree(this).reclaim(loggable, loggables, expirationChecker) && !wasTreeCreated) {
            txn.removeTreeMutable(this);
        }
    }

    public ITree openImmutableTree(@NotNull final MetaTree metaTree) {
        final int structureId = getStructureId();
        final long upToDateRootAddress = metaTree.getRootAddress(structureId);
        final boolean hasDuplicates = metaInfo.hasDuplicates();
        final boolean treeIsEmpty = upToDateRootAddress == Loggable.NULL_ADDRESS;
        final Log log = environment.getLog();
        final ITree result;
        if (!metaInfo.isKeyPrefixing()) {
            final BTreeBalancePolicy balancePolicy = environment.getBTreeBalancePolicy();
            result = treeIsEmpty ?
                    new BTreeEmpty(log, balancePolicy, hasDuplicates, structureId) :
                    new BTree(log, balancePolicy, upToDateRootAddress, hasDuplicates, structureId);
        } else {
            if (treeIsEmpty) {
                result = new PatriciaTreeEmpty(log, structureId, hasDuplicates);
            } else {
                result = hasDuplicates ?
                        new PatriciaTreeWithDuplicates(log, upToDateRootAddress, structureId) :
                        new PatriciaTree(log, upToDateRootAddress, structureId);
            }
        }
        return result;
    }

    int getStructureId() {
        return metaInfo.getStructureId();
    }
}


text:
package com.roothema.goodis.controller.company;

import com.jayway.restassured.response.Response;
import com.roothema.goodis.controller.base.BaseComponentTest;
import com.roothema.goodis.controller.dto.UserAccountDTO;
import com.roothema.goodis.controller.dto.UserToken;
import com.roothema.goodis.controller.exception.ErrorMessage;
import com.roothema.goodis.helper.CompanyRestHelper;
import com.roothema.goodis.helper.UserRestHelper;
import com.roothema.goodis.model.CompanyAccount;
import org.junit.Test;
import org.springframework.http.HttpStatus;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;

import static org.junit.Assert.assertEquals;

/**
 * Created by mharsadi on 2016. 09. 14..
 */
public class LoginCompanyControllerTest extends BaseComponentTest {

    @Test
    public void testValidCompanyLogin() throws Exception {
        // given
        CompanyAccount companyAccount = new CompanyAccount();
        companyAccount.setEmail("varga@gmail.com");
        companyAccount.setPassword("secretpassword");
        companyAccount.setName("Varga és Tsa Bt.");
        companyAccount.setAddress("somewhere street");
        companyAccount.setMainCategories(new HashSet<>(Arrays.asList("handcrafted-goods", "food-drink")));
        companyAccount.setVendorType("primary-producer");

        CompanyRestHelper.registerCompany(companyAccount);

        // when
        Response response = CompanyRestHelper.loginCompany(new UserToken("varga@gmail.com", "secretpassword"));

        // then
        assertEquals(HttpStatus.OK.value(), response.getStatusCode());
    }

    @Test
    public void testInvalidCompanyLoginWithEmail() throws Exception {
        // given
        CompanyAccount companyAccount = new CompanyAccount();
        companyAccount.setEmail("varga@gmail.com");
        companyAccount.setPassword("secretpassword");
        companyAccount.setName("Varga és Tsa Bt.");
        companyAccount.setAddress("somewhere street");
        companyAccount.setMainCategories(new HashSet<>(Collections.singletonList("handcrafted-goods")));
        companyAccount.setVendorType("primary-producer");

        CompanyRestHelper.registerCompany(companyAccount);

        // when
        Response response = CompanyRestHelper.loginCompany(new UserToken("varga2@gmail.com", "secretpassword"));

        // then
        assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.getStatusCode());
        assertEquals("No user has been found.", response.getBody().as(ErrorMessage.class).getMessage());
    }

    @Test
    public void testInvalidCompanyLoginWithPassword() throws Exception {
        // given
        CompanyAccount companyAccount = new CompanyAccount();
        companyAccount.setEmail("varga@gmail.com");
        companyAccount.setPassword("secretpassword");
        companyAccount.setName("Varga és Tsa Bt.");
        companyAccount.setAddress("somewhere street");
        companyAccount.setMainCategories(new HashSet<>(Collections.singletonList("handcrafted-goods")));
        companyAccount.setVendorType("primary-producer");

        CompanyRestHelper.registerCompany(companyAccount);

        // when
        Response response = CompanyRestHelper.loginCompany(new UserToken("varga@gmail.com", "secretpassword2"));

        // then
        assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.getStatusCode());
        assertEquals("Invalid password for the given user.", response.getBody().as(ErrorMessage.class).getMessage());
    }

    @Test
    public void testInvalidCompanyLoginWithRole() throws Exception {
        // given
        UserRestHelper.registerUser(new UserAccountDTO("Varga Béla", "bela.varga@gmail.com", "secretpasswordbela"));

        // when
        Response response = CompanyRestHelper.loginCompany(new UserToken("bela.varga@gmail.com", "secretpasswordbela"));

        // then
        assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.getStatusCode());
        assertEquals("Invalid role for the given user.", response.getBody().as(ErrorMessage.class).getMessage());
        String message = response.getBody().as(ErrorMessage.class).getMessage();
        System.out.println();
    }
}


text:
package utils

import (
	"encoding/csv"

	"github.com/spf13/afero"
)

//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . CSVUtilsInterface
type CSVUtilsInterface interface {
	GetDependenciesList() ([]DepList, error)
}

type CSVUtils struct {
	FilePath   string
	FileSystem afero.Fs
}

type DepList struct {
	Vendor  string
	Product string
}

func NewCSVUtils(filePath string) CSVUtils {
	return CSVUtils{filePath, afero.NewOsFs()}
}

func (csvU CSVUtils) GetDependenciesList() ([]DepList, error) {
	csvFile, err := csvU.FileSystem.Open(csvU.FilePath)
	if err != nil {
		return nil, err
	}

	reader := csv.NewReader(csvFile)

	if _, err := reader.Read(); err != nil {
		return nil, err
	}

	csvLines, err := reader.ReadAll()
	if err != nil {
		return nil, err
	}

	var deps []DepList

	for _, line := range csvLines {

		if line[2] != "" && line[3] != "" {
			deps = append(deps, DepList{
				Vendor:  line[2],
				Product: line[3],
			})
		}
	}

	return deps, nil
}


text:
<?php

namespace Grafite\Cms\Requests;

use Auth;
use Gate;
use Grafite\Cms\Models\Widget;
use Illuminate\Foundation\Http\FormRequest;

class WidgetRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if (config('app.env') !== 'testing') {
            return Gate::allows('cms', Auth::user());
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return Widget::$rules;
    }
}


text:
#pragma once
#include <aws/outposts/Outposts_EXPORTS.h>
#include <aws/outposts/OutpostsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace Http
{
    class URI;
} //namespace Http
namespace Outposts
{
namespace Model
{

  /**
   */
  class AWS_OUTPOSTS_API ListAssetsRequest : public OutpostsRequest
  {
  public:
    ListAssetsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListAssets"; }

    Aws::String SerializePayload() const override;

    void AddQueryStringParameters(Aws::Http::URI& uri) const override;

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline const Aws::String& GetOutpostIdentifier() const{ return m_outpostIdentifier; }

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline bool OutpostIdentifierHasBeenSet() const { return m_outpostIdentifierHasBeenSet; }

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline void SetOutpostIdentifier(const Aws::String& value) { m_outpostIdentifierHasBeenSet = true; m_outpostIdentifier = value; }

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline void SetOutpostIdentifier(Aws::String&& value) { m_outpostIdentifierHasBeenSet = true; m_outpostIdentifier = std::move(value); }

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline void SetOutpostIdentifier(const char* value) { m_outpostIdentifierHasBeenSet = true; m_outpostIdentifier.assign(value); }

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline ListAssetsRequest& WithOutpostIdentifier(const Aws::String& value) { SetOutpostIdentifier(value); return *this;}

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline ListAssetsRequest& WithOutpostIdentifier(Aws::String&& value) { SetOutpostIdentifier(std::move(value)); return *this;}

    /**
     *
 The ID or the Amazon Resource Name (ARN) of the Outpost.

     */
    inline ListAssetsRequest& WithOutpostIdentifier(const char* value) { SetOutpostIdentifier(value); return *this;}

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline const Aws::Vector<Aws::String>& GetHostIdFilter() const{ return m_hostIdFilter; }

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline bool HostIdFilterHasBeenSet() const { return m_hostIdFilterHasBeenSet; }

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline void SetHostIdFilter(const Aws::Vector<Aws::String>& value) { m_hostIdFilterHasBeenSet = true; m_hostIdFilter = value; }

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline void SetHostIdFilter(Aws::Vector<Aws::String>&& value) { m_hostIdFilterHasBeenSet = true; m_hostIdFilter = std::move(value); }

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline ListAssetsRequest& WithHostIdFilter(const Aws::Vector<Aws::String>& value) { SetHostIdFilter(value); return *this;}

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline ListAssetsRequest& WithHostIdFilter(Aws::Vector<Aws::String>&& value) { SetHostIdFilter(std::move(value)); return *this;}

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline ListAssetsRequest& AddHostIdFilter(const Aws::String& value) { m_hostIdFilterHasBeenSet = true; m_hostIdFilter.push_back(value); return *this; }

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline ListAssetsRequest& AddHostIdFilter(Aws::String&& value) { m_hostIdFilterHasBeenSet = true; m_hostIdFilter.push_back(std::move(value)); return *this; }

    /**
     *
 A filter for the host ID of Dedicated Hosts on the Outpost.

Filter
     * values are case sensitive. If you specify multiple values for a filter, the
     * values are joined with an OR, and the request returns all results
     * that match any of the specified values.

     */
    inline ListAssetsRequest& AddHostIdFilter(const char* value) { m_hostIdFilterHasBeenSet = true; m_hostIdFilter.push_back(value); return *this; }

    inline int GetMaxResults() const{ return m_maxResults; }

    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    inline ListAssetsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    inline ListAssetsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    inline ListAssetsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    inline ListAssetsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::String m_outpostIdentifier;
    bool m_outpostIdentifierHasBeenSet;

    Aws::Vector<Aws::String> m_hostIdFilter;
    bool m_hostIdFilterHasBeenSet;

    int m_maxResults;
    bool m_maxResultsHasBeenSet;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet;
  };

} // namespace Model
} // namespace Outposts
} // namespace Aws


text:
package gwen.core.eval.engine

import gwen.core._
import gwen.core.eval.EvalContext
import gwen.core.eval.EvalEngine
import gwen.core.node._
import gwen.core.node.gherkin.Dialect
import gwen.core.node.gherkin.Spec
import gwen.core.node.gherkin.SpecType
import gwen.core.node.gherkin.SpecPrinter
import gwen.core.result.SpecResult
import gwen.core.state.DataRecord
import gwen.core.status._

import scala.util.chaining._

import java.util.Date

import com.typesafe.scalalogging.LazyLogging

/**
  * Spec evaluation engine.
  */
trait SpecEngine[T <: EvalContext] extends LazyLogging {
  engine: EvalEngine[T] =>

  private [engine] def evaluateFeature(parent: GwenNode, spec: Spec, metaResults: List[SpecResult], dataRecord: Option[DataRecord], ctx: T): SpecResult = {
    spec.specFile foreach { file =>
      ctx.topScope.set("gwen.feature.file.name", file.getName)
      ctx.topScope.set("gwen.feature.file.path", file.getPath)
      ctx.topScope.set("gwen.feature.file.absolutePath", file.getAbsolutePath)
    }
    ctx.topScope.set("gwen.feature.name", spec.feature.name)
    ctx.topScope.set("gwen.eval.status.keyword", StatusKeyword.Pending.toString)
    ctx.topScope.set("gwen.eval.status.message", "")
    Dialect.withLanguage(spec.feature.language) {
      val nspec = normaliseSpec(spec, dataRecord)
      evaluateSpec(parent, nspec, metaResults, dataRecord, ctx)
    }
  }

  private [engine] def evaluateMeta(parent: GwenNode, meta: Spec, metaResults: List[SpecResult], dataRecord: Option[DataRecord], ctx: T): SpecResult = {
    val nmeta = normaliseSpec(meta, dataRecord)
    val metaResult = evaluateSpec(parent, nmeta, metaResults, dataRecord, ctx)
    val metaSpec = metaResult.spec
    metaSpec.evalStatus match {
      case _: Passed | Loaded =>
        metaResult
      case Failed(_, error) =>
        Errors.evaluationError(s"Failed to load meta: $metaSpec: ${error.getMessage}")
      case _ =>
        Errors.evaluationError(s"Failed to load meta: $metaSpec")
    }
  }

  /**
    * Evaluates a specification.
    */
  private def evaluateSpec(parent: GwenNode, spec: Spec, metaResults: List[SpecResult], dataRecord: Option[DataRecord], ctx: T): SpecResult = {
    val specType = spec.specType
    ctx.topScope.pushObject(SpecType.toString, specType)
    try {
      beforeSpec(spec, ctx)
      val started = new Date()
      (if(spec.isMeta) "Loading" else "Evaluating") tap {action =>
        logger.info("")
        logger.info(s"$action $specType: ${spec.feature.name}${spec.specFile.map(file => s" [file: $file]").getOrElse("")}")
      }
      val resultSpec = spec.copy(
        withBackground = None,
        withScenarios = evaluateScenarios(spec, spec.scenarios, dataRecord, ctx, spec.feature.language),
        withRules = evaluateRules(spec, spec.rules, dataRecord, ctx, spec.feature.language),
        withMetaSpecs = metaResults.map(_.spec)
      )
      resultSpec.specFile foreach { _ =>
        logger.info(s"${if (resultSpec.isMeta) "Loaded" else "Evaluated"} $specType: ${spec.feature.name}${spec.specFile.map(file => s" [file: $file]").getOrElse("")}")
      }
      new SpecResult(resultSpec, None, ctx.getVideos, metaResults, started, new Date()) tap { result =>
        if(!spec.isMeta) {
          logStatus(ctx.options, resultSpec)
        } else {
          StatusLogger.log(ctx.options, logger, result.evalStatus, result.toString)
        }
        afterSpec(result, ctx)
      }
    } finally {
      spec.specFile foreach { _ =>
        ctx.topScope.popObject(SpecType.toString)
      }
    }
  }

}


text:
namespace _01.Stream_Progress.Entities
{
    using _01.Stream_Progress.Contracts;

    public abstract class Stream : IStream
    {
        private int length;
        private int bytesSent;

        protected Stream(int length, int bytesSent)
        {
            this.Length = length;
            this.BytesSent = bytesSent;
        }

        public int Length
        {
            get { return this.length; }
            private set { this.length = value; }
        }

        public int BytesSent
        {
            get { return this.bytesSent; }
            private set { this.bytesSent = value; }
        }

        public override string ToString()
        {
            return $"{nameof(this.Length)}: {this.Length}; {nameof(this.BytesSent)}: {this.BytesSent};";
        }
    }
}


text:
import Job from "../../model/job";
import loader from "../../../../iRobots/loader.js";

export default class Parse {
	constructor(city,kd) {
		this.city = city;
		this.kd = kd;
	}

	//根据返回的数据看是否自动停止解析
	maxPageSize(maxSize,json){
		var val = 20;
        return val > maxSize ? maxSize : val;
	}

	list(json){
		let arr = []
		json.data.disp_data.map((it,idx)=>{
			if(it.jobType!=0){
				return;
			}
			let companyAlias = null;
			let aliasLen = it["n_officialname#num#baidu"];
			if(aliasLen>1){
				companyAlias = it.n_officialname[aliasLen-1];
			}

			let job = new Job({
				jobId:it.loc,
				job:it.title,
				companyId:it.company_id,
				company:it.officialname,
				addr:it.companyaddress,
				workYear:it.ori_experience,
				education: it.ori_education,
				salary:it.salary,
				time:it.lastmod,
				info:it.description,
				companyAlias:companyAlias,
				companyDetail:it.companydescription,
				addr:it.companyaddress,
				pageContent:it,
				city:this.city,
				kd:this.kd,
				source:"baidu"
			})
			arr.push(job);
			return;

		})
		return arr;

	}

	info(html,json){
		// var $ = loader.parseHTML(html);
		// var addr = $(".job-addr .job-addr-txt").text().replace(/(^\s*)|(\s*$)/g, "").replace("工作地址:","").replace(/(^\s*)|(\s*$)/g, "");
		// var img = $(".media-item").first().find("img").attr("src");
		// var companyLogo = (!img)?null:img;
		//if(addr == ""){
			var addr = json.companyaddress;
		//}
		return {addr};
	}
}


text:
//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2013/06/08
// Author: Mike Ovsiannikov
//
// Copyright 2013,2016 Quantcast Corporation. All rights reserved.
//
// This file is part of Kosmos File System (KFS).
//
// 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.
//
// Kerberos 5 client side authentication implementation.
//
//----------------------------------------------------------------------------

#ifndef KFS_KRB_CLIENT_H
#define KFS_KRB_CLIENT_H

#include <time.h>

namespace KFS
{

class KrbClient
{
public:
    KrbClient();
    ~KrbClient();
    const char* Init(
        const char* inServiceHostNamePtr,
        const char* inServeiceNamePtr,
        const char* inKeyTabNamePtr,
        const char* inClientNamePtr,
        bool        inForceCacheInitFlag);
    const char* Cleanup();
    const char* Request(
        const char*& outDataPtr,
        int&         outDataLen,
        const char*& outSessionKeyPtr,
        int&         outSessionKeyLen);
    const char* Reply(
        const char*  inReplyPtr,
        int          inReplyLen);
    int GetErrorCode() const;
    time_t GetLastCredEndTime() const;
    KrbClient* Clone(
        const char*& outErrMsgPtr) const;
private:
    class Impl;
    Impl& mImpl;

    KrbClient(
        Impl& inImpl);
private:
    KrbClient(
        const KrbClient& inClient);
    KrbClient& operator=(
        const KrbClient& inClient);
};

}

#endif /* KFS_KRB_CLIENT_H */


text:
package com.flipkart.lyrics;

import com.flipkart.lyrics.annotators.AnnotatorStyle;
import com.flipkart.lyrics.annotators.validations.ValidationAnnotatorStyle;
import com.flipkart.lyrics.config.Chords;
import com.flipkart.lyrics.config.DefaultChords;
import com.flipkart.lyrics.config.Tune;
import com.flipkart.lyrics.helper.TriConsumer;
import com.flipkart.lyrics.model.AnnotationModel;
import com.flipkart.lyrics.model.MetaInfo;
import com.flipkart.lyrics.model.TypeModel;
import com.flipkart.lyrics.model.VariableModel;
import com.flipkart.lyrics.processor.fields.FieldAdditionalHandler;
import com.flipkart.lyrics.processor.fields.FieldModificationHandler;
import com.flipkart.lyrics.processor.types.TypeAdditionalHandler;
import com.flipkart.lyrics.sets.*;
import com.flipkart.lyrics.specs.FileWriter;
import com.flipkart.lyrics.specs.Modifier;
import com.flipkart.lyrics.specs.TypeSpec;
import com.flipkart.lyrics.styles.objectmethods.ObjectMethodsStyle;

import java.util.*;

public class TestTune implements Tune {

    private final FieldTypeHandlerSet fieldTypeHandlerSet = new DefaultFieldTypeHandlerSet();
    private final ParameterTypeHandlerSet parameterTypeHandlerSet = new DefaultParameterTypeHandlerSet();
    private final CreatorSet creatorSet = new DefaultCreatorSet();
    private final HandlerSet handlerSet = new DefaultHandlerSet();
    private final RuleSet ruleSet = new DefaultRuleSet();
    private final List<AnnotatorStyle> annotatorStyles = new ArrayList<>();
    private final List<ValidationAnnotatorStyle> validationAnnotatorStyles = new ArrayList<>();
    private final ObjectMethodsStyle objectMethodsStyle = null;
    private final Set<VariableModel> interfaces = new HashSet<>();
    private final Map<String, FieldAdditionalHandler> fieldAdditionalHandlerMap = new HashMap<>();
    private final Map<String, TypeAdditionalHandler> typeAdditionalHandlerMap = new HashMap<>();
    private final Map<String, FieldModificationHandler> fieldModificationHandlers = new HashMap<>();
    private final Chords chords = new DefaultChords();

    @Override
    public Modifier getDefaultFieldModifier() {
        return Modifier.PRIVATE;
    }

    @Override
    public Modifier getDefaultClassModifier() {
        return Modifier.PUBLIC;
    }

    @Override
    public List<AnnotationModel> getClassLevelAnnotations() {
        return null;
    }

    @Override
    public List<AnnotatorStyle> getAnnotatorStyles() {
        return annotatorStyles;
    }

    @Override
    public List<ValidationAnnotatorStyle> getValidationAnnotatorStyles() {
        return validationAnnotatorStyles;
    }

    @Override
    public FileWriter getFileWriter() {
        return null;
    }

    @Override
    public Chords getChords() {
        return chords;
    }

    @Override
    public boolean areAccessorsNeeded() {
        return true;
    }

    @Override
    public boolean isToStringNeeded() {
        return false;
    }

    @Override
    public boolean areHashCodeAndEqualsNeeded() {
        return false;
    }

    @Override
    public boolean isRequiredFieldConstructorNeeded() {
        return true;
    }

    @Override
    public boolean excludeInitializedFieldsFromConstructor() {
        return false;
    }

    @Override
    public boolean isCustomConstructorNeeded() {
        return false;
    }

    @Override
    public ObjectMethodsStyle getObjectMethodsStyle() {
        return objectMethodsStyle;
    }

    @Override
    public Set<VariableModel> interfaces() {
        return interfaces;
    }

    @Override
    public boolean forceDefaultFieldModifiers() {
        return false;
    }

    @Override
    public Map<String, TriConsumer<TypeSpec.Builder, TypeModel, MetaInfo>> getSpecialInterfacesHandler() {
        return null;
    }

    @Override
    public Map<String, FieldAdditionalHandler> getFieldsAdditionalPropertiesHandler() {
        return fieldAdditionalHandlerMap;
    }

    @Override
    public Map<String, FieldModificationHandler> getFieldModificationHandlers() {
        return fieldModificationHandlers;
    }

    @Override
    public Map<String, TypeAdditionalHandler> getTypeAdditionalPropertiesHandler() {
        return typeAdditionalHandlerMap;
    }

    @Override
    public CreatorSet getCreatorSet() {
        return creatorSet;
    }

    @Override
    public HandlerSet getHandlerSet() {
        return handlerSet;
    }

    @Override
    public RuleSet getRuleSet() {
        return ruleSet;
    }

    @Override
    public FieldTypeHandlerSet getFieldTypeHandlerSet() {
        return fieldTypeHandlerSet;
    }

    @Override
    public ParameterTypeHandlerSet getParameterTypeHandlerSet() {
        return parameterTypeHandlerSet;
    }
}


text:
package com.tian.project.chabaike.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.tian.project.chabaike.R;
import com.tian.project.chabaike.adapter.ItemInfoAdapter;
import com.tian.project.chabaike.common.CommonInterface;
import com.tian.project.chabaike.entity.HomePage;
import com.tian.project.chabaike.entity.ItemInfo;
import com.tian.project.chabaike.task.HeadlineTask;
import com.tian.project.chabaike.task.HeadlineTask.HeadlineTaskComplete;
import com.tian.project.chabaike.view.CustomTitle;

public class SearchActivity extends Activity implements OnScrollListener, OnClickListener{
	//¿Ø¼þÏà¹Ø
	private CustomTitle ctSearch;
	private ListView lvSearch;
	private View moreView;
	private Button btnLoad;
	private ProgressBar pgLoading;

	//Êý¾ÝÏà¹Ø
	private ItemInfo itemInfo;
	private ItemInfoAdapter adapter;
	private String keywordSearch;
	private int page;
	private int rows = 15;
	private int lastListItemIndex;
	private boolean isLoadCompleted = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);

		initUI();
		initData();
	}

	private void initUI() {
		keywordSearch = getIntent().getStringExtra(MoreActivity.INTENT_KEY_WORD);
		ctSearch = (CustomTitle) findViewById(R.id.ct_search);
		ctSearch.setTitleNameText(keywordSearch);
		ctSearch.setTitleBackOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SearchActivity.this.finish();
			}
		});
		ctSearch.setTitleHomeOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(SearchActivity.this,MainActivity.class));
			}
		});

		lvSearch = (ListView) findViewById(R.id.lv_search);
		moreView = getLayoutInflater().inflate(R.layout.list_view_footer_load_more,null);
		btnLoad = (Button) moreView.findViewById(R.id.btn_load);
		btnLoad.setOnClickListener(this);
		pgLoading = (ProgressBar) moreView.findViewById(R.id.pg_loading);
	}

	private void initData() {
		FirstLoadData();
	}

	/* -------------------- OnScrollListener -------------------- */
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(lastListItemIndex == adapter.getCount()&&scrollState == SCROLL_STATE_IDLE){
			LoadMoreData();
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastListItemIndex = firstVisibleItem+visibleItemCount-1;
	}
	/* -------------------- OnScrollListener -------------------- */

	private void FirstLoadData() {
		HeadlineTask task = new HeadlineTask(new HeadlineTaskComplete() {

			@Override
			public void getData(HomePage homePage, ItemInfo itemInfo) {
				SearchActivity.this.itemInfo = itemInfo;
				adapter = new ItemInfoAdapter(SearchActivity.this, itemInfo);
				lvSearch.addFooterView(moreView, null, false);
				lvSearch.setAdapter(adapter);
				lvSearch.setOnScrollListener(SearchActivity.this);
			}
		});
		task.execute(String.format(CommonInterface.URI_KEYWORD_SEARCH, page,rows,keywordSearch));
		page++;
	}

	private void LoadMoreData() {
		if(isLoadCompleted){
			isLoadCompleted = false;
			btnLoad.setVisibility(View.GONE);
			pgLoading.setVisibility(View.VISIBLE);

			HeadlineTask task = new HeadlineTask(new HeadlineTaskComplete() {

				@Override
				public void getData(HomePage homePage, ItemInfo itemInfo) {
					SearchActivity.this.itemInfo.getData().addAll(itemInfo.getData());
					adapter.notifyDataSetChanged();

					isLoadCompleted = true;
					btnLoad.setVisibility(View.VISIBLE);
					pgLoading.setVisibility(View.GONE);
				}
			});
			task.execute(String.format(CommonInterface.URI_KEYWORD_SEARCH, page,rows,keywordSearch));
			page++;

		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_load:
			LoadMoreData();
			break;

		default:
			break;
		}
	}
}