text:
#pragma once
#include <aws/autoscaling/AutoScaling_EXPORTS.h>
#include <aws/autoscaling/AutoScalingRequest.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace AutoScaling
{
namespace Model
{

  /*
  */
  class AWS_AUTOSCALING_API ExitStandbyRequest : public AutoScalingRequest
  {
  public:
    ExitStandbyRequest();
    Aws::String SerializePayload() const override;

    /*

One or more instance IDs. You must specify at least one instance ID.

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

    /*

One or more instance IDs. You must specify at least one instance ID.

    */
    inline void SetInstanceIds(const Aws::Vector<Aws::String>& value) { m_instanceIdsHasBeenSet = true; m_instanceIds = value; }

    /*

One or more instance IDs. You must specify at least one instance ID.

    */
    inline void SetInstanceIds(Aws::Vector<Aws::String>&& value) { m_instanceIdsHasBeenSet = true; m_instanceIds = value; }

    /*

One or more instance IDs. You must specify at least one instance ID.

    */
    inline ExitStandbyRequest& WithInstanceIds(const Aws::Vector<Aws::String>& value) { SetInstanceIds(value); return *this;}

    /*

One or more instance IDs. You must specify at least one instance ID.

    */
    inline ExitStandbyRequest& WithInstanceIds(Aws::Vector<Aws::String>&& value) { SetInstanceIds(value); return *this;}

    /*

One or more instance IDs. You must specify at least one instance ID.

    */
    inline ExitStandbyRequest& AddInstanceIds(const Aws::String& value) { m_instanceIdsHasBeenSet = true; m_instanceIds.push_back(value); return *this; }

    /*

One or more instance IDs. You must specify at least one instance ID.

    */
    inline ExitStandbyRequest& AddInstanceIds(Aws::String&& value) { m_instanceIdsHasBeenSet = true; m_instanceIds.push_back(value); return *this; }

    /*

One or more instance IDs. You must specify at least one instance ID.

    */
    inline ExitStandbyRequest& AddInstanceIds(const char* value) { m_instanceIdsHasBeenSet = true; m_instanceIds.push_back(value); return *this; }

    /*

The name of the Auto Scaling group.

    */
    inline const Aws::String& GetAutoScalingGroupName() const{ return m_autoScalingGroupName; }

    /*

The name of the Auto Scaling group.

    */
    inline void SetAutoScalingGroupName(const Aws::String& value) { m_autoScalingGroupNameHasBeenSet = true; m_autoScalingGroupName = value; }

    /*

The name of the Auto Scaling group.

    */
    inline void SetAutoScalingGroupName(Aws::String&& value) { m_autoScalingGroupNameHasBeenSet = true; m_autoScalingGroupName = value; }

    /*

The name of the Auto Scaling group.

    */
    inline void SetAutoScalingGroupName(const char* value) { m_autoScalingGroupNameHasBeenSet = true; m_autoScalingGroupName.assign(value); }

    /*

The name of the Auto Scaling group.

    */
    inline ExitStandbyRequest& WithAutoScalingGroupName(const Aws::String& value) { SetAutoScalingGroupName(value); return *this;}

    /*

The name of the Auto Scaling group.

    */
    inline ExitStandbyRequest& WithAutoScalingGroupName(Aws::String&& value) { SetAutoScalingGroupName(value); return *this;}

    /*

The name of the Auto Scaling group.

    */
    inline ExitStandbyRequest& WithAutoScalingGroupName(const char* value) { SetAutoScalingGroupName(value); return *this;}

  private:
    Aws::Vector<Aws::String> m_instanceIds;
    bool m_instanceIdsHasBeenSet;
    Aws::String m_autoScalingGroupName;
    bool m_autoScalingGroupNameHasBeenSet;
  };

} // namespace Model
} // namespace AutoScaling
} // namespace Aws


text:
var challengeServices = angular.module('challengeServices', [
    'ngResource',
    'globalServices']);

challengeServices.service('challengeService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
      var cache = $cacheFactory('challengeCache');
      var cacheTimeout = 30000;
      var res = $resource('/api/challenges/:cid', {}, {
        'get': {method: 'GET', cache: cache},
        'save': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'},
      });
      this.get = res.get;
      this.delete = res.delete;
      this.save = function() {
        cache.removeAll();
        return res.save.apply(res, arguments);
      };
      this.create = function() {
        cache.removeAll();
        return res.create.apply(res, arguments);
      };
      this.flush = cache.removeAll;
      $rootScope.$on('correctAnswer', cache.removeAll);
      return this;
    }]);

challengeServices.service('tagService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
        var tagCache = $cacheFactory('tagCache');

        this.res = $resource('/api/tags/:tagslug', {}, {
            'get': {method: 'GET', tagCache},
            'save': {method: 'PUT'},
            'create': {method: 'POST'},
        })

        this.get = this.res.get;
        this.save = this.res.save;
        this.create = this.res.create;
        this.delete = this.res.delete;

        this.getList = function(callback) {
            if (this.taglist) {
                callback(this.taglist);
                return;
            }
            this.res.get(angular.bind(this, function(data) {
                this.taglist = data;
                $timeout(
                    angular.bind(this, function() {
                        this.taglist = null;
                        tagCache.removeAll();
                    }),
                30000, false);
                callback(data);
            }))
            $rootScope.$on('$locationChangeSuccess', function() {
                this.taglist = null;
                tagCache.removeAll();
            });
        }

    }
])

challengeServices.service('attachService', [
    '$resource',
    '$rootScope',
    '$cacheFactory',
    '$timeout',
    function($resource, $rootScope, $cacheFactory, $timeout) {
        var attachCache = $cacheFactory('attachCache');

        this.res = $resource('/api/attachments/:aid', {}, {
            'get': {method: 'GET', attachCache},
            'save': {method: 'PUT'},
        })

        this.get = this.res.get;
        this.create = this.res.create;
        this.save = this.res.save;
        this.delete = this.res.delete;

        this.getList = function(callback) {
            if (this.attachlist) {
                callback(this.attachlist);
                return;
            }
            this.res.get(angular.bind(this, function(data) {
                this.attachlist = data;
                $timeout(
                    angular.bind(this, function() {
                        this.attachlist = null;
                        attachCache.removeAll();
                    }),
                30000, false);
                callback(data);
            }))
            $rootScope.$on('$locationChangeSuccess', function() {
                this.attachlist = null;
                attachCache.removeAll();
            });
        }

    }
])

challengeServices.service('answerService', [
    '$resource',
    '$rootScope',
    function($resource, $rootScope) {
      this.res = $resource('/api/answers/:aid', {}, {
        'create': {method: 'POST'}
      });
      this.create = function(what, success, failure) {
        this.res.create(what,
            function(resp) {
              success(resp);
              $rootScope.$broadcast('correctAnswer');
            },
            failure);
      };
    }]);

challengeServices.service('validatorService', [
    '$resource',
    '$rootScope',
    function($resource, $rootScope) {
      this.res = $resource('/api/validator', {}, {
        'create': {method: 'POST'}
      });
      this.create = function(what, success, failure) {
        this.res.create(what,
            function(resp) {
              success(resp);
            },
            failure);
      };
    }]);

challengeServices.service('scoreService', [
    'configService',
    function(configService) {
      this.scoring = 'plain';
      configService.get(angular.bind(this, function(cfg) {
        this.scoring = cfg.scoring;
      }));
      this.getCurrentPoints = function(challenge) {
        if (!challenge)
          return 0;
        return challenge.current_points;
      };
    }])

redpajama_set_name: RedPajamaGithub


text:
/* eslint-disable */

const browserSync = require('browser-sync').create();
const gulp = require('gulp');
const gutil = require('gulp-util');
const nodemon = require('gulp-nodemon');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

const devConfig = require('./webpack.dev.config');
const prdConfig = require('./webpack.prd.config');

gulp.task('build:webpack', [], function(callback) {
  webpack(prdConfig, function(err, stats) {
    if (err) throw new gutil.PluginError('webpack', err);

    gutil.log('[webpack]', stats.toString());

    callback();
  });
});

gulp.task('serve:bs', function() {

  const compiler = webpack(devConfig);

  browserSync.init({
    middleware: [
      webpackDevMiddleware(compiler, {
        noInfo: true,
        publicPath: devConfig.output.publicPath,
        stats: {
          colors: true,
        },
        watchOptions: {
          poll: true,
        },
      }),
      webpackHotMiddleware(compiler)
    ],
    open: false,
    proxy: 'https://rp.rshackleton.local/',
    port: 3000
  });
});

gulp.task('build', ['build:webpack']);
gulp.task('default', ['serve:bs']);


text:
(function() {
  var Logger, baselog, k, rpc, v,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  baselog = require('iced-logger');

  rpc = require('framed-msgpack-rpc').log;

  Logger = (function(_super) {
    __extends(Logger, _super);

    function Logger() {
      return Logger.__super__.constructor.apply(this, arguments);
    }

    Logger.prototype._log = function(m, l, ohook) {
      var map, msg, parts;
      parts = [];
      if (this.prefix != null) {
        parts.push(this.prefix);
      }
      parts.push(m);
      msg = parts.join(" ");
      map = {
        D: "debug",
        I: "info",
        W: "warn",
        E: "error",
        F: "fatal"
      };
      l = map[l] || "warn";
      return baselog[l](msg);
    };

    Logger.prototype.make_child = function(d) {
      return new Logger(d);
    };

    return Logger;

  })(rpc.Logger);

  rpc.set_default_logger_class(Logger);

  for (k in baselog) {
    v = baselog[k];
    exports[k] = v;
  }

}).call(this);


text:
import dectools.dectools as dectools
from print_buffer import print_buffer
p = print_buffer()
prnt = p.rint
printed = p.rinted

prnt("testing @dectools.(make)?_call_if")

prnt("Testing the @dectools.call_once")

def add_author(function):
    function.__author__ = "ME"

@dectools.call_once(add_author)
def think():
    prnt("THINK!")

prnt("Call once returns the original function:", think.__name__)
printed("Call once returns the original function: think")

prnt("Now we have an attribute:", think.__author__)
printed("Now we have an attribute: ME")

def register(function, url):
    prnt("In a real world, this would register", function.__name__, "to the url", url)

@dectools.call_once(register, url="license.html")
def license():
    prnt("All your base belong to us!")
printed("In a real world, this would register license to the url license.html")

def once(function):
    prnt("Just decorated", function.__name__)

@dectools.call_once(once)
def hello():
    prnt("Hello")
printed("Just decorated hello")
prnt("Hello still works")
hello()
printed("Hello")

@dectools.call_once(once)
@dectools.call_once(once)
@dectools.call_once(register, "goodbye.html")
@dectools.call_once(register, url="done.html")
def goodbye():
    prnt("Goodbye!")
printed("In a real world, this would register goodbye to the url done.html", -4)
printed("In a real world, this would register goodbye to the url goodbye.html", -3)
printed("Just decorated goodbye", -2)
printed("Just decorated goodbye")

goodbye()
printed("Goodbye!")
prnt("All Done")


text:
std::string util::getTempFileName(std::string tmpDir, std::string prefix, std::string suffix) {
	boost::filesystem::path temp_dir;
	if (tmpDir == "") {
		temp_dir = boost::filesystem::temp_directory_path();
	}
	else {
		temp_dir = tmpDir;
	}
	std::ostringstream tmpfn_model_str;
	tmpfn_model_str << prefix << "%%%%%%%%%%" << suffix;

	boost::filesystem::path tmpfn_model(tmpfn_model_str.str());
	boost::filesystem::path tmpfn = temp_dir / boost::filesystem::unique_path(tmpfn_model);
	return tmpfn.string();
}


