text:
package com.amazonaws.services.medialive.model;

import javax.annotation.Generated;

/**
 * M2ts Segmentation Markers
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum M2tsSegmentationMarkers {

    EBP("EBP"),
    EBP_LEGACY("EBP_LEGACY"),
    NONE("NONE"),
    PSI_SEGSTART("PSI_SEGSTART"),
    RAI_ADAPT("RAI_ADAPT"),
    RAI_SEGSTART("RAI_SEGSTART");

    private String value;

    private M2tsSegmentationMarkers(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return M2tsSegmentationMarkers corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static M2tsSegmentationMarkers fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (M2tsSegmentationMarkers enumEntry : M2tsSegmentationMarkers.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
{% extends "giv/templates/main" %}

{% block mainbody %}

Media

Check out Givology in the press & media.

<p.
In this section, you can read about our impact in the community, download our annual reports, check out our archive of photos and videos from our chapters and network, and learn about our philosophy of giving. If you would like to contribute to this archive, please e-mail us at info@givology.org.  We would love for you to join in on our campaigns!

Photos

Videos

Press

Annual Reports

{% include "sub-support-givology.html" %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
module Upcoming
  class Country
    include Upcoming::Defaults

    # +country_id+ (Required)
    # The country_id number of the country to look within. Country ID's are referred to within other API methods, such as metro.getStateList and state.getInfo. To run getInfo on multiple countries, simply pass an array or a comma-separated list of country_id numbers.
    #
    def self.info(country_id)
      country_id = country_id.join(',') if country_id.is_a?(Array)
      Mash.new(self.get('/', :query => {:method => 'country.getInfo', :country_id => country_id}.merge(Upcoming.default_options))).rsp.country
    end
  end
end


text:
/*
 * AHRS.h
 *
 *  Created on: Jul 30, 2015
 *      Author: Scott
 */

#ifndef SRC_AHRS_H_
#define SRC_AHRS_H_

#include "WPILib.h"
#include "ITimestampedDataSubscriber.h"
#include <thread>

class IIOProvider;
class ContinuousAngleTracker;
class InertialDataIntegrator;
class OffsetTracker;
class AHRSInternal;

class AHRS : public SensorBase,
             public LiveWindowSendable,
             public PIDSource  {
public:

    enum BoardAxis {
        kBoardAxisX = 0,
        kBoardAxisY = 1,
        kBoardAxisZ = 2,
    };

    struct BoardYawAxis
    {
        /* Identifies one of the board axes */
        BoardAxis board_axis;
        /* true if axis is pointing up (with respect to gravity); false if pointing down. */
        bool up;
    };

    enum SerialDataType {
    /**
     * (default):  6 and 9-axis processed data
     */
    kProcessedData = 0,
    /**
     * unprocessed data from each individual sensor
     */
    kRawData = 1
    };

private:
    friend class AHRSInternal;
    AHRSInternal *      ahrs_internal;

    volatile float      yaw;
    volatile float      pitch;
    volatile float      roll;
    volatile float      compass_heading;
    volatile float      world_linear_accel_x;
    volatile float      world_linear_accel_y;
    volatile float      world_linear_accel_z;
    volatile float      mpu_temp_c;
    volatile float      fused_heading;
    volatile float      altitude;
    volatile float      baro_pressure;
    volatile bool       is_moving;
    volatile bool       is_rotating;
    volatile float      baro_sensor_temp_c;
    volatile bool       altitude_valid;
    volatile bool       is_magnetometer_calibrated;
    volatile bool       magnetic_disturbance;
    volatile float    	quaternionW;
    volatile float    	quaternionX;
    volatile float    	quaternionY;
    volatile float    	quaternionZ;

    /* Integrated Data */
    float velocity[3];
    float displacement[3];

    /* Raw Data */
    volatile int16_t    raw_gyro_x;
    volatile int16_t    raw_gyro_y;
    volatile int16_t    raw_gyro_z;
    volatile int16_t    raw_accel_x;
    volatile int16_t    raw_accel_y;
    volatile int16_t    raw_accel_z;
    volatile int16_t    cal_mag_x;
    volatile int16_t    cal_mag_y;
    volatile int16_t    cal_mag_z;

    /* Configuration/Status */
    volatile uint8_t    update_rate_hz;
    volatile int16_t    accel_fsr_g;
    volatile int16_t    gyro_fsr_dps;
    volatile int16_t    capability_flags;
    volatile uint8_t    op_status;
    volatile int16_t    sensor_status;
    volatile uint8_t    cal_status;
    volatile uint8_t    selftest_status;

    /* Board ID */
    volatile uint8_t    board_type;
    volatile uint8_t    hw_rev;
    volatile uint8_t    fw_ver_major;
    volatile uint8_t    fw_ver_minor;

    long                last_sensor_timestamp;
    double              last_update_time;

    std::shared_ptr<ITable>	table;

    InertialDataIntegrator *integrator;
    ContinuousAngleTracker *yaw_angle_tracker;
    OffsetTracker *         yaw_offset_tracker;
    IIOProvider *           io;

    std::thread *           task;

#define MAX_NUM_CALLBACKS 3
    ITimestampedDataSubscriber *callbacks[MAX_NUM_CALLBACKS];
    void *callback_contexts[MAX_NUM_CALLBACKS];

public:
    AHRS(SPI::Port spi_port_id);
    AHRS(I2C::Port i2c_port_id);
    AHRS(SerialPort::Port serial_port_id);

    AHRS(SPI::Port spi_port_id, uint8_t update_rate_hz);
    AHRS(SPI::Port spi_port_id, uint32_t spi_bitrate, uint8_t update_rate_hz);

    AHRS(I2C::Port i2c_port_id, uint8_t update_rate_hz);

    AHRS(SerialPort::Port serial_port_id, AHRS::SerialDataType data_type, uint8_t update_rate_hz);

    float  GetPitch();
    float  GetRoll();
    float  GetYaw();
    float  GetCompassHeading();
    void   ZeroYaw();
    bool   IsCalibrating();
    bool   IsConnected();
    double GetByteCount();
    double GetUpdateCount();
    long   GetLastSensorTimestamp();
    float  GetWorldLinearAccelX();
    float  GetWorldLinearAccelY();
    float  GetWorldLinearAccelZ();
    bool   IsMoving();
    bool   IsRotating();
    float  GetBarometricPressure();
    float  GetAltitude();
    bool   IsAltitudeValid();
    float  GetFusedHeading();
    bool   IsMagneticDisturbance();
    bool   IsMagnetometerCalibrated();
    float  GetQuaternionW();
    float  GetQuaternionX();
    float  GetQuaternionY();
    float  GetQuaternionZ();
    void   ResetDisplacement();
    void   UpdateDisplacement( float accel_x_g, float accel_y_g,
                               int update_rate_hz, bool is_moving );
    float  GetVelocityX();
    float  GetVelocityY();
    float  GetVelocityZ();
    float  GetDisplacementX();
    float  GetDisplacementY();
    float  GetDisplacementZ();
    double GetAngle();
    double GetRate();
    void   SetAngleAdjustment(double angle);
    double GetAngleAdjustment();
    void   Reset();
    float  GetRawGyroX();
    float  GetRawGyroY();
    float  GetRawGyroZ();
    float  GetRawAccelX();
    float  GetRawAccelY();
    float  GetRawAccelZ();
    float  GetRawMagX();
    float  GetRawMagY();
    float  GetRawMagZ();
    float  GetPressure();
    float  GetTempC();
    AHRS::BoardYawAxis GetBoardYawAxis();
    std::string GetFirmwareVersion();

    bool RegisterCallback( ITimestampedDataSubscriber *callback, void *callback_context);
    bool DeregisterCallback( ITimestampedDataSubscriber *callback );

    int GetActualUpdateRate();
    int GetRequestedUpdateRate();

private:
    void SPIInit( SPI::Port spi_port_id, uint32_t bitrate, uint8_t update_rate_hz );
    void I2CInit( I2C::Port i2c_port_id, uint8_t update_rate_hz );
    void SerialInit(SerialPort::Port serial_port_id, AHRS::SerialDataType data_type, uint8_t update_rate_hz);
    void commonInit( uint8_t update_rate_hz );
    static int ThreadFunc(IIOProvider *io_provider);

    /* LiveWindowSendable implementation */
    void InitTable(std::shared_ptr<ITable> subtable);
    std::shared_ptr<ITable> GetTable() const;
    std::string GetSmartDashboardType() const;
    void UpdateTable();
    void StartLiveWindowMode();
    void StopLiveWindowMode();

    /* PIDSource implementation */
    double PIDGet();

    uint8_t GetActualUpdateRateInternal(uint8_t update_rate);
};

#endif /* SRC_AHRS_H_ */


text:
How to run Yona
===

Go to the unpacked directory and run yona.

```
YONA_DATA=/yona-data;export YONA_DATA
bin/yona
```
**[Caution!] Please move below bin folder and do not run `yona` directly**