text:
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">

<chapter id="general" xmlns:xi="http://www.w3.org/2001/XInclude">
    <title>General usage</title>

    <para>
    The General usage section covers aspects that are not covered in the tutorial section of the reference documentation.
    It follows a use case oriented structure.
    </para>

    <xi:include href="general/creating-queries.xml" />
    <xi:include href="general/result-handling.xml"/>
    <xi:include href="general/codegen.xml"/>
    <xi:include href="general/alias.xml" />

</chapter>


text:
<?php
  require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
  abstract class FunctionalTestCase extends PHPUnit_Extensions_Selenium2TestCase {

    protected function assertIsLocation($url,$message = '') {
      $this->assertEquals($this->getLocation(),$url,$message);
    }

    protected function assertHasNotErrorMessages($message = '') {
      $this->assertTextNotPresent('Fatal Error','Fatal Error '.$message);
      $this->assertTextNotPresent('error','error '.$message);
      $this->assertTextNotPresent('warning','warning '.$message);
      $this->assertTextNotPresent('Notice','notice '.$message);
    }

    protected function assertIsElementPresent($locator,$message='') {
      $this->assertTrue($this->isElementPresent($locator),'unable to find '.$locator.' '.$message);
    }

  }


text:
package org.continuousassurance.swamp.util;

import org.apache.commons.lang.ArrayUtils;

import java.security.SecureRandom;
import java.util.ArrayList;

import static org.continuousassurance.swamp.util.DebugUtil.intersection;

/**
 * This is a class that will generate a random SWAMP password according to the spec.
 * This means that a password must have at least one of each of 9 characters long

 *

 *
lower case

 *
upper case

 *
number

 *
special character

 *

 * ~ ` ! @ # $ % ^ & * ( ) _ + = | \ [ ] { } ? / . , < > ; : ' " and space " "
 *

 *
Created by Jeff Gaynor

 * on 10/8/14 at  3:18 PM
 */
public class PasswordGenerator {
    protected static void init() {
        if (isInit) return;
        String s = "abcdefghijklmnopqrstuvwxyz";
        LOWER_CASE = ArrayUtils.toObject(s.toCharArray());
        UPPER_CASE = ArrayUtils.toObject(s.toUpperCase().toCharArray());
        s = "0123456789";
        NUMBERS = ArrayUtils.toObject(s.toCharArray());
        // %<>&
        s = "~`!@#$^*()_+=|\\[]{}?/.,;:'\" ";
        SPECIAL_CHARS = ArrayUtils.toObject(s.toCharArray());
        CHARACTER_CLASSES = new Object[4];
        CHARACTER_CLASSES[0] = LOWER_CASE;
        CHARACTER_CLASSES[1] = UPPER_CASE;
        CHARACTER_CLASSES[2] = NUMBERS;
        CHARACTER_CLASSES[3] = SPECIAL_CHARS;
        isInit = true;
    }

    public static Character[] specialCharacters(){
        init();
        // Do not return the set of special characters, just a copy since otherwise someone might
        // inadvertently change it.
        Character[] x = new Character[SPECIAL_CHARS.length];
        System.arraycopy(SPECIAL_CHARS, 0, x, 0, x.length);
        return x;
    }
    static Character[] LOWER_CASE;
    static Character[] UPPER_CASE;
    static Character[] NUMBERS;
    static Character[] SPECIAL_CHARS;
    static Object[] CHARACTER_CLASSES;
    static boolean isInit = false;

    /**
     * Create a password of the given length using all password character classes.
     * @param length
     * @return
     */
    public static String generate(int length) {
              return generate(length, 4);
    }
    public static String generate(int length, int characterClassCount) {
        init();
        ArrayList<Character> arrayList = new ArrayList<Character>();

        int[] partion = partition(length, characterClassCount);
        for (int i = 0; i < characterClassCount; i++) {
            arrayList.addAll(generate((Character[]) CHARACTER_CLASSES[i], partion[i]));
        }
        java.util.Collections.shuffle(arrayList);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arrayList.size(); i++) {
            sb.append(arrayList.get(i));
        }
        return sb.toString();
    }

    /**
     * Partitions the integer x into the number of partitions. A partition
     * meaning that the sum of the resulting integers = x. E.g. to partition
     * the number 9 into 4 partitions you might get 1,3,2,3 or perhaps 6,1,1,1
     *
     * @param x
     * @param partitions
     * @return
     */
    protected static int[] partition(int x, int partitions) {

        int[] out = new int[partitions];
        for (int i = 0; i < out.length; i++) {
            out[i] = 1; // required since need at least one in each slot
        }
        int seed = x - partitions;
        for (int i = 0; i < out.length - 1; i++) {
            int r = secureRandom.nextInt(seed);
            out[i] = out[i] + r;
            seed = seed - r;
        }
        out[out.length - 1] = seed + out[out.length - 1];
        return out;

    }

    public static SecureRandom secureRandom = new SecureRandom();

    /**
     * Given a character class and an integer, n, get n random characters from the class.
     *
     * @param chars
     * @param n
     * @return
     */
    protected static ArrayList<Character> generate(Character[] chars, int n) {
        ArrayList<Character> sb = new ArrayList<Character>();
        for (int i = 0; i < n; i++) {
            sb.add(chars[secureRandom.nextInt(chars.length)]);
        }
        return sb;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("pwd(9,4)=" + generate(9, 4));
            System.out.println("pwd(10,3)=" + generate(10, 3));
        }
        String x = generate(10, 3);
        String y = generate(10, 3);
        System.out.println("generating intersection of passwords " + x + ", and " + y);
        Character[] zz = intersection(x, y);

        //zz = intersection(zz, x);
        if (zz.length == 0) {
            System.out.println("(none)");
        } else {
            for (Character q : zz) {
                System.out.print(q);
            }
        }
    }
}


text:
#ifndef SPLATT_UTIL_H
#define SPLATT_UTIL_H

/******************************************************************************
 * INCLUDES
 *****************************************************************************/
#include "base.h"
#include "utils.h"

double locate_ind_special (
  size_t const * const array, // non-decreasing array
  idx_t const length,
  size_t const ele,
  idx_t const nmodes);

idx_t argmin_elem_range(
  idx_t const * const arr,
  idx_t const N,
  idx_t const con);

idx_t array_max(
  idx_t const * const arr,
  idx_t const N);

idx_t array_min(
  idx_t const * const arr,
  idx_t const N);

idx_t array_min_range(
  idx_t const * const arr,
  idx_t const N,
  idx_t const con);

#endif


text:
<?php

namespace GraphCommons\Graph\Entity;

use GraphCommons\Graph\GraphEntity;

/**
 * @package    GraphCommons
 * @subpackage GraphCommons\Graph\Entity
 * @object     GraphCommons\Graph\Entity\Layout
 * @extends    GraphCommons\Graph\GraphEntity
 * @author     Kerem Güneş <qeremy@gmail.com>
 */
final class Layout extends GraphEntity
{
    /**
     * Gravity.
     * @var float
     */
    protected $gravity;

    /**
     * Drag coeff.
     * @var float
     */
    protected $dragCoeff;

    /**
     * Spring coeff.
     * @var float
     */
    protected $springCoeff;

    /**
     * Spring length.
     * @var float
     */
    protected $springLength;

    /**
     * Theta.
     * @var float
     */
    protected $theta;

    /**
     * Algorithm.
     * @var string
     */
    protected $algorithm;

    /**
     * Transform.
     * @var string
     */
    protected $transform;

    /**
     * Set gravity.
     *
     * @param  float $gravity
     * @return self
     */
    final public function setGravity($gravity)
    {
        $this->gravity = (float) $gravity;
        return $this;
    }

    /**
     * Set grag coeff.
     *
     * @param  float $dragCoeff
     * @return self
     */
    final public function setDragCoeff($dragCoeff)
    {
        $this->dragCoeff = (float) $dragCoeff;
        return $this;
    }

    /**
     * Set spring coeff.
     *
     * @param  float $springCoeff
     * @return self
     */
    final public function setSpringCoeff($springCoeff)
    {
        $this->springCoeff = (float) $springCoeff;
        return $this;
    }

    /**
     * Set spring length.
     *
     * @param  int $springLength
     * @return self
     */
    final public function setSpringLength($springLength)
    {
        $this->springLength = (int) $springLength;
        return $this;
    }

    /**
     * Set theta.
     *
     * @param  float $theta
     * @return self
     */
    final public function setTheta($theta)
    {
        $this->theta = (float) $theta;
        return $this;
    }

    /**
     * Set algorithm.
     *
     * @param  string $algorithm
     * @return self
     */
    final public function setAlgorithm($algorithm)
    {
        $this->algorithm = (string) $algorithm;
        return $this;
    }

    /**
     * Set transform.
     *
     * @param  string $transform
     * @return self
     */
    final public function setTransform($transform)
    {
        $this->transform = (string) $transform;
        return $this;
    }

    /**
     * Get gravity.
     *
     * @return float
     */
    final public function getGravity()
    {
        $this->gravity = $gravity;
        return $this;
    }

    /**
     * Get drag coeff.
     *
     * @return float
     */
    final public function getDragCoeff()
    {
        $this->dragCoeff = $dragCoeff;
        return $this;
    }

    /**
     * Get spring coeff.
     *
     * @return float
     */
    final public function getSpringCoeff()
    {
        $this->springCoeff = $springCoeff;
        return $this;
    }

    /**
     * Get spring length.
     *
     * @return int
     */
    final public function getSpringLength()
    {
        $this->springLength = $springLength;
        return $this;
    }

    /**
     * Get theta.
     *
     * @return float
     */
    final public function getTheta()
    {
        $this->theta = $theta;
        return $this;
    }

    /**
     * Get algorithm.
     *
     * @return string
     */
    final public function getAlgorithm()
    {
        $this->algorithm = $algorithm;
        return $this;
    }

    /**
     * Get transform.
     *
     * @return string
     */
    final public function getTransform()
    {
        $this->transform = $transform;
        return $this;
    }
}


text:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {NglPill} from './pill';
import {NglPillImage} from './pill-image';
import {NglPillLink} from './pill-link';
import {NglPillRemove} from './pill-remove';
import {NglIconsModule} from '../icons/module';

const NGL_PILL_DIRECTIVES = [
  NglPill,
  NglPillImage,
  NglPillLink,
  NglPillRemove,
];

@NgModule({
  declarations: [NGL_PILL_DIRECTIVES],
  exports: [NGL_PILL_DIRECTIVES],
  imports: [CommonModule, NglIconsModule],
})
export class NglPillsModule {}


text:
class Dice

  def roll
    return Random.rand(1..6)
  end

end


text:
package com.opengamma.web.analytics.rest;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

import org.json.JSONArray;

import com.google.common.collect.Lists;
import com.opengamma.engine.marketdata.spec.HistoricalMarketDataSpecification;
import com.opengamma.master.config.ConfigDocument;
import com.opengamma.master.config.ConfigMaster;
import com.opengamma.master.config.ConfigSearchRequest;
import com.opengamma.master.config.impl.ConfigSearchIterator;
import com.opengamma.master.historicaltimeseries.impl.HistoricalTimeSeriesRating;
import com.opengamma.util.ArgumentChecker;

/**
 * REST resource for looking up a list of valid values for time series resolver keys to use in a
 * {@link HistoricalMarketDataSpecification}. These correspond to the names of {@link HistoricalTimeSeriesRating}
 * instances stored in the configuration database.
 * @see com.opengamma.web.analytics.MarketDataSpecificationJsonReader
 */
@Path("timeseriesresolverkeys")
public class TimeSeriesResolverKeysResource {

  /**
   * The config master.
   */
  private final ConfigMaster _configMaster;

  /**
   * Creates an instance.
   *
   * @param configMaster  the config master, not null
   */
  public TimeSeriesResolverKeysResource(ConfigMaster configMaster) {
    ArgumentChecker.notNull(configMaster, "configMaster");
    _configMaster = configMaster;
  }

  /**
   * @return JSON array of resolver keys: {@code ["KEY1", "KEY2", ...]}
   */
  @GET
  public String getResolverKeys() {
    ConfigSearchRequest<HistoricalTimeSeriesRating> request =
        new ConfigSearchRequest<HistoricalTimeSeriesRating>(HistoricalTimeSeriesRating.class);
    List<String> keyNames = Lists.newArrayList();
    for (ConfigDocument doc : ConfigSearchIterator.iterable(_configMaster, request)) {
      keyNames.add(doc.getName());
    }
    return new JSONArray(keyNames).toString();
  }

}


text:
#ifndef H_BSP_H
#define H_BSP_H

#include <inttypes.h>
#include <mcu/mcu.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Define special stackos sections */
#define sec_data_core   __attribute__((section(".data.core")))
#define sec_bss_core    __attribute__((section(".bss.core")))
#define sec_bss_nz_core __attribute__((section(".bss.core.nz")))

/* More convenient section placement macros. */
#define bssnz_t         sec_bss_nz_core

extern uint8_t _ram_start;
extern uint8_t _ccram_start;

#define RAM_SIZE        (128 * 1024)
#define CCRAM_SIZE      (64 * 1024)

/* LED pins */
#define LED_BLINK_PIN   MCU_GPIO_PORTC(1)

#ifdef __cplusplus
}
#endif

#endif  /* H_BSP_H */


text:
class MajorsController < ApplicationController
  authorize_resource

  helper :student_majors

  active_scaffold :major do |config|
    config.list.sorting = {:name => 'ASC'}
    config.create.label = :create_major_label
    #este abaixo não está funcionando...
    config.update.label = :update_major_label

    config.columns[:institution].clear_link
    config.columns[:level].clear_link
    config.columns[:level].form_ui = :select
    config.columns[:institution].form_ui = :record_select

    config.columns[:student_majors].includes = [:students, :student_majors]

    config.list.columns = [:name, :level, :institution, :students]
    config.create.columns = [:name, :level, :institution, :student_majors]
    config.update.columns = [:name, :level, :institution, :student_majors]
    config.show.columns = [:name, :level, :institution, :students]

  end
  record_select :per_page => 10, :search_on => [:name], :order_by => 'name', :full_text_search => true
end


text:
package io.netty.util.internal;

import static io.netty.util.internal.ObjectUtil.checkNonEmpty;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * A collection of utility methods to retrieve and parse the values of the Java system properties.
 */
public final class SystemPropertyUtil {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(SystemPropertyUtil.class);

    /**
     * Returns {@code true} if and only if the system property with the specified {@code key}
     * exists.
     */
    public static boolean contains(String key) {
        return get(key) != null;
    }

    /**
     * Returns the value of the Java system property with the specified
     * {@code key}, while falling back to {@code null} if the property access fails.
     *
     * @return the property value or {@code null}
     */
    public static String get(String key) {
        return get(key, null);
    }

    /**
     * Returns the value of the Java system property with the specified
     * {@code key}, while falling back to the specified default value if
     * the property access fails.
     *
     * @return the property value.
     *         {@code def} if there's no such property or if an access to the
     *         specified property is not allowed.
     */
    public static String get(final String key, String def) {
        checkNonEmpty(key, "key");

        String value = null;
        try {
            if (System.getSecurityManager() == null) {
                value = System.getProperty(key);
            } else {
                value = AccessController.doPrivileged(new PrivilegedAction<String>() {
                    @Override
                    public String run() {
                        return System.getProperty(key);
                    }
                });
            }
        } catch (SecurityException e) {
            logger.warn("Unable to retrieve a system property '{}'; default values will be used.", key, e);
        }

        if (value == null) {
            return def;
        }

        return value;
    }

    /**
     * Returns the value of the Java system property with the specified
     * {@code key}, while falling back to the specified default value if
     * the property access fails.
     *
     * @return the property value.
     *         {@code def} if there's no such property or if an access to the
     *         specified property is not allowed.
     */
    public static boolean getBoolean(String key, boolean def) {
        String value = get(key);
        if (value == null) {
            return def;
        }

        value = value.trim().toLowerCase();
        if (value.isEmpty()) {
            return def;
        }

        if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) {
            return true;
        }

        if ("false".equals(value) || "no".equals(value) || "0".equals(value)) {
            return false;
        }

        logger.warn(
                "Unable to parse the boolean system property '{}':{} - using the default value: {}",
                key, value, def
        );

        return def;
    }

    /**
     * Returns the value of the Java system property with the specified
     * {@code key}, while falling back to the specified default value if
     * the property access fails.
     *
     * @return the property value.
     *         {@code def} if there's no such property or if an access to the
     *         specified property is not allowed.
     */
    public static int getInt(String key, int def) {
        String value = get(key);
        if (value == null) {
            return def;
        }

        value = value.trim();
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            // Ignore
        }

        logger.warn(
                "Unable to parse the integer system property '{}':{} - using the default value: {}",
                key, value, def
        );

        return def;
    }

    /**
     * Returns the value of the Java system property with the specified
     * {@code key}, while falling back to the specified default value if
     * the property access fails.
     *
     * @return the property value.
     *         {@code def} if there's no such property or if an access to the
     *         specified property is not allowed.
     */
    public static long getLong(String key, long def) {
        String value = get(key);
        if (value == null) {
            return def;
        }

        value = value.trim();
        try {
            return Long.parseLong(value);
        } catch (Exception e) {
            // Ignore
        }

        logger.warn(
                "Unable to parse the long integer system property '{}':{} - using the default value: {}",
                key, value, def
        );

        return def;
    }

    private SystemPropertyUtil() {
        // Unused
    }
}


text:
/*!
  \class SoMemoryError SoMemoryError.h Inventor/errors/SoMemoryError.h
  \brief The SoMemoryError class is used to inform of problems with memory allocation.
  \ingroup errors

  Modern operating systems takes care of handling most out of memory
  conditions for you, but in certain situations it can be wise to do
  some manual checking and intervention. This class is provided as an
  aid to help out in these situations.

  The basic design of the Coin library is to pass on the
  responsibility for handling failed attempts at memory allocation to
  the application programmer. If you want to detect and take care of
  these, you should compile Coin with the C++ exception throwing on
  and wrap your code within \c try{} and \c catch{} blocks. The most
  you can do if you get a failed allocation is typically to notify the
  user and then exit the application, though, and this is something
  most operating systems will do for you, so you probably need not
  consider this at all.

  So, where does the SoMemoryError class come in handy? There are
  certain things which could happen within the library which are best
  taken care of by internally handling failed attempts at memory
  allocation. An example: the user tries to load a model file which
  contains a filename pointer to a huge bitmapfile with a texture
  map. The end-user's system does not provide enough memory to load
  the file and prepare the texture image for rendering, though. This
  is a case where it is possible to just emit a warning and
  continue. The warning will then be passed through this class.

  Note that SoMemoryError is probably not of much use to the
  application programmer.
*/

// *************************************************************************

#include <Inventor/errors/SoMemoryError.h>

#include <cstdio>

#include <Inventor/SoType.h>
#include <Inventor/SbName.h>

// *************************************************************************

SoType SoMemoryError::classTypeId STATIC_SOTYPE_INIT;
SoErrorCB * SoMemoryError::callback = SoError::defaultHandlerCB;
void * SoMemoryError::callbackData = NULL;

// *************************************************************************

// Documented for parent class.
void
SoMemoryError::initClass(void)
{
  SoMemoryError::callback = SoError::defaultHandlerCB;
  SoMemoryError::callbackData = NULL;
  SoMemoryError::classTypeId =
    SoType::createType(SoError::getClassTypeId(), "MemoryError");
}

// Documented for parent class.
SoType
SoMemoryError::getClassTypeId(void)
{
  return SoMemoryError::classTypeId;
}

// Documented for parent class.
SoType
SoMemoryError::getTypeId(void) const
{
  return SoMemoryError::classTypeId;
}

// Documented for parent class.
void
SoMemoryError::setHandlerCallback(SoErrorCB * const function,
                                  void * const data)
{
  /* FIXME: Overriding the error handler for subclasses of SoError
     doesn't work yet. Use SoError::setHandlerCallback() instead as a
     workaround, but note that this will stop working when callback
     override is implemented properly. 2003-01-22 thammer.
  */
  SoMemoryError::callback = function;
  SoMemoryError::callbackData = data;
}

// Documented for parent class.
SoErrorCB *
SoMemoryError::getHandlerCallback(void)
{
  return SoMemoryError::callback;
}

// Documented for parent class.
void *
SoMemoryError::getHandlerData(void)
{
  return SoMemoryError::callbackData;
}

/*!
  Posts a warning about a failed memory allocation. \a whatWasAllocated
  should contain a description of what we tried to allocate.
*/
void
SoMemoryError::post(const char * const whatWasAllocated)
{
  SoMemoryError error;
  error.setDebugString("ERROR allocating '");
  error.appendToDebugString(whatWasAllocated);
  error.appendToDebugString("'.");
  error.handleError();
}

// Documented for parent class.
SoErrorCB * SoMemoryError::getHandler(void * & data) const
{
  data = SoMemoryError::callbackData;
  return SoMemoryError::callback;
}


text:
@implementation CNATPMPManager

@synthesize publicAddress;

- (id)init
{
if ((self = [super init]) != NULL)
	{
	initnatpmp(&natpmp);
	}
return(self);
}

- (void)dealloc
{
closenatpmp(&natpmp);
}

- (NSData *)externalAddress:(NSError **)outError;
{
#pragma unused (outError)

int theResult = sendpublicaddressrequest(&natpmp);
natpmpresp_t theResponse;
while (YES)
	{
	theResult = readnatpmpresponseorretry(&natpmp, &theResponse);
	if(theResult < 0 && theResult != NATPMP_TRYAGAIN)
		{
		return(NULL);
		}
	else if (theResult != NATPMP_TRYAGAIN)
		{
		self.publicAddress = [NSData dataWithBytes:&theResponse.publicaddress.addr length:sizeof(theResponse.publicaddress.addr)];
		return (self.publicAddress);
		}
	}
}

- (BOOL)openPortForProtocol:(int)protocol privatePort:(int)privateport publicPort:(int)publicport lifetime:(int)lifetime error:(NSError **)outError
{
#pragma unused (outError)
natpmpresp_t theResponse;
int theResult;

theResult = sendnewportmappingrequest(&natpmp, protocol, privateport, publicport, lifetime);

while (YES)
	{
	theResult = readnatpmpresponseorretry(&natpmp, &theResponse);
	if (theResult < 0 && theResult != NATPMP_TRYAGAIN)
		return(NO);
	else if(theResult!=NATPMP_TRYAGAIN)
		{
//		NSLog(@"mapped public port: %d", theResponse.newportmapping.mappedpublicport);
//		NSLog(@" private port: %d", theResponse.newportmapping.privateport);
//		NSLog(@"mapped lifetime: %d", theResponse.newportmapping.lifetime);
//				copy(publicport, response.newportmapping.mappedpublicport);
//				copy(privateport, response.newportmapping.privateport);
//				copy(mappinglifetime, response.newportmapping.lifetime);
		return(YES);
		}
	}
}