First Page
----
You can now access the welcome page by accessing the appropriate server 9000 port (http://127.0.0.1:9000 in local environment) with your web browser.

Finish setting admin and restart Yona.

**Note! For Windows OS users**
Please note [#windows-os](yona-run-options.md#windows-os)

### To restart

- In the Linux/Uinx, the kill pid command stops the service.
- [Simple Restart Shell Example](https://github.com/yona-projects/yona/blob/next/restart.sh)
- Windows users exit the batch file that is running with ctrl-c.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/llContent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:fadeScrollbars="false"
        />

</LinearLayout>


text:
<?php

namespace Illuminate\Http\Resources;

class MissingValue implements PotentiallyMissing
{
    /**
     * Determine if the object should be considered "missing".
     *
     * @return bool
     */
    public function isMissing()
    {
        return true;
    }
}


text:
using Anotar.Serilog;
using Serilog;
using Log = Serilog.Log;

public class ClassWithExistingField
{
// ReSharper disable once NotAccessedField.Local
    static ILogger existingLogger;

    static ClassWithExistingField()
    {
        existingLogger = Log.ForContext<ClassWithExistingField>();
    }

    public void Debug()
    {
        LogTo.Debug();
    }

}


text:
from __future__ import print_function
import os
import sys
import shutil
import zipfile
import shlex
from zipfile import ZipFile
from urllib.request import urlretrieve
from subprocess import Popen, PIPE
from distutils.cmd import Command

def zip_directory(dir, zip_file):
    zip = ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED)
    root_len = len(os.path.abspath(dir))
    for root, dirs, files in os.walk(dir):
        archive_root = os.path.abspath(root)[root_len:]
        for f in files:
            fullpath = os.path.join(root, f)
            archive_name = os.path.join(archive_root, f)
            zip.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)
    zip.close()

class WindowsPortableBuild(Command):
    description = "custom build command that builds portable win32 package"
    user_options = [
        ('dist-dir=', None,
         "path of dist directory to use for building portable kivy, the end result will be output to this driectory. default to cwd."),
        ('deps-url=', None,
         "url of binary dependancies for portable kivy package default: http://kivy.googlecode.com/files/portable-deps-win32.zip"),
        ('no-cext', None,
         "flag to disable building of c extensions"),
        ('no-mingw', None,
         "flag to disable bundling of mingw compiler for compiling c/cython extensions")]

    def initialize_options(self):
        self.dist_dir = None
        self.deps_url = None
        self.no_cext = None
        self.no_mingw = None

    def finalize_options(self):
        if not self.deps_url:
            self.deps_url = 'http://kivy.googlecode.com/files/portable-deps-win32.zip'
        if not self.dist_dir:
            self.dist_dir = os.getcwd()

        self.src_dir = os.path.dirname(sys.modules['__main__'].__file__)
        self.dist_name = self.distribution.get_fullname() # e.g. Kivy-0.5 (name and verison passed to setup())
        self.build_dir = os.path.join(self.dist_dir, self.dist_name+'-w32')

    def run(self):
        width = 30
        print("-" * width)
        print("Building Kivy Portable for Win 32")
        print("-" * width)
        print("\nPreparing Build...")
        print("-" * width)
        if os.path.exists(self.build_dir):
            print("*Cleaning old build dir")
            shutil.rmtree(self.build_dir, ignore_errors=True)
        print("*Creating build directory:", self.build_dir)
        os.makedirs(self.build_dir)

        print("\nGetting binary dependencies...")
        print("---------------------------------------")
        print("*Downloading:", self.deps_url)
        #report_hook is called every time a piece of teh file is downloaded to print progress
        def report_hook(block_count, block_size, total_size):
            p = block_count * block_size * 100.0 / total_size
            print("\b\b\b\b\b\b\b\b\b", "%06.2f" % p + "%", end=' ')
        print(" Progress: 000.00%", end=' ')
        urlretrieve(self.deps_url, # location of binary dependencies needed for portable kivy
                    os.path.join(self.build_dir, 'deps.zip'), # tmp file to store the archive
                    reporthook = report_hook)
        print(" [Done]")

        print("*Extracting binary dependencies...")
        zf = ZipFile(os.path.join(self.build_dir, 'deps.zip'))
        zf.extractall(self.build_dir)
        zf.close()
        if self.no_mingw:
            print("*Excluding MinGW from portable distribution (--no-mingw option is set)")
            shutil.rmtree(os.path.join(self.build_dir, 'MinGW'), ignore_errors=True)

        print("\nPutting kivy into portable environment")
        print("---------------------------------------")
        print("*Building kivy source distribution")
        sdist_cmd = [sys.executable, #path to python.exe
                     os.path.join(self.src_dir, 'setup.py'), #path to setup.py
                     'sdist', #make setup.py create a src distribution
                     '--dist-dir=%s'%self.build_dir] #put it into build folder
        Popen(sdist_cmd, stdout=PIPE, stderr=PIPE).communicate()

        print("*Placing kivy source distribution in portable context")
        src_dist = os.path.join(self.build_dir, self.dist_name)
        zf = ZipFile(src_dist+'.zip')
        zf.extractall(self.build_dir)
        zf.close()
        if self.no_mingw or self.no_cext:
            print("*Skipping C Extension build (either --no_cext or --no_mingw option set)")
        else:
            print("*Compiling C Extensions inplace for portable distribution")
            cext_cmd = [sys.executable, #path to python.exe
                        'setup.py',
                        'build_ext', #make setup.py create a src distribution
                        '--inplace'] #do it inplace
            #this time it runs teh setup.py inside the source distribution
            #thats has been generated inside the build dir (to generate ext
            #for teh target, instead of the source were building from)
            Popen(cext_cmd, cwd=src_dist).communicate()

        print("\nFinalizing kivy portable distribution...")
        print("---------------------------------------")
        print("*Copying scripts and resources")
        #copy launcher script and readme to portable root dir/build dir
        kivy_bat = os.path.join(src_dist, 'kivy', 'tools', 'packaging', 'win32', 'kivy.bat')
        shutil.copy(kivy_bat, os.path.join(self.build_dir, 'kivy.bat'))
        kivyenv_sh = os.path.join(src_dist, 'kivy', 'tools', 'packaging', 'win32', 'kivyenv.sh')
        shutil.copy(kivyenv_sh, os.path.join(self.build_dir, 'kivyenv.sh'))
        readme = os.path.join(src_dist, 'kivy', 'tools', 'packaging', 'win32', 'README.txt')
        shutil.copy(readme, os.path.join(self.build_dir, 'README.txt'))
        #rename kivy directory to "kivy"
        os.rename(src_dist, os.path.join(self.build_dir, 'kivy'))

        print("*Removing intermediate file")
        os.remove(os.path.join(self.build_dir, 'deps.zip'))
        os.remove(os.path.join(self.build_dir, src_dist + '.zip'))

        print("*Compressing portable distribution target")
        target = os.path.join(self.dist_dir, self.dist_name + "-w32.zip")
        zip_directory(self.build_dir, target)
        print("*Writing target:", target)
        print("*Removing build dir")
        shutil.rmtree(self.build_dir, ignore_errors=True)

        print("*Upload to google code")
        sys.path += [os.path.join(self.src_dir, 'kivy', 'tools', 'packaging')]
        import googlecode_upload
        version = self.dist_name.replace("Kivy-", "")
        status, reason, url = googlecode_upload.upload_find_auth(
            target, 'kivy',
            'Kivy {}, Windows portable version (Python 2.7, '
            '32 and 64 bits, bundled dependencies)'.format(version),
            ['Featured', 'OsSys-Windows'])

        if url:
              print('The file was uploaded successfully.')
              print('URL: %s' % url)
        else:
              print('An error occurred. Your file was not uploaded.')
              print('Google Code upload server said: %s (%s)' % (reason,
                  status))


text:
package com.whatistics.backend.parser;

import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * @author robert
 * Note: this class has a natural ordering that is inconsistent with equals.
 */
public class TimeFormat implements Comparable {

    private String rawFormat;
    private Locale locale;
    private DateTimeFormatter formatter;

    public TimeFormat(String rawFormat){
        this.rawFormat = rawFormat;
    }

    /**
     * Locale is ignored if the DateTimeFormatter is set directly later.
     * @param rawFormat
     * @param locale
     */
    public TimeFormat(String rawFormat, Locale locale){
        this.rawFormat = rawFormat;
        this.locale = locale;
    }

    public TimeFormat setFormatter(DateTimeFormatter formatter){
        this.formatter = formatter;
        return this;
    }

    public DateTimeFormatter asDateTimeFormatter(){
        if (formatter == null && locale == null)
            formatter = DateTimeFormatter.ofPattern(rawFormat);
        if (formatter == null && locale != null)
            formatter = DateTimeFormatter.ofPattern(rawFormat).withLocale(locale);

        return formatter;
    }

    public String getRawFormat() {
        return rawFormat;
    }

    public int getLength(){
        return rawFormat.length();
    }

    @Override
    public int compareTo(Object o) {
        TimeFormat p = (TimeFormat)o;
        if(p.getLength() < this.getLength())
            return 1;
        if(p.getLength() > this.getLength())
            return -1;
        else
            return 0;
    }

    @Override
    public int hashCode() {
        int result = rawFormat != null ? rawFormat.hashCode() : 0;
        result = 31 * result + (locale != null ? locale.hashCode() : 0);
        result = 31 * result + (formatter != null ? formatter.hashCode() : 0);
        return result;
    }

}


text:
#include "2d/CCFontAtlasCache.h"

#include <iostream>
#include <sstream>
#include "base/CCDirector.h"
#include "2d/CCFontFNT.h"
#include "2d/CCFontFreeType.h"
#include "2d/CCFontAtlas.h"
#include "2d/CCFontCharMap.h"
#include "2d/CCLabel.h"

NS_CC_BEGIN

std::unordered_map<std::string, FontAtlas *> FontAtlasCache::_atlasMap;

void FontAtlasCache::purgeCachedData()
{
    auto atlasMapCopy = _atlasMap;
    for (auto&& atlas : atlasMapCopy)
    {
        atlas.second->purgeTexturesAtlas();
    }
}

FontAtlas* FontAtlasCache::getFontAtlasTTF(const _ttfConfig* config)
{
    bool useDistanceField = config->distanceFieldEnabled;
    if(config->outlineSize > 0)
    {
        useDistanceField = false;
    }

    auto atlasName = generateFontName(config->fontFilePath, config->fontSize, useDistanceField);
    atlasName.append("_outline_");
    std::stringstream ss;
    ss << config->outlineSize;
    atlasName.append(ss.str());

    auto it = _atlasMap.find(atlasName);

    if ( it == _atlasMap.end() )
    {
        auto font = FontFreeType::create(config->fontFilePath, config->fontSize, config->glyphs,
            config->customGlyphs, useDistanceField, config->outlineSize);
        if (font)
        {
            auto tempAtlas = font->createFontAtlas();
            if (tempAtlas)
            {
                _atlasMap[atlasName] = tempAtlas;
                return _atlasMap[atlasName];
            }
        }
    }
    else
    {
        _atlasMap[atlasName]->retain();
        return _atlasMap[atlasName];
    }

    return nullptr;
}

FontAtlas* FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName, const Vec2& imageOffset /* = Vec2::ZERO */)
{
    std::string atlasName = generateFontName(fontFileName, 0,false);
    auto it = _atlasMap.find(atlasName);

    if ( it == _atlasMap.end() )
    {
        auto font = FontFNT::create(fontFileName,imageOffset);

        if(font)
        {
            auto tempAtlas = font->createFontAtlas();
            if (tempAtlas)
            {
                _atlasMap[atlasName] = tempAtlas;
                return _atlasMap[atlasName];
            }
        }
    }
    else
    {
        _atlasMap[atlasName]->retain();
        return _atlasMap[atlasName];
    }

    return nullptr;
}

FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile)
{
    std::string atlasName = generateFontName(plistFile, 0,false);
    auto it = _atlasMap.find(atlasName);

    if ( it == _atlasMap.end() )
    {
        auto font = FontCharMap::create(plistFile);

        if(font)
        {
            auto tempAtlas = font->createFontAtlas();
            if (tempAtlas)
            {
                _atlasMap[atlasName] = tempAtlas;
                return _atlasMap[atlasName];
            }
        }
    }
    else
    {
        _atlasMap[atlasName]->retain();
        return _atlasMap[atlasName];
    }

    return nullptr;
}

FontAtlas* FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap)
{
    char tmp[30];
    sprintf(tmp,"name:%u_%d_%d_%d",texture->getName(),itemWidth,itemHeight,startCharMap);
    std::string atlasName = generateFontName(tmp, 0,false);

    auto it = _atlasMap.find(atlasName);
    if ( it == _atlasMap.end() )
    {
        auto font = FontCharMap::create(texture,itemWidth,itemHeight,startCharMap);

        if(font)
        {
            auto tempAtlas = font->createFontAtlas();
            if (tempAtlas)
            {
                _atlasMap[atlasName] = tempAtlas;
                return _atlasMap[atlasName];
            }
        }
    }
    else
    {
        _atlasMap[atlasName]->retain();
        return _atlasMap[atlasName];
    }

    return nullptr;
}

FontAtlas* FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
{
    char tmp[255];
    snprintf(tmp,250,"name:%s_%d_%d_%d",charMapFile.c_str(),itemWidth,itemHeight,startCharMap);

    std::string atlasName = generateFontName(tmp, 0,false);

    auto it = _atlasMap.find(atlasName);
    if ( it == _atlasMap.end() )
    {
        auto font = FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap);

        if(font)
        {
            auto tempAtlas = font->createFontAtlas();
            if (tempAtlas)
            {
                _atlasMap[atlasName] = tempAtlas;
                return _atlasMap[atlasName];
            }
        }
    }
    else
    {
        _atlasMap[atlasName]->retain();
        return _atlasMap[atlasName];
    }

    return nullptr;
}

std::string FontAtlasCache::generateFontName(const std::string& fontFileName, float size, bool useDistanceField)
{
    std::string tempName(fontFileName);

    if(useDistanceField)
        tempName.append("df");
    // std::to_string is not supported on android, using std::stringstream instead.
    std::stringstream ss;
    ss.precision(2);
    ss << std::fixed << size;
    return  tempName.append(ss.str());
}

bool FontAtlasCache::releaseFontAtlas(FontAtlas *atlas)
{
    if (nullptr != atlas)
    {
        for( auto &item: _atlasMap )
        {
            if ( item.second == atlas )
            {
                if (atlas->getReferenceCount() == 1)
                {
                  _atlasMap.erase(item.first);
                }

                atlas->release();

                return true;
            }
        }
    }

    return false;
}

NS_CC_END


text:
package de.kuei.metafora.client.planningtool.xml.cfcreator;

public enum Role {
	originator, receiver
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MetroFramework.Forms;

namespace ManejoSQLite
{
    public partial class Principal : MetroForm
    {
        DataTable dsReporte;
        string ruta;

        public string Ruta
        {
            get
            {
                return ruta;
            }

            set
            {
                ruta = value;
            }
        }

        //-------------------Constructor-------------------
        public Principal()
        {
            InitializeComponent();
        }

        //--------------------Eventos------------------------

        private void Principal_Load(object sender, EventArgs e)
        {

        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            Services.Libro oLibro = new Services.Libro();
            BO.Libro oLibroBO = new BO.Libro();
            if (txtISBN.Text.Trim().Length > 0)
            {
                oLibroBO.Isbn = txtISBN.Text.Trim();
            }

            if (txtAutor.Text.Trim().Length > 0)
            {
                oLibroBO.Autor = txtAutor.Text.Trim();
            }

            if (txtEditorial.Text.Trim().Length > 0)
            {
                oLibroBO.Editorial = txtEditorial.Text.Trim();
            }

            if (txtNombre.Text.Trim().Length > 0)
            {
                oLibroBO.Titulo = txtNombre.Text.Trim();
            }

            if (txtPrecio.Text.Trim().Length > 0)
            {
                oLibroBO.Precio = Convert.ToDecimal( txtISBN.Text.Trim());
            }

            dgListado.DataSource = oLibro.ListarLibro(oLibroBO).Tables[0];
            dsReporte = oLibro.ListarLibro(oLibroBO).Tables[0];
        }

        private void btnNuevo_Click(object sender, EventArgs e)
        {
            ManejoSQLite.Editar frmEditar = new ManejoSQLite.Editar();
            frmEditar.ShowDialog();
        }

        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {
            BO.Libro olibroBO = new BO.Libro();
            string id = gridView1.GetFocusedRowCellValue("ISBN").ToString();
            olibroBO.Isbn = id;
            Editar frmEditar = new Editar(olibroBO);
            frmEditar.ShowDialog();
            this.Ruta = frmEditar.Ruta;
           // dgListado.DataSource = this.Listar();
        }

        private void btnImprimir_Click_1(object sender, EventArgs e)
        {
            rpt rpt = new rpt(dsReporte);
            rpt.ShowDialog();
        }

        private void dgListado_Click(object sender, EventArgs e)
        {

        }

        //---------------------Metodos------------------------

    }
}


text:
/**
 */
package CIM.IEC61970.Informative.InfGMLSupport.impl;

import CIM.IEC61970.Informative.InfGMLSupport.GmlPolygonGeometry;
import CIM.IEC61970.Informative.InfGMLSupport.InfGMLSupportPackage;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'Gml Polygon Geometry'.
 *
 *
 * @generated
 */
public class GmlPolygonGeometryImpl extends GmlDiagramObjectImpl implements GmlPolygonGeometry {
	/**
	 *
	 *
	 * @generated
	 */
	protected GmlPolygonGeometryImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return InfGMLSupportPackage.Literals.GML_POLYGON_GEOMETRY;
	}

} //GmlPolygonGeometryImpl


text:
function BxShowAuthService(id, suffix)
{
	var bxCurrentAuthId = '';
	if(window['bxCurrentAuthId'+suffix])
		bxCurrentAuthId = window['bxCurrentAuthId'+suffix];

	BX('bx_auth_serv'+suffix).style.display = '';
	if(bxCurrentAuthId != '' && bxCurrentAuthId != id)
	{
		BX('bx_auth_href_'+suffix+bxCurrentAuthId).className = '';
		BX('bx_auth_serv_'+suffix+bxCurrentAuthId).style.display = 'none';
	}
	BX('bx_auth_href_'+suffix+id).className = 'bx-ss-selected';
	BX('bx_auth_href_'+suffix+id).blur();
	BX('bx_auth_serv_'+suffix+id).style.display = '';
	var el = BX.findChild(BX('bx_auth_serv_'+suffix+id), {'tag':'input', 'attribute':{'type':'text'}}, true);
	if(el)
		try{el.focus();}catch(e){}
	window['bxCurrentAuthId'+suffix] = id;
    if(document.forms['bx_auth_services'+suffix])
        document.forms['bx_auth_services'+suffix].auth_service_id.value = id;
    else if(document.forms['bx_user_profile_form'+suffix])
        document.forms['bx_user_profile_form'+suffix].auth_service_id.value = id;
}

var bxAuthWnd = false;
function BxShowAuthFloat(id, suffix)
{
	var bCreated = false;
	if(!bxAuthWnd)
	{
		bxAuthWnd = new BX.CDialog({
			'content':'

',
			'width': 640,
			'height': 400,
			'resizable': false
		});
		bCreated = true;
	}
	bxAuthWnd.Show();

	if(bCreated)
		BX('bx_auth_float_container').appendChild(BX('bx_auth_float'));

	BxShowAuthService(id, suffix);
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
 Copyright 2016 The TensorFlow Authors. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <org.sortinghat.demo.AutoFitTextureView
          android:id="@+id/texture"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"/>

      <org.sortinghat.demo.OverlayView
          android:id="@+id/tracking_overlay"
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>

      <org.sortinghat.demo.OverlayView
          android:id="@+id/debug_overlay"
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>
</FrameLayout>


text:
	#include <Arduino.h>
	#include <SdFat.h>
#endif
#include "88dcdd.h"

//#define DISK_DEBUG

disks disk_drive;

void set_status(uint8_t bit)
{
	disk_drive.current->status &= ~bit;
}

void clear_status(uint8_t bit)
{
	disk_drive.current->status |= bit;
}

void disk_select(uint8_t b)
{
	uint8_t select = b & 0xf;

	if(select == 0)
	{
		disk_drive.current = &disk_drive.disk1;
	}
	else if(select == 1)
	{
		disk_drive.current = &disk_drive.disk2;
	}
	else
	{
		disk_drive.current = &disk_drive.nodisk;
	}
}

uint8_t disk_status()
{
#ifdef DISK_DEBUG
#ifdef ARDUINO
	Serial.print("Returning status ");
	Serial.print(disk_drive.current->status);
	Serial.println(" for disk");
#else
	printf("Returning status %d for disk\n", disk_drive.current->status);
#endif
#endif
	return disk_drive.current->status;
}

void disk_function(uint8_t b)
{
#ifdef DISK_DEBUG
#ifdef ARDUINO
	Serial.print("Disk function ");
	Serial.println(b);
#else
	printf("Disk function %d\n", b);
#endif
#endif

	if(b & CONTROL_STEP_IN)
	{
		disk_drive.current->track++;
		if(disk_drive.current->track != 0)
			clear_status(STATUS_TRACK_0);
#ifdef ARDUINO
		disk_drive.current->fp.seek(TRACK * disk_drive.current->track);
#else
		fseek(disk_drive.current->fp, TRACK * disk_drive.current->track, SEEK_SET);
#endif

#ifdef DISK_DEBUG
#ifdef ARDUINO
		Serial.print("Track seek to : ");
		Serial.println(TRACK * disk_drive.current->track);
#else
		printf("Track seek to : %d\n", TRACK * disk_drive.current->track);
#endif
#endif
	}
	if(b & CONTROL_STEP_OUT)
	{
		if(disk_drive.current->track > 0)
			disk_drive.current->track--;
		if(disk_drive.current->track == 0)
			set_status(STATUS_TRACK_0);
#ifdef ARDUINO
		disk_drive.current->fp.seek(TRACK * disk_drive.current->track);
#else
		fseek(disk_drive.current->fp, TRACK * disk_drive.current->track, SEEK_SET);
#endif
#ifdef DISK_DEBUG
#ifdef ARDUINO
                Serial.print("Track seek to : ");
                Serial.println(TRACK * disk_drive.current->track);
#else
                printf("Track seek to : %d\n", TRACK * disk_drive.current->track);
#endif
#endif
	}
	if(b & CONTROL_HEAD_LOAD)
	{
		set_status(STATUS_HEAD);
		set_status(STATUS_NRDA);
	}
	if(b & CONTROL_HEAD_UNLOAD)
	{
		clear_status(STATUS_HEAD);
	}
	if(b & CONTROL_IE)
	{
	}
	if(b & CONTROL_ID)
	{
	}
	if(b & CONTROL_HCS)
	{
	}
	if(b & CONTROL_WE)
	{
		set_status(STATUS_ENWD);
		disk_drive.current->write_status = 0;
	}
}

uint8_t sector()
{
	uint32_t seek;
	uint8_t ret_val;

	if(disk_drive.current->sector == 32)
	{
		disk_drive.current->sector = 0;
	}
	//current_sector = current_sector % 32;
	seek = disk_drive.current->track * TRACK + disk_drive.current->sector * (SECTOR);
#ifdef ARDUINO
	disk_drive.current->fp.seek(seek);
#else
	fseek(disk_drive.current->fp, seek, SEEK_SET);
#endif

	ret_val = disk_drive.current->sector << 1;
#ifdef DISK_DEBUG
#ifdef ARDUINO
        Serial.print("Current sector: ");
	Serial.print(disk_drive.current->sector);
	Serial.print(" (");
	Serial.print(ret_val, HEX);
	Serial.print(") (bytes per track: ");
	Serial.print(TRACK);
	Serial.println(")");
#else
	printf("Current sector: %d (%X) (bytes per track: %d)\n", disk_drive.current->sector, ret_val, TRACK);
#endif
#endif

	disk_drive.current->sector++;
	return ret_val;
}

void write(uint8_t b)
{
#ifdef DISK_DEBUG
#ifdef ARDUINO
        Serial.print("Write ");
        Serial.print(b);
        Serial.print(" (byte in sector: ");
        Serial.print(disk_drive.current->write_status);
        Serial.println(")");
#else
	printf("Write %d (byte in sector: %d)\n", b, disk_drive.current->write_status);
#endif
#endif
#ifdef ARDUINO
	disk_drive.current->fp.write(&b, 1);
#else
	fwrite(&b, 1, 1, disk_drive.current->fp);
#endif
	if(disk_drive.current->write_status == 137)
	{
		disk_drive.current->write_status = 0;
		clear_status(STATUS_ENWD);
#ifdef DISK_DEBUG
#ifdef ARDUINO
		Serial.println("Disabling clear");
#else
		printf("Disabling clear\n");
#endif
#endif
	}
	else
		disk_drive.current->write_status++;
}

uint8_t read()
{
	static uint32_t bytes = 0;
	uint8_t b;

#ifdef ARDUINO
	b = disk_drive.current->fp.read();
#else
	fread(&b, 1, 1, disk_drive.current->fp);
#endif

	bytes++;

#ifdef DISK_DEBUG
#ifdef ARDUINO
        Serial.print("Reading byte ");
        Serial.print(bytes);
        Serial.print(" (");
        Serial.print(b, HEX);
        Serial.println(")");
#else
	printf("Reading byte %d (%x)\n", bytes, b);
#endif
#endif
	return b;
}


text:
const Sequelize = require('sequelize');

module.exports = function(app) {
  const sequelizeClient = app.get('sequelizeClient');
  const attendees = sequelizeClient.define(
    'attendees',
    {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        unique: true,
        primaryKey: true,
        allowNull: false
      },
      confirmed: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false
      },
      email: {
        type: Sequelize.STRING
      }
    },
    {
      hooks: {
        beforeCount(options) {
          options.raw = true;
        }
      }
    }
  );

  attendees.associate = function(models) {
    // eslint-disable-line no-unused-vars
    // Define associations here
    // See http://docs.sequelizejs.com/en/latest/docs/associations/
    attendees.belongsTo(models.users, { foreignKey: 'uid' });
  };

  return attendees;
};


text:
"""
Coursera's asynchronous grader command line SDK.

You may install it from source, or via pip.
"""

import logging
import requests
import sys

from courseraprogramming.commands import common
from courseraprogramming.commands import oauth2

# Program exit codes to indicate what to do next
class ErrorCodes:
    FATAL_ERROR = 1
    RETRYABLE_ERROR = 2

class GraderExecutorStatus:
    COMPLETED = "COMPLETED"
    PENDING = "PENDING"
    FAILED = "FAILED"
    MISSING = "MISSING"

class GraderExecutorError(Exception):

    def __init__(self, status):
        self.status = status

class ItemNotFoundError(Exception):

    def __init__(self, id):
        self.id = id

class ValidationError(Exception):
    pass

class InternalError(Exception):
    pass

class ProgrammingAssignmentDraftNotReadyError(Exception):
    pass