@end


text:
package org.testmonkeys.jentitytest.test.integration.nullChecks;

import org.hamcrest.core.StringContains;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.testmonkeys.jentitytest.hamcrest.Entity;

import static org.junit.Assert.assertThat;

public class NullCheckDetailsTest {
    @Rule
    public ExpectedException expectedEx = ExpectedException.none();

    @Test
    public void expectedNotNull_String() {

        expectedEx.expect(AssertionError.class);
        expectedEx.expectMessage(StringContains.containsString("Property: Address.street\n" +
                "\tExpected: not null (\"street1\")\n" +
                "\tActual: null"));

        Address expected = new Address();
        expected.setStreet("street1");
        Address actual = new Address();
        assertThat(actual, Entity.isEqualTo(expected));
    }

    @Test
    public void expectedNull_String() {

        expectedEx.expect(AssertionError.class);
        expectedEx.expectMessage(StringContains.containsString("Property: Address.street\n" +
                "\tExpected: null\n" +
                "\tActual: not null (\"street1\")"));

        Address actual = new Address();
        actual.setStreet("street1");
        Address expected = new Address();
        assertThat(actual, Entity.isEqualTo(expected));
    }

    @Test
    public void expectedNotNull_Object() {

        expectedEx.expect(AssertionError.class);
        expectedEx.expectMessage(StringContains.containsString("Property: NullCheckModel.address\n" +
                "\tExpected: not null ({\"street\":\"street1\"})\n" +
                "\tActual: null"));

        Address address = new Address();
        address.setStreet("street1");
        NullCheckModel expected = new NullCheckModel();
        expected.setAddress(address);
        NullCheckModel actual = new NullCheckModel();
        assertThat(actual, Entity.isEqualTo(expected));
    }

    @Test
    public void actualNotNull_Object() {

        expectedEx.expect(AssertionError.class);
        expectedEx.expectMessage(StringContains.containsString("Property: NullCheckModel.address\n" +
                "\tExpected: null\n" +
                "\tActual: not null ({\"street\":\"street1\"})\n" +
                "Comparison was performed using SimpleTypeComparator"));

        Address address = new Address();
        address.setStreet("street1");
        NullCheckModel expected = new NullCheckModel();
        NullCheckModel actual = new NullCheckModel();
        actual.setAddress(address);
        assertThat(actual, Entity.isEqualTo(expected));
    }

}


text:
require 'spec_helper'

describe NoteObserver do
  subject { NoteObserver.instance }

  let(:team_without_author) { (1..2).map { |n| double :user, id: n } }

  describe '#after_create' do
    let(:note) { double :note }

    it 'is called after a note is created' do
      subject.should_receive :after_create

      Note.observers.enable :note_observer do
        create(:note)
      end
    end

    it 'sends out notifications' do
      subject.should_receive(:send_notify_mails).with(note)

      subject.after_create(note)
    end
  end

  describe "#send_notify_mails" do
    let(:note) { double :note, notify: false, notify_author: false }

    it 'notifies team of new note when flagged to notify' do
      note.stub(:notify).and_return(true)
      subject.should_receive(:notify_team).with(note)

      subject.after_create(note)
    end

    it 'does not notify team of new note when not flagged to notify' do
      subject.should_not_receive(:notify_team).with(note)

      subject.after_create(note)
    end

    it 'notifies the author of a commit when flagged to notify the author' do
      note.stub(:notify_author).and_return(true)
      note.stub(:noteable).and_return(double(author_email: 'test@test.com'))
      note.stub(:id).and_return(42)
      author = double :user, id: 1, email: 'test@test.com'
      note.stub(:commit_author).and_return(author)
      Notify.should_receive(:note_commit_email)

      subject.after_create(note)
    end

    it 'does not notify the author of a commit when not flagged to notify the author' do
      notify.should_not_receive(:note_commit_email)

      subject.after_create(note)
    end

    it 'does nothing if no notify flags are set' do
      subject.after_create(note).should be_nil
    end
  end

  describe '#notify_team' do
    let(:note) { double :note, id: 1 }

    before :each do
      subject.stub(:team_without_note_author).with(note).and_return(team_without_author)
    end

    context 'notifies team of a new note on' do
      it 'a commit' do
        note.stub(:noteable_type).and_return('Commit')
        notify.should_receive(:note_commit_email).twice

        subject.send(:notify_team, note)
      end

      it 'an issue' do
        note.stub(:noteable_type).and_return('Issue')
        notify.should_receive(:note_issue_email).twice

        subject.send(:notify_team, note)
      end

      it 'a wiki page' do
        note.stub(:noteable_type).and_return('Wiki')
        notify.should_receive(:note_wiki_email).twice

        subject.send(:notify_team, note)
      end

      it 'a merge request' do
        note.stub(:noteable_type).and_return('MergeRequest')
        notify.should_receive(:note_merge_request_email).twice

        subject.send(:notify_team, note)
      end

      it 'a wall' do
        # Note: wall posts have #noteable_type of nil
        note.stub(:noteable_type).and_return(nil)
        notify.should_receive(:note_wall_email).twice

        subject.send(:notify_team, note)
      end
    end

    it 'does nothing for a new note on a snippet' do
      note.stub(:noteable_type).and_return('Snippet')

      subject.send(:notify_team, note).should be_nil
    end
  end

  describe '#team_without_note_author' do
    let(:author) { double :user, id: 4 }

    let(:users) { team_without_author + [author] }
    let(:project)  { double :project, users: users }
    let(:note) { double :note, project: project, author: author }

    it 'returns the projects user without the note author included' do
      subject.send(:team_without_note_author, note).should == team_without_author
    end
  end

  def notify
    Notify
  end
end


text:
package org.geotools.gpx.gpx10;

import java.util.List;

import javax.xml.namespace.QName;

import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.gpx.GPXField;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.xsd.AbstractComplexBinding;
import org.geotools.xsd.ElementInstance;
import org.geotools.xsd.Node;
import org.opengis.feature.Feature;
import org.opengis.feature.simple.SimpleFeatureType;

import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiLineString;

/**
 * Binding object for the type http://www.topografix.com/GPX/1/1:trkType.
 *
 *

 *

 *
 *  <?xml version="1.0" encoding="UTF-8"?><xsd:complexType name="trkType" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

 *      <xsd:annotation>

 *        <xsd:documentation>

 *  		trk represents a track - an ordered list of points describing a path.

 *  	  </xsd:documentation>

 *  	</xsd:annotation>

 *      <xsd:sequence>

 *        <xsd:element minOccurs="0" name="name" type="xsd:string">

 *  		<xsd:annotation>

 *  		  <xsd:documentation>

 *  			GPS name of track.

 *  		  </xsd:documentation>

 *  		</xsd:annotation>

 *  	  </xsd:element>

 *  	  <xsd:element minOccurs="0" name="cmt" type="xsd:string">

 *  		<xsd:annotation>

 *  		  <xsd:documentation>

 *  			GPS comment for track.

 *  		  </xsd:documentation>

 *  		</xsd:annotation>

 *  	  </xsd:element>

 *        <xsd:element minOccurs="0" name="desc" type="xsd:string">

 *  		<xsd:annotation>

 *  		  <xsd:documentation>

 *  			User description of track.

 *  		  </xsd:documentation>

 *  		</xsd:annotation>

 *  	  </xsd:element>

 *  	  <xsd:element minOccurs="0" name="src" type="xsd:string">

 *  		<xsd:annotation>

 *  		  <xsd:documentation>

 *  			Source of data. Included to give user some idea of reliability and accuracy of data.

 *  		  </xsd:documentation>

 *  		</xsd:annotation>

 *  	  </xsd:element>

 *        <xsd:element maxOccurs="unbounded" minOccurs="0" name="link" type="linkType">

 *  		<xsd:annotation>

 *  		  <xsd:documentation>

 *  			Links to external information about track.

 *  		  </xsd:documentation>

 *  		</xsd:annotation>

 *  	  </xsd:element>

 *  	  <xsd:element minOccurs="0" name="number" type="xsd:nonNegativeInteger">

 *  		<xsd:annotation>

 *  		  <xsd:documentation>

 *  			GPS track number.

 *  		  </xsd:documentation>

 *  		</xsd:annotation>

 *  	  </xsd:element>

 *  	  <xsd:element minOccurs="0" name="type" type="xsd:string">

 *  		<xsd:annotation>

 *  		  <xsd:documentation>

 *  			Type (classification) of track.

 *  		  </xsd:documentation>

 *  		</xsd:annotation>

 *  	  </xsd:element>

 *

 *  	 <xsd:element minOccurs="0" name="extensions" type="extensionsType">

 *        <xsd:annotation>

 *         <xsd:documentation>

 *  		You can add extend GPX by adding your own elements from another schema here.

 *  	   </xsd:documentation>

 *  	  </xsd:annotation>

 *  	 </xsd:element>

 *

 *       <xsd:element maxOccurs="unbounded" minOccurs="0" name="trkseg" type="trksegType">

 *        <xsd:annotation>

 *         <xsd:documentation>

 *  		A Track Segment holds a list of Track Points which are logically connected in order. To represent a single GPS track where GPS reception was lost, or the GPS receiver was turned off, start a new Track Segment for each continuous span of track data.

 *  	   </xsd:documentation>

 *  	  </xsd:annotation>

 *  	 </xsd:element>

 *      </xsd:sequence>

 *    </xsd:complexType>
 *
 *
 *

 *

 *
 * @generated
 */
public class TrkTypeBinding extends AbstractComplexBinding {

    public static final String FEATURE_TYPE_NAME_TRACKS = "tracks";

    private static final String ATTR_NAME_GEOM = "geom";

    private GeometryFactory gf;
    private SimpleFeatureType trkFt;
    private SimpleFeatureBuilder fb;

    public TrkTypeBinding(GeometryFactory gf) {
        this.gf = gf;
        SimpleFeatureTypeBuilder sftb = new SimpleFeatureTypeBuilder();
        sftb.setName(FEATURE_TYPE_NAME_TRACKS);
        sftb.setDefaultGeometry(ATTR_NAME_GEOM);
        sftb.add(ATTR_NAME_GEOM, MultiLineString.class, DefaultGeographicCRS.WGS84);
        for (GPXField field : GPXField.getCachedValues()) {
            field.addBinding(sftb);
        }
        this.trkFt = sftb.buildFeatureType();
        this.fb = new SimpleFeatureBuilder(trkFt);
    }

    /**
     * @generated
     */
    public QName getTarget() {
        return GPX10.trkType;
    }

    /**
     *
     *
     *
     * @generated modifiable
     */
    public Class getType() {
        return Feature.class;
    }

    /**
     *
     *
     *
     * @generated modifiable
     */
    public Object parse(ElementInstance instance, Node node, Object value) throws Exception {
        List<LineString> trackSegments = node.getChildValues(LineString.class);
        MultiLineString geom = gf.createMultiLineString(trackSegments.toArray(new LineString[0]));
        fb.reset();
        fb.set(ATTR_NAME_GEOM, geom);
        for (GPXField field : GPXField.getCachedValues()) {
            field.parse(fb, node);
        }
        return fb.buildFeature(null);
    }

}


text:
/* jslint bitwise:true */

"use strict";

var MOD = 65521;

// This is a clean-room implementation of adler32 designed for detecting
// if markup is not what we expect it to be. It does not need to be
// cryptographically strong, only reasonable good at detecting if markup
// generated on the server is different than that on the client.
function adler32(data) {
  var a = 1;
  var b = 0;
  for (var i = 0; i < data.length; i++) {
    a = (a + data.charCodeAt(i)) % MOD;
    b = (b + a) % MOD;
  }
  return a | (b << 16);
}

module.exports = adler32;


text:
using System;
using System.Collections.Generic;

namespace Jcq.IcqProtocol.DataTypes
{
    public class Snac0909 : Snac
    {
        public Snac0909() : base(0x9, 0x9)
        {
        }

        public int ErrorCode { get; set; }

        public TlvErrorSubCode ErrorSubCode { get; } = new TlvErrorSubCode();

        public TlvErrorDescriptionUrl ErrorDescriptionUrl { get; } = new TlvErrorDescriptionUrl();

        public override int CalculateDataSize()
        {
            throw new NotImplementedException();
        }

        public override List<byte> Serialize()
        {
            throw new NotImplementedException();
        }

        public override void Deserialize(List<byte> data)
        {
            base.Deserialize(data);

            int index = SizeFixPart;

            ErrorCode = ByteConverter.ToUInt16(data.GetRange(index, 2));
            index += 2;

            while (index < data.Count)
            {
                TlvDescriptor desc = TlvDescriptor.GetDescriptor(index, data);

                switch (desc.TypeId)
                {
                    case 0x8:
                        ErrorSubCode.Deserialize(data.GetRange(index, desc.TotalSize));
                        break;
                    case 0x4:
                        ErrorDescriptionUrl.Deserialize(data.GetRange(index, desc.TotalSize));
                        break;
                }

                index += desc.TotalSize;
            }

            TotalSize = index;
        }
    }
}


text:
(function(/*! Stitch !*/) {
  if (!this.require) {
    var modules = {}, cache = {};
    var require = function(name, root) {
      var path = expand(root, name), indexPath = expand(path, './index'), module, fn;
      module   = cache[path] || cache[indexPath];
      if (module) {
        return module;
      } else if (fn = modules[path] || modules[path = indexPath]) {
        module = {id: path, exports: {}};
        cache[path] = module.exports;
        fn(module.exports, function(name) {
          return require(name, dirname(path));
        }, module);
        return cache[path] = module.exports;
      } else {
        throw 'module ' + name + ' not found';
      }
    };
    var expand = function(root, name) {
      var results = [], parts, part;
      // If path is relative
      if (/^\.\.?(\/|$)/.test(name)) {
        parts = [root, name].join('/').split('/');
      } else {
        parts = name.split('/');
      }
      for (var i = 0, length = parts.length; i < length; i++) {
        part = parts[i];
        if (part == '..') {
          results.pop();
        } else if (part != '.' && part != '') {
          results.push(part);
        }
      }
      return results.join('/');
    };
    var dirname = function(path) {
      return path.split('/').slice(0, -1).join('/');
    };
    this.require = function(name) {
      return require(name, '');
    };
    this.require.define = function(bundle) {
      for (var key in bundle) {
        modules[key] = bundle[key];
      }
    };
    this.require.modules = modules;
    this.require.cache   = cache;
  }
  return this.require.define;
}).call(this)({
  "models/orm": function(exports, require, module) {
module.exports = {orm: true};

window.ormCount = window.ormCount || 0;
window.ormCount += 1;
}, "models/user": function(exports, require, module) {
var ORM = require('models/orm');

var User = function(name){
  this.name = name;
};

User.ORM = ORM;

module.exports = User;
}, "models/person": function(exports, require, module) {
var ORM = require('models/orm');
}, "index": function(exports, require, module) {
require('models/user');
require('models/person');

// Do some stuff
}
});


text:
enum class CExprErrorType {
  NONE                          = 0,
  ZERO_TO_NEG_POWER_UNDEF       = 1,
  POWER_FAILED                  = 2,
  REAL_TOO_BIG_FOR_INTEGER      = 3,
  NAN_OPERATION                 = 4,
  NON_INTEGER_POWER_OF_NEGATIVE = 5,
  DIVIDE_BY_ZERO                = 6
};

class CExprErrorData {
 public:
  CExprErrorData() { }

  void setLastError(const std::string &message) {
    if (message == "") {
      lastError_ = "";

      hasError_ = false;

      return;
    }

    if (hasError_)
      return;

    lastError_ = message;

    hasError_ = true;
  }

  bool isError() const {
    return hasError_;
  }

  const std::string &getLastError() const {
    return lastError_;
  }

 private:
  bool        hasError_ { false };
  std::string lastError_;
};

#endif


text:
import posthtml from 'posthtml';
import {URL} from 'url';
import {isJsonScript, isValidScript} from '../utilities/cdn-tag';
import {OptionSet} from '../utilities/option-set';

function sxgTransform(node: posthtml.Node, options: OptionSet = {}): posthtml.Node {
  // Make sure that isJsonScript is used before `isValidScript`. We bail out
  // early if the ScriptNode is of type="application/json" since it wouldn't
  // have any src url to modify.
  if (isJsonScript(node)) {
    return node;
  }

  if (!isValidScript(node)) {
    return node;
  }

  if (options.minified) {
    const src = node.attrs.src;
    node.attrs.src = src.replace('.js', '.sxg.js');
  } else {
    const url = new URL(node.attrs.src);
    url.searchParams.append('f', 'sxg');
    node.attrs.src = url.toString();
  }

  return node;
}

/**
 * Returns a function that will transform script node sources into their sxg counterparts.
 * @param options
 */
export default function(options: OptionSet = {}): (tree: posthtml.Node) => void {
  return function(tree: posthtml.Node) {
    tree.match({tag: 'script'}, (script) => {
      return sxgTransform(script, options);
    });
  }
}


text:
namespace spvtools {
namespace opt {

// See optimizer.hpp for documentation.
class SpreadVolatileSemantics : public Pass {
 public:
  SpreadVolatileSemantics() {}

  const char* name() const override { return "spread-volatile-semantics"; }

  Status Process() override;

  IRContext::Analysis GetPreservedAnalyses() override {
    return IRContext::kAnalysisDefUse | IRContext::kAnalysisDecorations |
           IRContext::kAnalysisInstrToBlockMapping;
  }

 private:
  // Iterates interface variables and spreads the Volatile semantics if it has
  // load instructions for the Volatile semantics.
  Pass::Status SpreadVolatileSemanticsToVariables(
      const bool is_vk_memory_model_enabled);

  // Returns whether |var_id| is the result id of a target builtin variable for
  // the volatile semantics for |execution_model| based on the Vulkan spec
  // VUID-StandaloneSpirv-VulkanMemoryModel-04678 or
  // VUID-StandaloneSpirv-VulkanMemoryModel-04679.
  bool IsTargetForVolatileSemantics(uint32_t var_id,
                                    SpvExecutionModel execution_model);

  // Collects interface variables that need the volatile semantics.
  // |is_vk_memory_model_enabled| is true if VulkanMemoryModel capability is
  // enabled.
  void CollectTargetsForVolatileSemantics(
      const bool is_vk_memory_model_enabled);

  // Reports an error if an interface variable is used by two entry points and
  // it needs the Volatile decoration for one but not for another. Returns true
  // if the error must be reported.
  bool HasInterfaceInConflictOfVolatileSemantics();

  // Returns whether the variable whose result is |var_id| is used by a
  // non-volatile load or a pointer to it is used by a non-volatile load in
  // |entry_point| or not.
  bool IsTargetUsedByNonVolatileLoadInEntryPoint(uint32_t var_id,
                                                 Instruction* entry_point);

  // Visits load instructions of pointers to variable whose result id is
  // |var_id| if the load instructions are in entry points whose
  // function id is one of |entry_function_ids|. |handle_load| is a function to
  // do some actions for the load instructions. Finishes the traversal and
  // returns false if |handle_load| returns false for a load instruction.
  // Otherwise, returns true after running |handle_load| for all the load
  // instructions.
  bool VisitLoadsOfPointersToVariableInEntries(
      uint32_t var_id, const std::function<bool(Instruction*)>& handle_load,
      const std::unordered_set<uint32_t>& entry_function_ids);

  // Sets Memory Operands of OpLoad instructions that load |var| or pointers
  // of |var| as Volatile if the function id of the OpLoad instruction is
  // included in |entry_function_ids|.
  void SetVolatileForLoadsInEntries(
      Instruction* var, const std::unordered_set<uint32_t>& entry_function_ids);

  // Adds OpDecorate Volatile for |var| if it does not exist.
  void DecorateVarWithVolatile(Instruction* var);

  // Returns a set of entry function ids to spread the volatile semantics for
  // the variable with the result id |var_id|.
  std::unordered_set<uint32_t> EntryFunctionsToSpreadVolatileSemanticsForVar(
      uint32_t var_id) {
    auto itr = var_ids_to_entry_fn_for_volatile_semantics_.find(var_id);
    if (itr == var_ids_to_entry_fn_for_volatile_semantics_.end()) return {};
    return itr->second;
  }

  // Specifies that we have to spread the volatile semantics for the
  // variable with the result id |var_id| for the entry point |entry_point|.
  void MarkVolatileSemanticsForVariable(uint32_t var_id,
                                        Instruction* entry_point);

  // Result ids of variables to entry function ids for the volatile semantics
  // spread.
  std::unordered_map<uint32_t, std::unordered_set<uint32_t>>
      var_ids_to_entry_fn_for_volatile_semantics_;
};

}  // namespace opt
}  // namespace spvtools

#endif  // SOURCE_OPT_SPREAD_VOLATILE_SEMANTICS_H_


text:
var adapter = require('../../lib/adapter'),
    should = require('should'),
    support = require('./support/bootstrap');

describe('adapter', function() {

  /**
   * Setup and Teardown
   */

  before(function(done) {
    support.Setup('test_create', done);
  });

  after(function(done) {
    support.Teardown('test_create', done);
  });

  // Attributes for the test table
  var attributes = {
    field_1: 'foo',
    field_2: 'bar'
  };

  /**
   * CREATE
   *
   * Insert a row into a table
   */

  describe('.create()', function() {

    // Insert a record
    it('should insert a single record', function(done) {
      adapter.create('test_create', attributes, function(err, result) {

        // Check record was actually inserted
        support.Client(function(err, client, close) {
          client.query('SELECT * FROM "test_create"', function(err, result) {

            // Test 1 row is returned
            result.rows.length.should.eql(1);

            // close client
            close();

            done();
          });
        });
      });
    });

    // Create Auto-Incremented ID
    it('should create an auto-incremented ID field', function(done) {
      adapter.create('test_create', attributes, function(err, result) {

        // Should have an ID of 2
        result.id.should.eql(2);

        done();
      });
    });

    it('should keep case', function(done) {
      var attributes = {
        field_1: 'Foo',
        field_2: 'bAr'
      };

      adapter.create('test_create', attributes, function(err, result) {

        result.field_1.should.eql('Foo');
        result.field_2.should.eql('bAr');

        done();
      });
    });

  });
});


text:
class TrayIcon : public QObject {
	Q_OBJECT

	private:
		QSystemTrayIcon *trayIcon;

	public:
		QSettings *settings;
		MainWindow *settings_window;

		explicit TrayIcon(QObject *parent = 0);

		void show();
		void notify(QString title, QString message);
		void populateMenu(QHash<QString, float> exchange);