def command_publish(args):
    oauth2_instance = oauth2.build_oauth2(args)
    course_id = args.course
    item_ids = [args.item] + (getattr(args, 'additional_items') or [])
    error = None
    for item_id in item_ids:
        logging.info("Starting publish for item {} in course {}".format(
            item_id, course_id))
        try:
            logging.info("Fetching required write access token...")
            authoring_pa_id = get_authoring_pa_id(
                oauth2_instance, course_id, item_id)
            write_access_token = get_write_access_token(
                oauth2_instance, args.get_endpoint, authoring_pa_id)
            logging.info("Publishing...")
            publish_item(
                oauth2_instance,
                args.publish_endpoint,
                args.publish_action,
                authoring_pa_id,
                write_access_token)
            logging.info("Publish complete for item {} in course {}".format(
                item_id, course_id))
        except ItemNotFoundError as e:
            logging.error(
                "Unable to find a publishable assignment with item "
                "id {}. Maybe there are no changes to publish?".format(
                    id))
            error = ErrorCodes.FATAL_ERROR
        except ValidationError as e:
            logging.error(
                "We found some validation errors in your assignment with item "
                "id {}. Please verify that your assignment is formatted "
                "correctly and try again.".format(
                    item_id))
            error = ErrorCodes.FATAL_ERROR
        except GraderExecutorError as e:
            if e.status == GraderExecutorStatus.PENDING:
                logging.warn(
                    "We are still processing your grader for your assignment "
                    "with item id {}.  Please try again soon.".format(
                        item_id))
                if error != ErrorCodes.FATAL_ERROR:
                    error = ErrorCodes.RETRYABLE_ERROR
            elif e.status == GraderExecutorStatus.FAILED:
                logging.error(
                    "We were unable to process your grader for your "
                    "assignment with item id {}.  Please try to upload your "
                    "grader again. If the problem persists, please let us "
                    "know.".format(
                        item_id))
                error = ErrorCodes.FATAL_ERROR
            elif e.status == GraderExecutorStatus.MISSING:
                logging.error(
                    "We were unable to find your grader for your assignment "
                    "with item id {}.  Please try to upload your grader "
                    "again. If the problem persists, please let us "
                    "know.".format(
                        item_id))
                error = ErrorCodes.FATAL_ERROR
        except InternalError as e:
            logging.error(
                "Something unexpected happened while trying to publish your "
                "assignment with item id {}. Please verify your course and "
                "item ids are correct.  If the problem persists, please let "
                "us know.".format(
                    item_id))
            error = ErrorCodes.FATAL_ERROR
        except ProgrammingAssignmentDraftNotReadyError as e:
            logging.error(
                "Your assignment with item id {} is not ready for publish. "
                "Please verify your assignment draft is ready and try "
                "again.".format(item_id))
            error = ErrorCodes.FATAL_ERROR
    if error is not None:
        sys.exit(error)

def get_write_access_token(oauth2_instance, get_endpoint, authoring_pa_id):
    auth = oauth2_instance.build_authorizer()
    resp = requests.get(
        '{}/{}?fields=writeAccessToken'.format(
            get_endpoint, authoring_pa_id),
        auth=auth)
    if resp.status_code == 404:
        raise ItemNotFoundError(authoring_pa_id)
    elif resp.status_code == 500:
        raise InternalError()
    pa_authoring = resp.json()['elements'][0]
    if not pa_authoring['readyForPublish']:
        raise ProgrammingAssignmentDraftNotReadyError()
    return pa_authoring['writeAccessToken']

def get_authoring_pa_id(oauth2_instance, course_id, item_id):
    auth = oauth2_instance.build_authorizer()
    atom_relation_api = 'https://api.coursera.org/api/'
    'authoringItemContentRelations.v1'
    resp = requests.get(
        '{}/{}~{}?fields=atomId'.format(
            atom_relation_api, course_id, item_id),
        auth=auth)
    if resp.status_code == 404:
        return '{}~{}'.format(course_id, item_id)
    elif resp.status_code == 500:
        raise InternalError()
    return resp.json()['elements'][0]['atomId']

def publish_item(
        oauth2_instance,
        publish_endpoint,
        publish_action,
        authoring_pa_id,
        write_access_token):

    auth = oauth2_instance.build_authorizer()
    params = {
        "action": publish_action,
        "id": authoring_pa_id
    }
    resp = requests.post(
        publish_endpoint, params=params, json=write_access_token, auth=auth)
    if resp.status_code == 400:
        status = get_executor_status(resp.json())
        if status is None:
            raise ValidationError()
        else:
            raise GraderExecutorError(status)
    elif resp.status_code == 404:
        raise ItemNotFoundError(course_id, item_id)
    elif resp.status_code in (409, 500):
        raise InternalError()

def get_executor_status(resp_body):
    try:
        return resp_body['details'][0]['status']
    except KeyError:
        return None

def parser(subparsers):
    "Build an argparse argument parser to parse the command line."
    # create the parser for the publish command.
    parser_publish = subparsers.add_parser(
        'publish',
        help='Publish ALL changes made to a programming assignment.')

    parser_publish.set_defaults(func=command_publish)

    parser_publish.add_argument(
        'course',
        help='The id of the course containing the assignment to publish.')

    parser_publish.add_argument(
        'item',
        help='The id of the assignment to publish.')

    parser_publish.add_argument(
        '--additional-items',
        nargs='+',
        help='The next two args specify an item ID which will also be '
             'published.')

    parser_publish.add_argument(
        '--get-endpoint',
        default='https://api.coursera.org/api/'
                'authoringProgrammingAssignments.v2',
        help='Override the endpoint used to get the assignment (draft)')

    parser_publish.add_argument(
        '--publish-endpoint',
        default='https://api.coursera.org/api/'
                'authoringProgrammingAssignments.v2',
        help='Override the endpoint used to publish the assignment (draft)')

    parser_publish.add_argument(
        '--publish-action',
        default='publish',
        help='The name of the Naptime action used to publish the assignment')

    return parser_publish


text:
/*!
 * Module Requirements
 */

var breeze = require('breeze')
  , fs = require('fsagent')
  , inherits = require('util').inherits
  , path = require('path')

/*!
 * Folio Requirements
 */

var Base = require('./base')
  , browser = require('./requires/includes/require');

/*!
 * Primary Export
 */

module.exports = Requires;

function Requires () {
  Base.call(this);
  this.name = 'requires';
}

/*!
 * Inherit from Base
 */

inherits(Requires, Base);

/*!
 * Expose the Api
 */