	signals:
		void manualUpdateTriggered();

	public slots:
		void openSettings();
		void updateAll();
};

#endif // TRAYICON_H


text:
'use strict';

module.exports = {
    rules: {
        // Enforce all defaultProps have a corresponding non-required PropType
        'react/default-props-match-prop-types': 'error',
        // Forbid foreign propTypes
        'react/forbid-foreign-prop-types': 'error',
        // Enforce boolean attributes notation in JSX
        'react/jsx-boolean-value': ['error', 'never'],
        // Validate closing bracket location in JSX
        'react/jsx-closing-bracket-location': ['error', 'after-props'],
        // Enforce or disallow spaces inside of curly braces in JSX attributes
        'react/jsx-curly-spacing': ['error', { when: 'always', children: true }],
        // Enforce or disallow spaces around equal signs in JSX attributes
        'react/jsx-equals-spacing': ['error', 'never'],
        // Restrict file extensions that may contain JSX
        'react/jsx-filename-extension': ['error', { extensions: ['.js'] }],
        // Enforce shorthand or standard form for React fragments
        'react/jsx-fragments': ['warn', 'syntax'],
        // Enforce event handler naming conventions in JSX
        'react/jsx-handler-names': ['error', {
            eventHandlerPrefix: 'handle',
            eventHandlerPropPrefix: 'on',
        }],
        // Validate props indentation in JSX
        'react/jsx-indent-props': ['error', 4],
        // Validate JSX indentation
        'react/jsx-indent': ['error', 4],
        // Detect missing key prop
        'react/jsx-key': 'warn',
        // No .bind() or Arrow Functions in JSX Props
        'react/jsx-no-bind': 'warn',
        // Prevent comments from being inserted as text nodes
        'react/jsx-no-comment-textnodes': 'error',
        // Prevent duplicate props in JSX
        'react/jsx-no-duplicate-props': 'error',
        // Prevent usage of unsafe target='_blank'
        'react/jsx-no-target-blank': ['warn', { allowReferrer: true }],
        // Disallow undeclared variables in JSX
        'react/jsx-no-undef': 'error',
        // Enforce PasalCase for user-defined JSX components
        'react/jsx-pascal-case': 'error',
        // Enforce or forbid spaces before the closing bracket of self-closing JSX elements
        'react/jsx-tag-spacing': ['error', {
            closingSlash: 'never',
            beforeClosing: 'never',
            beforeSelfClosing: 'always',
            afterOpening: 'never',
        }],
        // Prevent React to be incorrectly marked as unused
        'react/jsx-uses-react': 'error',
        // Prevent variables used in JSX to be incorrectly marked as unused
        'react/jsx-uses-vars': 'error',
        // Prevent missing parentheses around multilines JSX
        'react/jsx-wrap-multilines': ['error', {
            declaration: true,
            assignment: true,
            return: true,
        }],
        // Prevent passing of children as props
        'react/no-children-prop': 'error',
        // Prevent problem with children and props.dangerouslySetInnerHTML
        'react/no-danger-with-children': 'error',
        // Prevent usage of deprecated methods
        'react/no-deprecated': 'warn',
        // Prevent direct mutation of this.state
        'react/no-direct-mutation-state': 'error',
        // Prevent usage of isMounted
        'react/no-is-mounted': 'error',
        // Prevent usage of the return value of React.render
        'react/no-render-return-value': 'error',
        // Prevent using string references
        'react/no-string-refs': 'error',
        // Prevent invalid characters from appearing in markup
        'react/no-unescaped-entities': 'error',
        // Prevent usage of unknown DOM property
        'react/no-unknown-property': 'error',
        // Require ES6 class declarations over React.createClass
        'react/prefer-es6-class': ['error', 'always'],
        // Prevent missing props validation in a React component definition
        'react/prop-types': 'error',
        // Prevent missing React when using JSX
        'react/react-in-jsx-scope': 'error',
        // Enforce ES5 or ES6 class for returning value in render function
        'react/require-render-return': 'error',
        // Prevent extra closing tags for components without children
        'react/self-closing-comp': 'error',
        // Enforce component methods order
        'react/sort-comp': ['error', {
            order: [
                'static-variables',
                'static-methods',
                'static-lifecycle',
                'instance-variables',
                'lifecycle',
                'render',
                '/^render.+$/',
                'everything-else',
                '/^handle.+$/',
            ],
            groups: {
                'static-lifecycle': [
                    'displayName',
                    'propTypes',
                    'contextTypes',
                    'childContextTypes',
                    'defaultProps',
                    'getDerivedStateFromProps',
                ],
                lifecycle: [
                    'mixins',
                    'statics',
                    'constructor',
                    'getDefaultProps',
                    'state',
                    'getInitialState',
                    'getChildContext',
                    'componentWillMount',
                    'UNSAFE_componentWillMount',
                    'componentDidMount',
                    'componentWillReceiveProps',
                    'UNSAFE_componentWillReceiveProps',
                    'shouldComponentUpdate',
                    'componentWillUpdate',
                    'UNSAFE_componentWillUpdate',
                    'getSnapshotBeforeUpdate',
                    'componentDidUpdate',
                    'componentDidCatch',
                    'componentWillUnmount',
                ],
            },
        }],
        // Enforce style prop value being an object
        'react/style-prop-object': 'error',
        // Prevent void DOM elements (e.g. <img />, <br />) from receiving children
        'react/void-dom-elements-no-children': 'error',
    },
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Int. J. Mycol. Lichenol. 2(1): 77 (1985)

#### Original name
Strattonia dissimilis Barrasa, Soláns & G. Moreno

### Remarks
null


text:
'use strict';

var _joi = require('joi');

var _joi2 = _interopRequireDefault(_joi);

var _handlers = require('../handlers');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

module.exports = [
// News Posts
{
	'method': 'GET',
	'path': '/api/newsPosts/{id}',
	'config': {
		'tags': ['api'],
		'description': 'Get one newsPost by id',
		'notes': 'Get one newsPost by id',
		'validate': {
			'params': {
				'id': _joi2.default.number().required()
			}
		}
	},
	'handler': _handlers.newsPosts.get
}, {
	'method': 'GET',
	'path': '/api/newsPosts',
	'config': {
		'tags': ['api'],
		'description': 'Get all newsPosts',
		'notes': 'Get all newsPosts'
	},
	'handler': _handlers.newsPosts.getAll
}, {
	'method': 'POST',
	'path': '/api/newsPosts',
	'config': {
		'tags': ['api'],
		'description': 'Add a new newsPost',
		'notes': 'Add a new newsPost',
		'auth': {
			'strategy': 'jsonWebToken',
			'scope': ['newsContributor', 'systemAdmin']
		},
		'validate': {
			'payload': {
				'Files': _joi2.default.optional(),
				'UserId': _joi2.default.number().required(),
				'FactionId': _joi2.default.optional(),
				'GameSystemId': _joi2.default.optional(),
				'ManufacturerId': _joi2.default.optional(),
				'title': _joi2.default.string().required(),
				'callout': _joi2.default.string().required(),
				'body': _joi2.default.string().required(),
				'published': _joi2.default.boolean().required(),
				'featured': _joi2.default.boolean().required(),
				'tags': _joi2.default.optional(),
				'manufacturerId': _joi2.default.optional(),
				'gameSystemId': _joi2.default.optional(),
				'category': _joi2.default.string().required()
			}
		}
	},
	'handler': _handlers.newsPosts.create
}, {
	'method': 'PUT',
	'path': '/api/newsPosts/{id}',
	'config': {
		'tags': ['api'],
		'description': 'Update a newsPost by id',
		'notes': 'Update a newsPost by id',
		'auth': {
			'strategy': 'jsonWebToken',
			'scope': ['newsContributor', 'systemAdmin']
		},
		'validate': {
			'params': {
				'id': _joi2.default.number().required()
			},
			'payload': {
				'id': _joi2.default.optional(),
				'createdAt': _joi2.default.optional(),
				'updatedAt': _joi2.default.optional(),
				'ManufacturerId': _joi2.default.optional(),
				'FactionId': _joi2.default.optional(),
				'GameSystemId': _joi2.default.optional(),
				'User': _joi2.default.optional(),
				'Files': _joi2.default.optional(),
				'UserId': _joi2.default.number().required(),
				'title': _joi2.default.string().required(),
				'callout': _joi2.default.string().required(),
				'body': _joi2.default.string().required(),
				'published': _joi2.default.boolean().required(),
				'featured': _joi2.default.boolean().required(),
				'tags': _joi2.default.optional(),
				'manufacturerId': _joi2.default.optional(),
				'gameSystemId': _joi2.default.optional(),
				'category': _joi2.default.string().required()
			}
		}
	},
	'handler': _handlers.newsPosts.update
}, {
	'method': 'POST',
	'path': '/api/search/newsPosts',
	'config': {
		'tags': ['api'],
		'description': 'Return News Post search results',
		'notes': 'Return News Post search results',
		'validate': {
			'payload': {
				'maxResults': _joi2.default.optional(),
				'searchQuery': _joi2.default.optional(),
				'orderBy': _joi2.default.string().required(),
				'searchBy': _joi2.default.optional(),
				'pageNumber': _joi2.default.number().required(),
				'pageSize': _joi2.default.optional(),
				'published': _joi2.default.optional()
			}
		}
	},
	'handler': _handlers.newsPosts.search
}, {
	'method': 'DELETE',
	'path': '/api/newsPosts/{id}',
	'config': {
		'tags': ['api'],
		'description': 'Delete a newsPost by id',
		'notes': 'Delete a newsPost by id',
		'auth': {
			'strategy': 'jsonWebToken',
			'scope': ['newsContributor', 'systemAdmin']
		},
		'validate': {
			'params': {
				'id': _joi2.default.number().required()
			}
		}
	},
	'handler': _handlers.newsPosts.delete
}];


text:
(function(ns){
    'use strict';

    //实现自己的对象跟踪系统
    var lobby = {};
    if (typeof Object.objectId !== 'function') {
        Object.objectId = function(){
            var generateId = function(){
                var id = 0;
                return function(){
                    return id++;
                };
            }();
            return function(obj){
                if (obj != null) {
                    if (!obj.hasOwnProperty("__id")) {
                        obj.__id = generateId();
                    }
                    return obj.__id;
                } else {
                    return null;
                }
            };
        }();
    }

    if (typeof Object.objectName !== 'function') {
        Object.objectName = function(o){
            var id = Object.objectId(o);
            return lobby[id] || id;
        };
    }

    if (typeof Object.traceObj !== 'function') {
        Object.traceObj = function(name, obj){
            lobby[Object.objectId(obj)] = name;
        };
        Object.traceObj("lobby", lobby);
        Object.traceObj("Object", Object);
        Object.traceObj("Object.prototype", Object.prototype);
        Object.traceObj("Function", Function);
        Object.traceObj("Function.prototype", Function.prototype);
        Object.traceObj("Array", Array);
        Object.traceObj("Array.prototype", Array.prototype);
        Object.traceObj("RegExp", RegExp);
        Object.traceObj("RegExp.prototype", RegExp.prototype);
        Object.traceObj("String", String);
        Object.traceObj("String.prototype", String.prototype);
        Object.traceObj("Number", Number);
        Object.traceObj("Number.prototype", Number.prototype);
        Object.traceObj("Date", Date);
        Object.traceObj("Date.prototype", Date.prototype);
        Object.traceObj("Error", Error);
        Object.traceObj("Error.prototype", Error.prototype);
        Object.traceObj("Boolean", Boolean);
        Object.traceObj("Boolean.prototype", Boolean.prototype);
        Object.traceObj("Math", Math);
        Object.traceObj("Math.prototype", Math.prototype);
    }

    if (typeof Object.beget !== 'function') {
        Object.beget = function(o){
            var F = function(){};
            F.prototype = o;
            return new F();
        };
    }

    if (typeof Object.parents !== 'function') {
        Object.parents = function(obj){
            var parents = [];
            var parent = obj;
            do {
                parents.push(parent);
                parent = Object.getPrototypeOf(parent);
            } while(parent);
            return parents;
        };
    }

    ns.ls = function(){
        console.log(lobby);
    };

    ns.assertSame = function(actual, expect){
        var actualId = Object.objectId(actual), expectedId = Object.objectId(expect);
        if (actualId !== expectedId){
            throw new Error("expect: " + Object.objectName(expect) + ", but actual was: " + Object.objectName(actual));
        }
    };

})(GLOBAL);


text:
import json
import os

# Import Bottle
import bottle
from bottle import jinja2_template as template
from bottle import response, run, static_file
# Import Bottle Extensions
from bottle_sqlalchemy import SQLAlchemyPlugin
# Import SQLAlchemy
from sqlalchemy import Column, Integer, String, Text, create_engine
from sqlalchemy.ext.declarative import declarative_base

# Define dirs
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, 'static')

# App Config
bottle.TEMPLATE_PATH.insert(0, os.path.join(BASE_DIR, 'templates'))
bottle.debug(True)  # Don't forget switch this to `False` on production!

# SQLite Database config
Base = declarative_base()
db_engine = create_engine('sqlite:///' + os.path.join(BASE_DIR, 'articles.db'))

# Starting App
app = bottle.default_app()

# Install Bottle plugins
app.install(SQLAlchemyPlugin(db_engine, keyword='sqlite_db'))

# Articles Database class
class ArticlesDB(Base):
    __tablename__ = 'articles'
    id = Column(Integer, primary_key=True)
    title = Column(String(255), nullable=False)
    description = Column(Text())

# API routes
@app.get('/api/articles/')
def get_all_articles(sqlite_db):
    """Get all Articles from Database"""
    articles = []
    articles_query = sqlite_db.query(ArticlesDB).all()

    for i in articles_query:
        articles.append({
            'title': i.title,
            'description': i.description
        })

    response.headers['Content-Type'] = 'application/json'
    return json.dumps({'data': articles})

# Index page route
@app.get('/')
def show_index():
    """Show Index page"""
    return template('index')

# Static files route
@app.get('/static/<filename:path>')
def get_static_files(filename):
    """Get Static files"""
    return static_file(filename, root=STATIC_DIR)

# Run server
run(app, server='auto', host='localhost', port=8080, reloader=True)


text:
Graph implementation are header-only files in boost graph module.

##Overlapping Community Detection Algorithms
- Cis : Connected Iterative Scan
- Demon: Democratically Estimate of Modular Organization of Network
- HRGrow: Heat-Kernel Graph Diffusion

##Sequential Implementation

Algorithm | Header | Definition
--- | --- | ---
CIs | [cis_sequential_algorithm.h](sequential/cis_sequential_algorithm.h) | [cis_sequential_algorithm.cpp](sequential/cis_sequential_algorithm.cpp)
Demon | [demon_sequential_algorithm.h](sequential/demon_sequential_algorithm.h) | [demon_seqential_algorithm.cpp](sequential/demon_seqential_algorithm.cpp)
HRGrow | [hk_grow_sequential_algorithm.h](sequential/hk_grow_sequential_algorithm.h) | [hk_grow_sequential_algorithm.cpp](sequential/hk_grow_sequential_algorithm.cpp)


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta viewport="width=device-width, initial-scale=1">
	<title>hi</title>

There are {{meetups.length}} meetups

		<form ng-submit="createMeetup()">
			<input type="text" placeholder="meetup name" ng-model="meetupName">
			<button type="submit">add</button>
		</form>


text:
@echo off & setlocal enableextensions enabledelayedexpansion
::
:: tc.bat - compile & run tests (clang).
::

set      unit=string_view
set unit_file=string-view

:: if no std is given, use c++14

set std=%1
if "%std%"=="" set std=c++14

set  clang=clang

call :CompilerVersion version
echo %clang% %version%: %std%

set UCAP=%unit%
call :toupper UCAP

set unit_select=-D%unit_prfx%_CONFIG_SELECT_%UCAP%=%unit_prfx%_%UCAP%_DEFAULT
::set unit_select=-D%unit_prfx%_CONFIG_SELECT_%UCAP%=%unit_prfx%_%UCAP%_NONSTD
::set unit_select=-D%unit_prfx%_CONFIG_SELECT_%UCAP%=%unit_prfx%_%UCAP%_STD

set unit_config=^
    -Dnssv_CONFIG_STD_SV_OPERATOR=1 ^
    -Dnssv_CONFIG_USR_SV_OPERATOR=1 ^
    -Dnssv_CONFIG_CONFIRMS_COMPILATION_ERRORS=0 ^
    -Dnssv_STRING_VIEW_HEADER=\"nonstd/string_view.hpp\"

rem -flto / -fwhole-program
set  optflags=-O2
set warnflags=-Wall -Wextra -Wpedantic -Weverything -Wshadow -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-missing-noreturn -Wno-documentation-unknown-command -Wno-documentation-deprecated-sync -Wno-documentation -Wno-weak-vtables -Wno-missing-prototypes -Wno-missing-variable-declarations -Wno-exit-time-destructors -Wno-global-constructors

"%clang%" -m32 -std=%std% %optflags% %warnflags% %unit_select% %unit_config% -fms-compatibility-version=19.00 -isystem "%VCInstallDir%include" -isystem "%WindowsSdkDir_71A%include" -isystem lest -I../include -I. -o %unit_file%-main.t.exe %unit_file%-main.t.cpp %unit_file%.t.cpp && %unit_file%-main.t.exe
endlocal & goto :EOF

:: subroutines:

:CompilerVersion  version
echo off & setlocal enableextensions
set tmpprogram=_getcompilerversion.tmp
set tmpsource=%tmpprogram%.c

echo #include ^<stdio.h^>     > %tmpsource%
echo int main(){printf("%%d.%%d.%%d\n",__clang_major__,__clang_minor__,__clang_patchlevel__);} >> %tmpsource%

"%clang%" -m32 -o %tmpprogram% %tmpsource% >nul
for /f %%x in ('%tmpprogram%') do set version=%%x
del %tmpprogram%.* >nul
endlocal & set %1=%version%& goto :EOF

:: toupper; makes use of the fact that string
:: replacement (via SET) is not case sensitive
:toupper
for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
goto :EOF


text:
package versioning.java.files;

public interface TestBChild extends TestB {
    public String getBar();

}


text:
* 自定义表名称
* 自定义列名称
* 自定义外联列名称
* 自定义多对多联结表名称
* 创建自己的`NamingStrategy`

## 创建自己的`NamingStrategy`

如果在`ormconfig`文件中定义了连接选项,
那么你可以简单地使用它并按照以下方式覆盖它:

```typescript
import {createConnection, getConnectionOptions} from "typeorm";
import {MyNamingStrategy} from "./logger/MyNamingStrategy";

//getConnectionOptions将读取ormconfig文件中的选项并将其返回到connectionOptions对象中,然后你只需向其附加其他属性
getConnectionOptions().then(connectionOptions => {
    return createConnection(Object.assign(connectionOptions, {
        namingStrategy: new MyNamingStrategy()
    }))
});
```

命名策略是一个需要改变的主题。
一旦API稳定下来,就会获得详细的文档。