Requires.prototype.handle = function () {
  var self = this
    , api = {}

  // helper function
  function mountable (key) {
    return function (val) {
      self.attrs[key] = val;
      return this;
    }
  }

  /**
   * ### .package (name)
   *
   * Note the main export to expose for this
   * package.
   *
   * @param {String} name
   * @returns api for chaining
   * @name package
   * @api public
   */

  api.package = mountable('package');

  /**
   * ### .dir (name)
   *
   * Set the starting point directory to traverse
   * for required files. If a relative path is given,
   * it was be resolved from glossary root.
   *
   * @param {String} name
   * @returns api for chaining
   * @name dir
   * @api public
   */

  api.dir = mountable('dir');

  /**
   * ### .entry (name)
   *
   * Set the entry point for the module. An alias
   * will be created from this file to the package
   * name.
   *
   * @param {String} name
   * @returns api for chaining
   * @name entry
   * @api public
   */

  api.entry = mountable('entry');

  /**
   * ### .header (toggle)
   *
   * Toggle whether the common JS header should
   * be included in this pass. Defaults
   * to true.
   *
   * @param {Boolean} toggle
   * @returns api for chaining
   * @name header
   * @api public
   */

  api.header = mountable('header');

  /**
   * ### .ignore (file)
   *
   * Add a file to the ignore list. Files are
   * resolved relative to the required `dir`.
   *
   * @param {String} file path
   * @returns api for chaining
   * @name ignore
   * @api public
   */

  api.ignore = function (file) {
    var ignore = self.attrs.ignore || (self.attrs.ignore = []);
    ignore.push(file);
    return this;
  };

  /**
   * ### .replace (from, to)
   *
   * Replace `require` calls from in each
   * file `from` path `to` path.
   *
   * @param {String} from file
   * @param {String} to file
   * @returns api for chaining
   * @name replace
   * @api public
   */

  api.replace = function (from, to) {
    var replace = self.attrs.replace || (self.attrs.replace = []);
    from = from.replace(/\//g, '\\\/');
    replace.push({
        from: new RegExp("require\\('" + from + "'\\)", "g")
      , to: "require('" + to + "')"
    });
    return this;
  };

  /**
   * ### .pop ()
   *
   * Return to the glossary.
   *
   * @returns Glossary
   * @name pop
   * @api public
   */

  api.pop = this.pop.bind(this);

  return api;
};

/*!
 * ### .compile (string, logger, callback)
 *
 * Read in a directory tree of the provided directory.
 * Remove an ignores, replace any require replacements,
 * and wrap in browser commonjs require loader. Include
 * the common js header if needed.
 *
 * @param {String} string of incoming source
 * @param {Object} logger
 * @param {Function} callback
 * @cb Error or null
 * @cb transformed string
 * @name compile
 * @api public
 */

Requires.prototype.compile = function (str, log, cb) {
  var self = this
    , dir = this.attrs.dir
    , root = this.glossary._attrs.root;

  log.search('#{dir}', { dir: dir });

  // normalize our paths
  if (!fs.isPathAbsolute(dir)) {
    dir = path.resolve(root, dir);
  }

  // get recursive file listing
  fs.tree(dir, function (err, res) {
    if (err) return cb(err);

    // make sure file isn't ignore
    function checkIgnore (file) {
      var res = true
        , ignore = self.attrs.ignore || [];

      ignore.forEach(function (ig) {
        var full = !fs.isPathAbsolute(ig)
          ? path.resolve(dir, ig)
          : ig;
        if (~file.indexOf(full)) {
          res = false;
          log.ign('#{file}', {
              file: file.replace(root, '.')
          });
        }
      });

      return res;
    }

    // sort alphabetically
    res.sort();

    // prepare our file names
    res = res
      .filter(function (file) {
        var ext = path.extname(file).toLowerCase()
        if (ext !== '.js') return false;
        return checkIgnore(file);
      })
      .map(function (file) {
        return {
            req: file.replace(dir + '/', '')
          , file: file
        };
      });

    var buf = str;

    // include commonJS require header
    if (self.attrs.header !== false) {
      log.inc('[[ requires header ]](blue)');
      buf += '\n' + browser.require + '\n\n';
      buf += 'require.modules = {};\n\n';
      buf += 'require.resolve = ' + browser.resolve + ';\n\n';
      buf += 'require.register = ' + browser.register + ';\n\n';
      buf += 'require.relative = ' + browser.relative + ';\n\n';


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using QuantConnect.Indicators;
using QuantConnect.Orders;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
    public class Sig10Strategy : BaseStrategy
    {
        #region "fields"

        private bool bReverseTrade = false;
        public decimal RevPct = 1.0015m;
        private decimal _lossThreshhold = -50;
        private decimal _tolerance = -.001m;
        private int _period;     // used to size the length of the trendArray
        private Indicator _price;
        public InstantaneousTrend Trend;
        public Momentum TrendMomentum;
        public RollingWindow<decimal> MomentumWindow;
        public bool IsActive = true;
        public int TradeAttempts = 0;
        public OrderStatus Status = OrderStatus.None;
        public string comment = string.Empty;
        private SecurityHolding _holding;

        #endregion
        #region "Properties"
        /// <summary>
        /// The symbol being processed
        /// </summary>
        public Symbol symbol { get; set; }

        public int Id { get; set; }
        /// <summary>
        /// The entry price from the last trade, set from the outside
        /// </summary>
        public decimal nEntryPrice { get; set; }

        /// <summary>
        /// The crossover carried from one instance to the next via serialization
        /// set to 1 when (nTrig Greater Than the current trend)
        /// set to -1 when (nTrig less than the current trend)
        /// It needs to be public because it is Serialized
        /// </summary>
        public int xOver { get; set; }

        /// <summary>
        /// The trigger use in the decision process
        /// Used internally only, not serialized or set from the outside
        /// </summary>
        public decimal nTrig { get; set; }
        /// <summary>
        /// True if the the order was filled in the last trade.  Mostly used after Limit orders
        /// It needs to be public because it is set from the outside by checking the ticket in the Transactions collection
        /// </summary>
        public Boolean orderFilled { get; set; }
        /// <summary>
        /// A flag to disable the trading.  True means make the trade.  This is left over from the
        /// InstantTrendStrategy where the trade was being made in the strategy.
        /// </summary>
        //public Boolean maketrade { get; set; }
        /// <summary>
        /// The array used to keep track of the last n trend inputs
        /// It works like a RollingWindow by pushing down the [0] to [1] etc. before updating the [0]
        /// </summary>
        public decimal[] trendArray { get; set; }
        /// <summary>
        /// The bar count from the algorithm
        /// This is set each time through to the barcount in the algorithm
        /// </summary>
        public int Barcount { get; set; }
        /// <summary>
        /// The state of the portfolio.  This is pushed in each time it is run from the Portfolio
        /// it is not Serialized.
        /// </summary>
        public bool IsShort { get; set; }
        /// <summary>
        /// The state of the portfolio.  This is pushed in each time it is run from the Portfolio
        /// </summary>
        public bool IsLong { get; set; }
        /// <summary>
        /// Internal state variables.  This POCO is used to report the internal state of the Signal.
        /// </summary>
        public SigC sigC { get; set; }

        public decimal UnrealizedProfit { get; set; }

        private bool BarcountLT4 { get; set; }
        private bool NTrigLTEP { get; set; }
        private bool NTrigGTEP { get; set; }
        private bool NTrigGTTA0 { get; set; }
        private bool NTrigLTTA0 { get; set; }
        private bool ReverseTrade { get; set; }
        private bool xOverIsPositive { get; set; }
        private bool xOverisNegative { get; set; }
        private bool OrderFilled { get; set; }

        #endregion

        public Sig10Strategy(SecurityHolding sym, Indicator priceIdentity, int trendPeriod, decimal lossThreshhold, decimal tolerance, decimal revertPct)
        {

            trendArray = new decimal[trendPeriod + 1];       // initialized to 0.  Add a period for Deserialize to make IsReady true

            symbol = sym.Symbol;
            _holding = sym;
            _price = priceIdentity;
            _period = trendPeriod;
            _lossThreshhold = lossThreshhold;
            _tolerance = tolerance;
            RevPct = revertPct;
            Trend = new InstantaneousTrend(sym.Symbol.Value, 7, .24m).Of(priceIdentity);
            TrendMomentum = new Momentum(2).Of(Trend);
            MomentumWindow = new RollingWindow<decimal>(2);
            ActualSignal = OrderSignal.doNothing;

            Trend.Updated += (object sender, IndicatorDataPoint updated) =>
            {
                Barcount++;
                UpdateTrendArray(Trend.Current.Value);
                nTrig = Trend.Current.Value;
                if (Trend.IsReady)
                {
                    TrendMomentum.Update(Trend.Current);
                }
                if (TrendMomentum.IsReady)
                    MomentumWindow.Add(TrendMomentum.Current.Value);
                if (MomentumWindow.IsReady)
                    CheckSignal();
            };
        }

        public override void CheckSignal()
        {
            ActualSignal = OrderSignal.doNothing;
            if (Barcount < 4)
            {
                BarcountLT4 = true;
                comment = "Barcount < 4";
                nTrig = Trend.Current.Value;
                ActualSignal = OrderSignal.doNothing;
            }
            else
            {
                nTrig = 2m * trendArray[0] - trendArray[2];

                IsShort = _holding.IsShort;
                IsLong = _holding.IsLong;

                #region "Selection Logic Reversals"

                ActualSignal = CheckLossThreshhold(ref comment, ActualSignal);
                if (Barcount>17)
                    Debug.WriteLine("Bar count > 17");

                if (nTrig < (Math.Abs(nEntryPrice) / RevPct))
                {
                    NTrigLTEP = true;
                    if (IsLong)
                    {
                        ActualSignal = OrderSignal.revertToShort;
                        bReverseTrade = true;
                        ReverseTrade = true;
                        comment =
                            string.Format("nTrig {0} < (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )",
                                Math.Round(nTrig, 4),
                                nEntryPrice,
                                RevPct,
                                NTrigLTEP,
                                IsLong);
                    }
                    else
                    {
                        NTrigLTEP = false;
                    }
                }
                else
                {
                    if (nTrig > (Math.Abs(nEntryPrice) * RevPct))
                    {
                        NTrigGTEP = true;
                        if (IsShort)
                        {
                            ActualSignal = OrderSignal.revertToLong;
                            bReverseTrade = true;
                            ReverseTrade = true;
                            comment =
                                string.Format("nTrig {0} > (nEntryPrice {1} * RevPct {2}) {3} IsLong {4} )",
                                    Math.Round(nTrig, 4),
                                    nEntryPrice,
                                    RevPct,
                                    NTrigLTEP,
                                    IsLong);
                        }
                        else
                        {
                            NTrigGTEP = false;
                        }
                    }
                }

                #endregion
                #region "selection logic buy/sell"

                ActualSignal = CheckLossThreshhold(ref comment, ActualSignal);

                if (!bReverseTrade)
                {

                    if (nTrig > trendArray[0])
                    {
                        NTrigGTTA0 = true;
                        if (xOver == -1)
                        {
                            #region "If Not Long"
                            if (!IsLong)
                            {

                                if (!orderFilled)
                                {
                                    ActualSignal = OrderSignal.goLong;
                                    comment =
                                        string.Format(
                                            "nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}",
                                            Math.Round(nTrig, 4),
                                            Math.Round(trendArray[0], 4),
                                            xOver,
                                            !IsLong,
                                            !orderFilled);
                                }
                                else
                                {
                                    ActualSignal = OrderSignal.goLongLimit;
                                    comment =
                                        string.Format(
                                            "nTrig {0} > trend {1} xOver {2} !IsLong {3} !orderFilled {4}",
                                            Math.Round(nTrig, 4),
                                            Math.Round(trendArray[0], 4),
                                            xOver,
                                            !IsLong,
                                            !orderFilled);

                                }
                            }
                            #endregion
                        }

                        if (comment.Length == 0)
                            comment = "Trigger over trend - setting xOver to 1";
                        xOver = 1;
                        xOverisNegative = xOver < 0;
                        xOverIsPositive = xOver > 0;
                    }
                    else
                    {
                        if (nTrig < trendArray[0])
                        {
                            NTrigLTTA0 = true;
                            if (xOver == 1)
                            {
                                #region "If Not Short"
                                if (!IsShort)
                                {
                                    if (!orderFilled)
                                    {
                                        ActualSignal = OrderSignal.goShort;
                                        comment =
                                            string.Format(
                                                "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}",
                                                Math.Round(nTrig, 4),
                                                Math.Round(trendArray[0], 4),
                                                xOver,
                                                !IsShort,
                                                !orderFilled);

                                    }
                                    else
                                    {
                                        ActualSignal = OrderSignal.goShortLimit;
                                        comment =
                                            string.Format(
                                                "nTrig {0} < trend {1} xOver {2} !isShort {3} orderFilled {4}",
                                                Math.Round(nTrig, 4),
                                                Math.Round(trendArray[0], 4),
                                                xOver,
                                                !IsShort,
                                                !orderFilled);

                                    }
                                }
                                #endregion
                            }
                            if (comment.Length == 0)
                                comment = "Trigger under trend - setting xOver to -1";
                            xOver = -1;
                            xOverisNegative = xOver < 0;
                            xOverIsPositive = xOver > 0;
                        }

                    }
                }

                #endregion

            }

        }
        private void UpdateTrendArray(decimal trendCurrent)
        {
            for (int i = trendArray.Length - 2; i >= 0; i--)
            {
                trendArray[i + 1] = trendArray[i];
            }
            trendArray[0] = trendCurrent;
        }

        private OrderSignal CheckLossThreshhold(ref string comment, OrderSignal retval)
        {
            //if (Barcount >= 376)
            //    System.Diagnostics.Debug.WriteLine("Barcount: " + Barcount);
            if (UnrealizedProfit < _lossThreshhold)
            {
                if (IsLong)
                {
                    retval = OrderSignal.goShortLimit;

                }
                if (IsShort)
                {
                    retval = OrderSignal.goLongLimit;

                }
                comment = string.Format("Unrealized loss exceeded {0}", _lossThreshhold);
                bReverseTrade = true;
            }
            return retval;
        }

        /// <summary>
        /// Convenience function which creates an IndicatorDataPoint
        /// </summary>
        /// <param name="time">DateTime - the bar time for the IndicatorDataPoint</param>
        /// <param name="value">decimal - the value for the IndicatorDataPoint</param>
        /// <returns>a new IndicatorDataPoint</returns>
        /// <remarks>I use this function to shorten the a Add call from
        /// new IndicatorDataPoint(this.Time, value)
        /// Less typing.</remarks>
        private IndicatorDataPoint idp(DateTime time, decimal value)
        {
            return new IndicatorDataPoint(time, value);
        }
    }
}


text:
package org.springframework.test.web.servlet.setup;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * The main class to import to access all available {@link MockMvcBuilder}s.
 *
 *
Eclipse users: consider adding this class as a Java editor
 * favorite. To navigate, open the Preferences and type "favorites".
 *
 * @author Rossen Stoyanchev
 * @since 3.2
 */
public class MockMvcBuilders {

	/**
	 * Build a {@link MockMvc} using the given, fully initialized, i.e.
	 * refreshed, {@link WebApplicationContext}. The {@link DispatcherServlet}
	 * will use the context to discover Spring MVC infrastructure and
	 * application controllers in it. The context must have been configured with
	 * a {@link ServletContext}.
	 */
	public static DefaultMockMvcBuilder webAppContextSetup(WebApplicationContext context) {
		return new DefaultMockMvcBuilder(context);
	}

	/**
	 * Build a {@link MockMvc} by registering one or more {@code @Controller}'s
	 * instances and configuring Spring MVC infrastructure programmatically.
	 * This allows full control over the instantiation and initialization of
	 * controllers, and their dependencies, similar to plain unit tests while
	 * also making it possible to test one controller at a time.
	 *
	 *
When this option is used, the minimum infrastructure required by the
	 * {@link DispatcherServlet} to serve requests with annotated controllers is
	 * automatically created, and can be customized, resulting in configuration
	 * that is equivalent to what the MVC Java configuration provides except
	 * using builder style methods.
	 *
	 *
If the Spring MVC configuration of an application is relatively
	 * straight-forward, for example when using the MVC namespace or the MVC
	 * Java config, then using this builder might be a good option for testing
	 * a majority of controllers. A much smaller number of tests can be used
	 * to focus on testing and verifying the actual Spring MVC configuration.
	 *
	 * @param controllers one or more {@link Controller @Controller}'s to test
	 */
	public static StandaloneMockMvcBuilder standaloneSetup(Object... controllers) {
		return new StandaloneMockMvcBuilder(controllers);
	}

}


text:
package com.coolweather.android.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by 李宁 on 2017/7/3.
 */

public class HttpUtil {
    public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
        OkHttpClient client =new OkHttpClient();
        Request request=new Request.Builder().url(address).build();
        client.newCall(request ).enqueue(callback);
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Jb. 17: (1893)

#### Original name
Schenckiella marcgraviae Henn., 1893

### Remarks
null


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Commelina acuminata (R.Br.) Poir.

### Remarks
null


text:
namespace AVRDisassembler.InstructionSet.OpCodes.Bits
{
    public class SES : OpCode
    {
        public override string Comment => "Set Signed Flag";
    }
}


text:
<?php
// Config file for 'development' environment
return array(
    "display_errors" => true,
    "index_file" => "",
    "profiler_enabled"=>true,
    "modules" => array(
        "demo"=>array()
    )
);


text:
package eu.openanalytics.rsb.message;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

import java.util.GregorianCalendar;
import java.util.Map;
import java.util.UUID;

import org.junit.Before;
import org.junit.Test;

import eu.openanalytics.rsb.Util;
import eu.openanalytics.rsb.message.AbstractWorkItem.Source;

/**
 * @author "Open Analytics <rsb.development@openanalytics.eu>"
 */
public class JsonFunctionCallJobTestCase
{

    private JsonFunctionCallJob jsonFunctionCallJob;

    @Before
    public void prepareTest()
    {
        jsonFunctionCallJob = new JsonFunctionCallJob(Source.REST, "appName", null, UUID.randomUUID(),
            (GregorianCalendar) GregorianCalendar.getInstance(), "\\\"fake_job\\\"");
    }

    @Test
    public void getFunctionName()
    {
        assertThat(jsonFunctionCallJob.getFunctionName(), notNullValue());
    }

    @Test
    public void buildSuccessResultString()
    {
        final JsonFunctionCallResult xmlFunctionCallResult = jsonFunctionCallJob.buildSuccessResult("\\\"fake_result\\\"");
        assertThat(xmlFunctionCallResult, notNullValue());
        assertThat(xmlFunctionCallResult.isSuccess(), is(true));
    }

    @Test
    public void buildErrorResultThrowable() throws Exception
    {
        final JsonFunctionCallResult xmlFunctionCallResult = jsonFunctionCallJob.buildErrorResult(
            new RuntimeException("simulated error"), null);
        assertThat(xmlFunctionCallResult, notNullValue());
        assertThat(xmlFunctionCallResult.isSuccess(), is(false));
        assertThat(Util.fromJson(xmlFunctionCallResult.getPayload(), Map.class), notNullValue());
    }
}


text:
{-# OPTIONS_GHC -Wall  #-}
{-# LANGUAGE ExplicitForAll #-}

module QuickCover.FeatureBased   where

import Test.QuickCheck (quickCheckWithResult,Property,property,chatty
                       ,Result(Failure),Arbitrary,stdArgs,maxSuccess
                       ,counterExamples)
import Test.QuickCheck.Property (morallyDubiousIOProperty,noShrinking)
import Data.IORef (readIORef,writeIORef)
import Data.Set as Set (Set,empty,isSubsetOf,union,insert,fromList)
import Control.DeepSeq(deepseq,NFData)
import Data.Function (on)
import QuickCover.GroupRec (groupRecBy)
import QuickCover.Log (logger,isLogging)

prop_feature :: (Ord c) => ((a -> Maybe Bool) -> a -> IO b) ->
                (b -> IO (Set c))-> Set c -> (a -> Maybe Bool) ->
                a -> Property
prop_feature feature postProcess s pf ce = morallyDubiousIOProperty $ do
 features <- postProcess =<< feature pf ce
 return $ property $ features `isSubsetOf` s

performFeatureBased :: (Ord c, Ord a, Read a, Arbitrary a,Show a) =>
                       ((a -> Maybe Bool) -> a -> IO b)
                       -> (b -> IO (Set c)) -> Bool -> Int -> (a -> Maybe Bool)
                       -> IO (Set a)
performFeatureBased = performFeatureBased' empty empty

performFeatureBased' :: (Ord c, Ord a, Read a, Arbitrary a,Show a) =>
   Set c -> Set a  -> ((a -> Maybe Bool) -> a -> IO b)
   -> (b -> IO (Set c)) -> Bool -> Int -> (a -> Maybe Bool)
   -> IO (Set a)
performFeatureBased' s xs feature postProcess shrinking n pf = do
  r <- quickCheckWithResult stdArgs{chatty=False,maxSuccess=n}
       ((if shrinking then id else noShrinking) .
        prop_feature feature postProcess s pf)
  case r of
    Failure {counterExamples = [ces]} -> do
      let ce = read ces
      features <- postProcess =<< feature pf ce
      performFeatureBased' (features `union` s) (ce `insert` xs)
        feature postProcess shrinking n pf
    _                                 -> return xs

-- collects program points (with their values optionally) as features
pp_feature :: (NFData a) =>
              (a -> Maybe Bool) -> a -> IO [(Int,Maybe String)]
pp_feature pf x = do
  deepseq x $ deepseq pf $ writeIORef logger []
  writeIORef isLogging True
  let pfx = pf x
  r <- deepseq (pfx) $ readIORef logger
  writeIORef isLogging False
  return $ case pfx of
    Nothing -> []
    _       -> reverse r

data Coverage = Node
              | NodeValue
              | Path
              | PathValue
                deriving (Read,Show)

featureBased :: (Ord a, Read a, Arbitrary a, NFData a,Show a) => Coverage
                -> Bool -> Int -> (a -> Maybe Bool) -> IO (Set a)
featureBased Node      = performFeatureBased pp_feature  (return . node)
featureBased NodeValue = performFeatureBased pp_feature  (return . nodeValue)
featureBased Path      = performFeatureBased pp_feature  (return . path)
featureBased PathValue = performFeatureBased pp_feature  (return . pathValue)

node :: [(Int, Maybe String)] -> Set Int
node = fromList . map fst

nodeValue :: [(Int, Maybe String)] -> Set (Int, Maybe String)
nodeValue = fromList

{-
-- seems non-terminating
path :: [(Int, Maybe String)] -> Set [Int]
path = singleton . (map fst)

-- seems non-terminating
pathValue :: [(Int, Maybe String)] -> Set [(Int, Maybe String)]
pathValue = singleton
-}

path :: [(Int, Maybe String)] -> Set [Int]
path = groupRecBy (==) . fmap fst

pathValue :: [(Int, Maybe String)] -> Set [(Int, Maybe String)]
pathValue = groupRecBy ((==) `on` fst)


text:
package org.neo4j.cypher.internal.compiler.v2_3.planner.logical

import org.neo4j.cypher.internal.compiler.v2_3.planner.QueryGraph
import org.neo4j.cypher.internal.compiler.v2_3.planner.logical.greedy.projectEndpoints
import org.neo4j.cypher.internal.compiler.v2_3.planner.logical.plans.LogicalPlan
import org.neo4j.cypher.internal.compiler.v2_3.planner.logical.steps._
import org.neo4j.cypher.internal.compiler.v2_3.planner.logical.steps.solveOptionalMatches.OptionalSolver

object QueryPlannerConfiguration {
  val default = QueryPlannerConfiguration(
    pickBestCandidate = pickBestPlanUsingHintsAndCost,
    applySelections = Selector(pickBestPlanUsingHintsAndCost,
      selectPatternPredicates,
      triadicSelectionFinder,
      selectCovered,
      selectHasLabelWithJoin
    ),
    projectAllEndpoints = projectEndpoints.all,
    optionalSolvers = Seq(
      applyOptional,
      outerHashJoin
    ),
    leafPlanners = LeafPlannerList(
      argumentLeafPlanner,

      // MATCH n WHERE id(n) IN ... RETURN n
      idSeekLeafPlanner,

      // MATCH n WHERE n.prop IN ... RETURN n
      uniqueIndexSeekLeafPlanner,

      // MATCH n WHERE n.prop IN ... RETURN n
      indexSeekLeafPlanner,

      // MATCH n WHERE has(n.prop) RETURN n
      indexScanLeafPlanner,

      // MATCH (n:Person) RETURN n
      labelScanLeafPlanner,

      // MATCH n RETURN n
      allNodesLeafPlanner,

      // Legacy indices
      legacyHintLeafPlanner
    )
  )
}

case class QueryPlannerConfiguration(leafPlanners: LeafPlannerList,
                                     applySelections: PlanTransformer[QueryGraph],
                                     projectAllEndpoints: PlanTransformer[QueryGraph],
                                     optionalSolvers: Seq[OptionalSolver],
                                     pickBestCandidate: LogicalPlanningFunction0[CandidateSelector]) {

  def toKit()(implicit context: LogicalPlanningContext): QueryPlannerKit =
    QueryPlannerKit(
      select = (plan: LogicalPlan, qg: QueryGraph) => applySelections(plan, qg),
      projectAllEndpoints = (plan: LogicalPlan, qg: QueryGraph) => projectAllEndpoints(plan, qg),
      pickBest = pickBestCandidate(context)
    )
}

case class QueryPlannerKit(select: (LogicalPlan, QueryGraph) => LogicalPlan,
                           projectAllEndpoints: (LogicalPlan, QueryGraph) => LogicalPlan,
                           pickBest: CandidateSelector) {
  def select(plans: Iterable[Seq[LogicalPlan]], qg: QueryGraph): Iterable[Seq[LogicalPlan]] =
    plans.map(_.map(plan => select(plan, qg)))
}


text:
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="description" content="">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, target-densitydpi=medium-dpi" />
        <title>One More Check-In</title>
        <!--
        In case of emergency, revert to 2.0.1, or another straight normalize instead of burnscars
        <link rel="stylesheet" type="text/css" href="js/normalize/2.1.1/normalize.css" />
        <link rel="stylesheet" type="text/css" href="js/normalize/master/normalize.css" />
        <link rel="stylesheet" type="text/css" href="js/spitfire/1.1.0/burnscars.css" />
        -->
        <link rel="stylesheet" type="text/css" href="js/normalize/2.0.1/normalize.css" />

        <link rel="stylesheet" type="text/css" href="css/app.css" />
        <link rel="stylesheet" type="text/css" href="fonts/pictos.css" />
        <meta name="format-detection" content="telephone=no">
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    </head>
    <body>
      <!-- External dependencies -->
        <script type="text/javascript" src="js/spitfire/1.1.0/burnscars.js"></script>
        <!--
        <script type="text/javascript" src="js/spitfire/master/burnscars.js"></script>
        -->
        <script type="text/javascript" src="js/zepto/1.0rc1/zepto.js"></script>
        <!--
        <script type="text/javascript" src="js/zepto/1.0/zepto.js"></script>
        <script type="text/javascript" src="js/zepto/master/zepto.js"></script>
        -->
        <script type="text/javascript" src="js/handlebars/1.0.rc.1/handlebars.runtime.js"></script>
        <!--
        <script type="text/javascript" src="js/handlebars/1.0.10/handlebars.runtime.js"></script>
        <script type="text/javascript" src="js/handlebars/master/handlebars.runtime.js"></script>
        -->

      <!-- Application -->
        <script type="text/javascript" src="js/phonegap.js"></script>
        <script type="text/javascript" src="js/templates.js"></script>

        <script type="text/javascript" src="js/phoneapp/0.1.0/phoneapp.js"></script>
        <!--
        <script type="text/javascript" src="js/phoneapp/master/phoneapp.js"></script>
        -->

        <script type="text/javascript" src="js/app.js"></script>
        <script type="text/javascript">
            Omci.initialize();
        </script>
    </body>
</html>


text:
/*
description: Search main code includes reading the pageRank and calculating the text matchValue.
input: pattern  _The search pattern
       PageRankMap  _<key,value> is <url, pageRank>
       parse_text _Text includes url and the parse text in the url page, separated by '\t'.
output: searchResult _Text includes the url and its weight.
Mapper: <null, url and parse_text> --> <weight, url>
Reducer: <weight, url> --> sorted <weight, url>
*/
//package org.apache.hadoop.mapred;
package SearchPackage;

import java.io.IOException;
import java.net.URI;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.MapFile.Reader;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import org.apache.nutch.parse.ParseText;

public class Search {

  private static String pattern = null;
  private static MapFileRead pageRankRead = null;

  public static class TextMatcher {
   /* private String pattern;
    private String text;
    public double matchVal;

    public TextMatcher(String pattern, String text) {
      this.pattern = pattern;
      this.text = text;
      this.matchVal = 0;
    }*/

    public static double calcMatchVal(String text, String Pattern) throws IOException, InterruptedException {
      int patternLen = pattern.length();
      int textLen = text.length();
      int tmpTextLen = 0;	//匹配的部分字符串在Text的总长度
      int tmpPatternLen = 0;		//除去前面完全匹配的匹配字符个数
      double matchVal = 0;

      for(int i = 0; i < textLen; i++) {
	tmpTextLen++;
	if(text.charAt(i) == pattern.charAt(tmpPatternLen)) {
	  tmpPatternLen++;
	  if(tmpPatternLen == 1) {
	    tmpTextLen = 1;
	  }
	  if(tmpPatternLen == patternLen || tmpTextLen == 3*patternLen) {
          //当匹配完成或者匹配了一定数量的字符仍然没有匹配成功则计算当前匹配值
	    matchVal += ((double)tmpPatternLen)/((double)tmpTextLen);
	    tmpPatternLen = 0;
	  }
	}
      }
      return matchVal;
    }
  }

  public static class SearchMapper extends Mapper<LongWritable, Text, DoubleWritable, Text> {

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
      String text = value.toString();
      String url = new String();
      int i = 0;
      while(text.charAt(i) != ' ') {
        url = url+text.charAt(i);
        i++;
      }
      text = text.substring(++i,text.length());
      double urlMatchVal = TextMatcher.calcMatchVal(url, pattern);
      double textMatchVal = TextMatcher.calcMatchVal(text, pattern);
      double pageRank = pageRankRead.getValue(url);
      double urlWeight = Math.pow(urlMatchVal*10+textMatchVal, pageRank)+pageRank*1000;
      context.write(new DoubleWritable(urlWeight), new Text(url));
    }
  }

  public static class SearchReducer extends Reducer<DoubleWritable, Text, DoubleWritable, Text> {
    public void reduce(DoubleWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
      for(Text value : values) {
        context.write(key, value);
      }
    }
  }

  public static void main(String[] args) throws Exception {
    if(args.length != 3) {
      System.err.println("Usage: Search <input> <output> <pattern>");
      System.exit(-1);
    }

    Configuration conf = new Configuration();
    Job job = new Job(conf,"Search");
    job.setJarByClass(Search.class);

    FileInputFormat.addInputPath(job, new Path(args[0]));
    FileOutputFormat.setOutputPath(job, new Path(args[1]));
    pattern = args[2];

    job.setMapperClass(SearchMapper.class);
    job.setReducerClass(SearchReducer.class);
    job.setOutputKeyClass(DoubleWritable.class);
    job.setOutputValueClass(Text.class);

    job.setNumReduceTasks(1);

    pageRankRead = new MapFileRead("hdfs://localhost/input/PageRankMap");
    job.waitForCompletion(true);
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<artifactId>drools-examples</artifactId>
		<groupId>com.github.calcacuervo</groupId>
		<version>1.0-SNAPSHOT</version>
	</parent>
	<groupId>com.github.calcacuervo</groupId>
	<artifactId>models</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>models</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>org.kie</groupId>
			<artifactId>kie-api</artifactId>
		</dependency>
	</dependencies>
</project>