text:
const fs = require('fs');
const path = require('path');
const handlebars = require('handlebars').create();
const annotator = require('./annotator');
const helpers = require('./helpers');
const templateFor = function(name) {
    return handlebars.compile(
        fs.readFileSync(
            path.resolve(__dirname, 'templates', name + '.txt'),
            'utf8'
        )
    );
};
const headerTemplate = templateFor('head');
const footerTemplate = templateFor('foot');
const detailTemplate = handlebars.compile(
    [
        '
',
        '{{#show_lines}}{{maxLines}}{{/show_lines}}	',
        '{{#show_line_execution_counts lineCoverage}}{{maxLines}}{{/show_line_execution_counts}}	',
        '
{{#show_code annotatedCode}}{{/show_code}}
	',
        '
\n'
    ].join('')
);
const summaryTableHeader = [
    '
',
    '
',
    '
',
    '
',
    '   File	',
    '   	',
    '   Statements	',
    '   	',
    '   Branches	',
    '   	',
    '   Functions	',
    '   	',
    '   Lines	',
    '   	',
    '
',
    '
',
    '
'
].join('\n');
const summaryLineTemplate = handlebars.compile(
    [
        '
',
        '{{file}}	',
        '
{{#show_picture}}{{metrics.statements.pct}}{{/show_picture}}
	',
        '{{metrics.statements.pct}}%	',
        '{{metrics.statements.covered}}/{{metrics.statements.total}}	',
        '{{metrics.branches.pct}}%	',
        '{{metrics.branches.covered}}/{{metrics.branches.total}}	',
        '{{metrics.functions.pct}}%	',
        '{{metrics.functions.covered}}/{{metrics.functions.total}}	',
        '{{metrics.lines.pct}}%	',
        '{{metrics.lines.covered}}/{{metrics.lines.total}}	',
        '
\n'
    ].join('\n\t')
);
const summaryTableFooter = ['
', '
', '
'].join('\n');
const emptyClasses = {
    statements: 'empty',
    lines: 'empty',
    functions: 'empty',
    branches: 'empty'
};

helpers.registerHelpers(handlebars);

const standardLinkMapper = {
    getPath(node) {
        if (typeof node === 'string') {
            return node;
        }
        let filePath = node.getQualifiedName();
        if (node.isSummary()) {
            if (filePath !== '') {
                filePath += '/index.html';
            } else {
                filePath = 'index.html';
            }
        } else {
            filePath += '.html';
        }
        return filePath;
    },

    relativePath(source, target) {
        const targetPath = this.getPath(target);
        const sourcePath = path.dirname(this.getPath(source));
        return path.relative(sourcePath, targetPath);
    },

    assetPath(node, name) {
        return this.relativePath(this.getPath(node), name);
    }
};

function fixPct(metrics) {
    Object.keys(emptyClasses).forEach(key => {
        metrics[key].pct = 0;
    });
    return metrics;
}

class HtmlReport {
    constructor(opts) {
        this.verbose = opts.verbose;
        this.linkMapper = opts.linkMapper || standardLinkMapper;
        this.subdir = opts.subdir || '';
        this.date = Date();
        this.skipEmpty = opts.skipEmpty;
    }

    getBreadcrumbHtml(node) {
        let parent = node.getParent();
        const nodePath = [];

        while (parent) {
            nodePath.push(parent);
            parent = parent.getParent();
        }

        const linkPath = nodePath.map(ancestor => {
            const target = this.linkMapper.relativePath(node, ancestor);
            const name = ancestor.getRelativeName() || 'All files';
            return '' + name + '';
        });

        linkPath.reverse();
        return linkPath.length > 0
            ? linkPath.join(' / ') + ' ' + node.getRelativeName()
            : 'All files';
    }

    fillTemplate(node, templateData, context) {
        const linkMapper = this.linkMapper;
        const summary = node.getCoverageSummary();
        templateData.entity = node.getQualifiedName() || 'All files';
        templateData.metrics = summary;
        templateData.reportClass = context.classForPercent(
            'statements',
            summary.statements.pct
        );
        templateData.pathHtml = this.getBreadcrumbHtml(node);
        templateData.base = {
            css: linkMapper.assetPath(node, 'base.css')
        };
        templateData.sorter = {
            js: linkMapper.assetPath(node, 'sorter.js'),
            image: linkMapper.assetPath(node, 'sort-arrow-sprite.png')
        };
        templateData.blockNavigation = {
            js: linkMapper.assetPath(node, 'block-navigation.js')
        };
        templateData.prettify = {
            js: linkMapper.assetPath(node, 'prettify.js'),
            css: linkMapper.assetPath(node, 'prettify.css')
        };
    }

    getTemplateData() {
        return { datetime: this.date };
    }

    getWriter(context) {
        if (!this.subdir) {
            return context.writer;
        }
        return context.writer.writerForDir(this.subdir);
    }

    onStart(root, context) {
        const assetHeaders = {
            '.js': '/* eslint-disable */\n'
        };

        ['.', 'vendor'].forEach(subdir => {
            const writer = this.getWriter(context);
            const srcDir = path.resolve(__dirname, 'assets', subdir);
            fs.readdirSync(srcDir).forEach(f => {
                const resolvedSource = path.resolve(srcDir, f);
                const resolvedDestination = '.';
                const stat = fs.statSync(resolvedSource);
                let dest;

                if (stat.isFile()) {
                    dest = resolvedDestination + '/' + f;
                    if (this.verbose) {
                        console.log('Write asset: ' + dest);
                    }
                    writer.copyFile(
                        resolvedSource,
                        dest,
                        assetHeaders[path.extname(f)]
                    );
                }
            });
        });
    }

    onSummary(node, context) {
        const linkMapper = this.linkMapper;
        const templateData = this.getTemplateData();
        const children = node.getChildren();
        const skipEmpty = this.skipEmpty;

        this.fillTemplate(node, templateData, context);
        const cw = this.getWriter(context).writeFile(linkMapper.getPath(node));
        cw.write(headerTemplate(templateData));
        cw.write(summaryTableHeader);
        children.forEach(child => {
            const metrics = child.getCoverageSummary();
            const isEmpty = metrics.isEmpty();
            if (skipEmpty && isEmpty) {
                return;
            }
            const reportClasses = isEmpty
                ? emptyClasses
                : {
                      statements: context.classForPercent(
                          'statements',
                          metrics.statements.pct
                      ),
                      lines: context.classForPercent(
                          'lines',
                          metrics.lines.pct
                      ),
                      functions: context.classForPercent(
                          'functions',
                          metrics.functions.pct
                      ),
                      branches: context.classForPercent(
                          'branches',
                          metrics.branches.pct
                      )
                  };
            const data = {
                metrics: isEmpty ? fixPct(metrics) : metrics,
                reportClasses,
                file: child.getRelativeName(),
                output: linkMapper.relativePath(node, child)
            };
            cw.write(summaryLineTemplate(data) + '\n');
        });
        cw.write(summaryTableFooter);
        cw.write(footerTemplate(templateData));
        cw.close();
    }

    onDetail(node, context) {
        const linkMapper = this.linkMapper;
        const templateData = this.getTemplateData();

        this.fillTemplate(node, templateData, context);
        const cw = this.getWriter(context).writeFile(linkMapper.getPath(node));
        cw.write(headerTemplate(templateData));
        cw.write('

\n');
        cw.write(
            detailTemplate(
                annotator.annotateSourceCode(node.getFileCoverage(), context)
            )
        );
        cw.write('

\n');
        cw.write(footerTemplate(templateData));
        cw.close();
    }
}

module.exports = HtmlReport;


text:
class Painting < ActiveRecord::Base
  belongs_to :gallery

  has_attached_file :picture,
                    :styles => { :normal => ["832x768>", :png], :thumb => ["130x130>", :png] },
                    :storage => :s3,
                    :path => ":attachment/:id/:style.png",
                    :s3_credentials => File.join(Rails.root, 'config', 's3.yml')

  validates_attachment_presence :picture

  validates_presence_of :picture, :title, :author, :gallery_id

  def serializable_hash(options = nil)
	  super(:only => [:id, :title, :author])
	end
end


text:
// @file rsmember.h

/** replica set member */

#pragma once

#include "../../util/concurrency/value.h"

namespace mongo {

    /*
        RS_STARTUP    serving still starting up, or still trying to initiate the set
        RS_PRIMARY    this server thinks it is primary
        RS_SECONDARY  this server thinks it is a secondary (slave mode)
        RS_RECOVERING recovering/resyncing; after recovery usually auto-transitions to secondary
        RS_FATAL      something bad has occurred and server is not completely offline with regard to the replica set.  fatal error.
        RS_STARTUP2   loaded config, still determining who is primary
    */
    struct MemberState {
        enum MS {
            RS_STARTUP = 0,
            RS_PRIMARY = 1,
            RS_SECONDARY = 2,
            RS_RECOVERING = 3,
            RS_FATAL = 4,
            RS_STARTUP2 = 5,
            RS_UNKNOWN = 6, /* remote node not yet reached */
            RS_ARBITER = 7,
            RS_DOWN = 8, /* node not reachable for a report */
            RS_ROLLBACK = 9,
            RS_SHUNNED = 10, /* node shunned from replica set */
        } s;

        MemberState(MS ms = RS_UNKNOWN) : s(ms) { }
        explicit MemberState(int ms) : s((MS) ms) { }

        bool startup() const { return s == RS_STARTUP; }
        bool primary() const { return s == RS_PRIMARY; }
        bool secondary() const { return s == RS_SECONDARY; }
        bool recovering() const { return s == RS_RECOVERING; }
        bool startup2() const { return s == RS_STARTUP2; }
        bool fatal() const { return s == RS_FATAL; }
        bool rollback() const { return s == RS_ROLLBACK; }
        bool readable() const { return s == RS_PRIMARY || s == RS_SECONDARY; }
        bool shunned() const { return s == RS_SHUNNED; }

        string toString() const;

        bool operator==(const MemberState& r) const { return s == r.s; }
        bool operator!=(const MemberState& r) const { return s != r.s; }
    };

    /* this is supposed to be just basic information on a member,
       and copy constructable. */
    class HeartbeatInfo {
        unsigned _id;
    public:
        HeartbeatInfo() : _id(0xffffffff), hbstate(MemberState::RS_UNKNOWN), health(-1.0),
            downSince(0), lastHeartbeatRecv(0), skew(INT_MIN), authIssue(false), ping(0) { }
        HeartbeatInfo(unsigned id);
        unsigned id() const { return _id; }
        MemberState hbstate;
        double health;
        time_t upSince;
        long long downSince;
        // This is the last time we got a response from a heartbeat request to a given member.
        time_t lastHeartbeat;
        // This is the last time we got a heartbeat request from a given member.
        time_t lastHeartbeatRecv;
        DiagStr lastHeartbeatMsg;
        DiagStr syncingTo;
        OpTime opTime;
        int skew;
        bool authIssue;
        unsigned int ping; // milliseconds
        static unsigned int numPings;

        bool up() const { return health > 0; }

        /** health is set to -1 on startup.  that means we haven't even checked yet.  0 means we checked and it failed. */
        bool maybeUp() const { return health != 0; }

        long long timeDown() const; // ms

        /* true if changed in a way of interest to the repl set manager. */
        bool changed(const HeartbeatInfo& old) const;

        void recvHeartbeat();
    };

    inline HeartbeatInfo::HeartbeatInfo(unsigned id) :
        _id(id),
        lastHeartbeatRecv(0),
        authIssue(false),
        ping(0) {
        hbstate = MemberState::RS_UNKNOWN;
        health = -1.0;
        downSince = 0;
        lastHeartbeat = upSince = 0;
        skew = INT_MIN;
    }

    inline bool HeartbeatInfo::changed(const HeartbeatInfo& old) const {
        return health != old.health ||
               hbstate != old.hbstate;
    }

    inline string MemberState::toString() const {
        switch ( s ) {
        case RS_STARTUP: return "STARTUP";
        case RS_PRIMARY: return "PRIMARY";
        case RS_SECONDARY: return "SECONDARY";
        case RS_RECOVERING: return "RECOVERING";
        case RS_FATAL: return "FATAL";
        case RS_STARTUP2: return "STARTUP2";
        case RS_ARBITER: return "ARBITER";
        case RS_DOWN: return "DOWN";
        case RS_ROLLBACK: return "ROLLBACK";
        case RS_UNKNOWN: return "UNKNOWN";
        case RS_SHUNNED: return "REMOVED";
        }
        return "";
    }

}


text:
package com.reactnativenavigation.views;

import android.content.Context;
import android.view.Menu;
import android.view.ViewManager;

import com.facebook.react.bridge.Callback;
import com.reactnativenavigation.NavigationApplication;
import com.reactnativenavigation.events.ContextualMenuHiddenEvent;
import com.reactnativenavigation.events.EventBus;
import com.reactnativenavigation.params.ContextualMenuButtonParams;
import com.reactnativenavigation.params.ContextualMenuParams;
import com.reactnativenavigation.params.StyleParams;
import com.reactnativenavigation.params.TitleBarLeftButtonParams;

import java.util.List;

public class ContextualMenu extends TitleBar implements LeftButtonOnClickListener, ContextualMenuButton.ContextualButtonClickListener {
    private ContextualMenuParams params;
    private Callback onButtonClicked;
    private final String navigatorEventId;

    public ContextualMenu(Context context, ContextualMenuParams params, StyleParams styleParams, Callback onButtonClicked) {
        super(context);
        this.params = params;
        this.onButtonClicked = onButtonClicked;
        navigatorEventId = params.navigationParams.navigatorEventId;
        setStyle(styleParams);
        setButtons();
    }

    public void setStyle(StyleParams styleParams) {
        params.setButtonsColor(styleParams.contextualMenuButtonsColor);
        if (styleParams.contextualMenuBackgroundColor.hasColor()) {
            setBackgroundColor(styleParams.contextualMenuBackgroundColor.getColor());
        }
    }

    public void setButtons() {
        addButtonsToContextualMenu(params.buttons, getMenu());
        setBackButton(params.leftButton);
    }

    private void setBackButton(TitleBarLeftButtonParams leftButton) {
        setLeftButton(leftButton, this, null, false);
    }

    private void addButtonsToContextualMenu(List<ContextualMenuButtonParams> buttons, Menu menu) {
        for (int i = 0; i < buttons.size(); i++) {
            final TitleBarButton button = new ContextualMenuButton(menu, getActionMenuView(), buttons.get(i), this);
            addButtonInReverseOrder(buttons, i, button);
        }
    }

    @Override
    public boolean onTitleBarBackButtonClick() {
        dismiss();
        EventBus.instance.post(new ContextualMenuHiddenEvent());
        return true;
    }

    @Override
    public void onSideMenuButtonClick() {
        // nothing
    }

    @Override
    public void onClick(int index) {
        dismiss();
        EventBus.instance.post(new ContextualMenuHiddenEvent());
        onButtonClicked.invoke(index);
    }

    public void dismiss() {
        hide(new Runnable() {
            @Override
            public void run() {
                ((ViewManager) getParent()).removeView(ContextualMenu.this);
            }
        });
        NavigationApplication.instance.getEventEmitter().sendNavigatorEvent("contextualMenuDismissed", navigatorEventId);
    }
}