text:
module VerilogGen

  # Check if all the ports in the list are inputs.
  # @param [Array] port_lst is the list of ports
  # @return [Boolean] True if all are inputs.
  def self.unconnected_input_ports?(port_lst)
    return false if port_lst.empty?
    port_lst.each do |port|
      return false unless port.direction == "input"
    end
    return true
  end

  # Check if all the ports in the list are outputs.
  # @param [Array] port_lst is the list of ports
  # @return [Boolean] True if all are outputs.
  def self.unconnected_output_ports?(port_lst)
    return false if port_lst.empty?
    port_lst.each do |port|
      return false unless port.direction == "output"
    end
    return true
  end

  # Find the super width from a list of ports.
  # @param [Array] list of ports
  # @return [Array] lhs, rhs
  # @note:
  #     Assumes that all ports in the list are of same endiannes..
  #     FIXME: For this it looks at the port in the middle.
  #     Should scan all the ports to detect it.
  def self.super_port_width(port_lst)
    sample_port = port_lst[port_lst.size/2]
    lhs_values = []
    rhs_values = []
    port_lst.each do |port|
      lhs_values << port.lhs
      rhs_values << port.rhs
    end
    if sample_port.lhs > sample_port.rhs
      return lhs_values.max, rhs_values.min
    else
      return lhs_values.min, rhs_values.max
    end
  end

  # Adds a connect port to the hdl module class.
  # @return nil
  # @note The name of the connect port is the name of the pin
  #       and the width of the port is the super width.
  def self.add_new_connect_port(klass, pin_name, port_lst)
    lhs, rhs = super_port_width(port_lst)
    p = port_lst[0].create_connect_port(pin_name, lhs, rhs)
    klass.ports[pin_name] = p
  end

  # Create pins for unconnected ports in current instance.
  # @param [Object] instance of hdl module
  # @return [Fixnum] Number of pins added
  # @note Ports with existing pins are skippped.
  def self.create_missing_pins(instance)
    num_pins_created = 0
    instance.class.ports.each do |port_name, port|
      unless instance.pins.key? port_name
        instance.pins[port_name] = Pin.new(port)
        num_pins_created += 1
      end
    end
    num_pins_created
  end

  # Create  missing pins for all children below the instance.
  # Use depth first to build all the leaf and then the rest of the
  # modules.
  # @param [Object] instance of the design.
  # @return [nil]
  # @note Idempotent since port that have pins are skipped.
  def self.create_missing_pins_depth_first(instance)
    if instance.class.proxy
      # Leaf do not change the ports. hence we don't need to do it again.
      # But it is harmless if all ports are already connected.
      create_missing_pins instance
    else
      instance.class.child_instances.each do |child_name, child|
        create_missing_pins_depth_first child
      end
      # If new pins are created then we would need to create the connect ports
      # in the current class.
      num_new_ports = create_connect_ports(instance.class)

      # Run custom user connect
      instance.class.connect

      # If we added new ports to the class then all instantiaton must get new pins.
      create_missing_pins instance if num_new_ports > 0
    end
  end

  # Create connectivity map for children of a hdl module.
  # @param [Object] klass of the hdl module.
  # @return [Hash] hash of array. PinName => [Port0, Port 10.....]
  #
  def self.get_child_pins_connectivity(klass)
    pin_connections = Hash.new {|hash, key| hash[key] = Array.new }
    klass.child_instances.each do |child_name, child|
      child.pins.each do |port_name, pin|
        pin_connections[pin.name].push pin.port
      end
    end
    pin_connections
  end

  # Create ports to provide connectivity to the child instances.
  # @param [Object] klass HdlModule
  # @return [Fixnum] number of ports created in the class.
  # @note
  #     An input port is created if the children pins are inputs.
  #     A  output port is created if the children pins are output.
  #     If mixture of input and output pins, then no ports are created.
  #     The width of the port is the superset of the width.
  def self.create_connect_ports(klass)
    num_connect_ports = 0
    pin_connections = get_child_pins_connectivity(klass)
    pin_connections.each do |pin_name, port_lst|
      if unconnected_input_ports?(port_lst)
        add_new_connect_port(klass, pin_name, port_lst)
        num_connect_ports += 1
      elsif unconnected_output_ports?(port_lst)
        add_new_connect_port(klass, pin_name, port_lst)
        num_connect_ports += 1
      end
    end
    num_connect_ports
  end

  # Connect child instances and create hookup ports.
  # @param [Object] top_level_class of the design.
  # @note
  #     Start with each child instance.
  #
  def self.hookup(top_level_class)
    top_level_class.child_instances.each do |instance_name, instance|
      create_missing_pins_depth_first(instance)
    end
    # Run custom user connect
    top_level_class.connect

    # Create the primary connect ports
    create_connect_ports(top_level_class)

  end

end


text:
if [[ $(npm list -g --depth=0 | grep parse-server) ]]
then
  echo "packages are already installed..."
else
  echo "installing npm packages..."
  npm install -g parse-server mongodb-runner parse-dashboard
fi
sudo pip install simplejson
sudo pip install requests

redpajama_set_name: RedPajamaGithub


text:
package com.tech.frontier.net;

import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.tech.frontier.listeners.DataListener;
import com.tech.frontier.models.entities.Article;
import com.tech.frontier.net.handlers.ArticlesHandler;
import com.tech.frontier.net.mgr.RequestQueueMgr;

import org.json.JSONArray;

import java.util.List;

public class ArticleAPIImpl implements ArticleAPI {

    private int mPage = 0;
    ArticlesHandler mJsonHandler = new ArticlesHandler();

    @Override
    public void fetchArticles(final DataListener<List<Article>> listener) {
        performRequest(0, listener);
    }

    @Override
    public void loadMode(DataListener<List<Article>> listener) {
        performRequest(++mPage, listener);
    }

    private void performRequest(final int page, final DataListener<List<Article>> listener) {
        JsonArrayRequest request = new JsonArrayRequest(
                "http://www.devtf.cn/articles.php?page=" + page + "&count=50",
                new Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        if (listener != null) {
                            // 解析结果
                            listener.onComplete(mJsonHandler.parse(jsonArray));
                        }
                    }
                }, null);
        RequestQueueMgr.getRequestQueue().add(request);
    }
}


text:
<?php

namespace Happyr\DoctrineSpecification\Exception;

class InvalidArgumentException extends \InvalidArgumentException
{

}


text:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <map>
#include <vector>
#include <list>
#include <cmath>
#include <cstdint>

#include <signal.h>
#include <unistd.h>

#include "packet_control_interface.h"

#define TEST_DELAY 2000

#define NUM_DEVICES 12u
#define NUM_LEDS NUM_DEVICES
#define NUM_RFS NUM_DEVICES

struct SColor {
   uint8_t Red, Green, Blue;
};

class CRangeFinder {
public:
   CRangeFinder(const std::string& str_path, const std::string& str_prefix, unsigned int un_index) {
      m_strRfBrightnessPath = str_path;
      m_strRfBrightnessPath += (str_prefix + "[" + std::to_string(un_index) + "]/");
      m_strRfBrightnessPath += "brightness";
   }

   uint16_t Read() {
      uint16_t unValue;
      std::ifstream cBrightnessFile(m_strRfBrightnessPath.c_str());
      cBrightnessFile >> unValue;
      return unValue;
   }
public:
   std::string m_strRfBrightnessPath;
};

class CLED {
   public:
      CLED(const std::string& str_path, const std::string& str_prefix, unsigned int un_index) {
         for(const std::string& str_color : {"red", "green", "blue"}) {
            std::string strBrightnessPath(str_path);
            strBrightnessPath += (str_prefix + "[" + std::to_string(un_index) + "]:" + str_color + "/");
            strBrightnessPath += "brightness";

            m_mapBrightnessPaths[str_color] = strBrightnessPath;
         }
      }

      void SetRed(uint8_t un_red) {
         std::ofstream cBrightnessFile(m_mapBrightnessPaths["red"].c_str());
         cBrightnessFile << static_cast<int>(un_red);
      }

      void SetGreen(uint8_t un_green) {
         std::ofstream cBrightnessFile(m_mapBrightnessPaths["green"].c_str());
         cBrightnessFile << static_cast<int>(un_green);
      }

      void SetBlue(uint8_t un_blue) {
         std::ofstream cBrightnessFile(m_mapBrightnessPaths["blue"].c_str());
         cBrightnessFile << static_cast<int>(un_blue);
      }

   private:
      std::map<std::string, std::string> m_mapBrightnessPaths;
   };

class CLEDDeck {
public:
   CLEDDeck() {
      for(unsigned int un_led_idx = 0; un_led_idx < NUM_LEDS; un_led_idx++) {
         m_vecLEDs.emplace_back("/sys/class/leds/", "pca963x:led_deck", un_led_idx + 1);
      }
   }

   void SetColor(unsigned int un_index, const SColor& s_color) {
      CLED& cLED = m_vecLEDs[un_index];
      cLED.SetRed(s_color.Red);
      cLED.SetGreen(s_color.Green);
      cLED.SetBlue(s_color.Blue);
   }

   void SetColor(unsigned int un_index, uint8_t un_red, uint8_t un_green, uint8_t un_blue) {
      CLED& cLED = m_vecLEDs[un_index];
      cLED.SetRed(un_red);
      cLED.SetGreen(un_green);
      cLED.SetBlue(un_blue);
   }

   void SetAllColors(const SColor& s_color) {
      for(CLED& cLED : m_vecLEDs) {
         cLED.SetRed(s_color.Red);
         cLED.SetGreen(s_color.Green);
         cLED.SetBlue(s_color.Blue);
      }
   }

   void SetAllColors(uint8_t un_red, uint8_t un_green, uint8_t un_blue) {
      for(CLED& cLED : m_vecLEDs) {
         cLED.SetRed(un_red);
         cLED.SetGreen(un_green);
         cLED.SetBlue(un_blue);
      }
   }

private:
   std::vector<CLED> m_vecLEDs;
};

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

volatile bool bShutdownSignal = false;

void InteruptSignalHandler(int n_unused) {
   bShutdownSignal = true;
}

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

int main(int n_arg_count, char* ppch_args[]) {
   /* Register the SIGINT handler to shut down system cleanly on abort */
   ::signal(SIGINT, InteruptSignalHandler);

   enum class EActuatorInputLimit : uint8_t {
      LAUTO = 0, L100 = 1, L150 = 2, L500 = 3, L900 = 4
   };

   std::vector<CRangeFinder> vecRangeFinders;
   std::vector<CLED> vecLEDs;

   CPacketControlInterface* m_pcPowerManagementInterface =
      new CPacketControlInterface("power management", "/dev/ttySC0", 57600);

   if(!m_pcPowerManagementInterface->Open()) {
         std::cerr << "Error" << std::endl << "Could not open the device" << std::endl;
         return -ENODEV;
   }

   /* Override actuator input limit to 100mA */
   m_pcPowerManagementInterface->SendPacket(CPacketControlInterface::CPacket::EType::SET_ACTUATOR_INPUT_LIMIT_OVERRIDE,
                                            static_cast<const uint8_t>(EActuatorInputLimit::L100));

   /* Enable the actuator power domain */
   m_pcPowerManagementInterface->SendPacket(CPacketControlInterface::CPacket::EType::SET_ACTUATOR_POWER_ENABLE, true);

   for(unsigned int un_dev_idx = 0; un_dev_idx < NUM_DEVICES; un_dev_idx++) {
      vecRangeFinders.emplace_back("/sys/class/rfs/", "bebot:rf_chassis", un_dev_idx);
      vecLEDs.emplace_back("/sys/class/leds/", "pca963x:led_deck", un_dev_idx);
   }

   /*
   for(unsigned int un_dev_idx = 0; un_dev_idx < NUM_DEVICES; un_dev_idx++) {
      for(int j = 0;  j < 128; j++) {
         vecLEDs[un_dev_idx].SetRed(j);
         usleep(TEST_DELAY);
      }
      for(int j = 128;  j > 0; j--) {
         vecLEDs[un_dev_idx].SetRed(j);
         usleep(TEST_DELAY);
      }
      for(int j = 0;  j < 128; j++) {
         vecLEDs[un_dev_idx].SetGreen(j);
         usleep(TEST_DELAY);
      }
      for(int j = 128;  j > 0; j--) {
         vecLEDs[un_dev_idx].SetGreen(j);
         usleep(TEST_DELAY);
      }for(int j = 0;  j < 128; j++) {
         vecLEDs[un_dev_idx].SetBlue(j);
         usleep(TEST_DELAY);
      }
      for(int j = 128;  j > 0; j--) {
         vecLEDs[un_dev_idx].SetBlue(j);
         usleep(TEST_DELAY);
      }
   }
   */

   while(!bShutdownSignal) {
      std::vector<std::list<uint16_t>> vecReadings(NUM_DEVICES);

      for(unsigned int un_dev_idx = 0; un_dev_idx < NUM_DEVICES; un_dev_idx++) {
         vecReadings[un_dev_idx].push_front(vecRangeFinders[un_dev_idx].Read());
         if(vecReadings[un_dev_idx].size() > 5) {
            vecReadings[un_dev_idx].pop_back();
         }

         std::list<uint16_t> lstReadings;
         std::copy(std::begin(vecReadings[un_dev_idx]),
                   std::end(vecReadings[un_dev_idx]),
                   std::begin(lstReadings));

         lstReadings.sort();

         std::list<uint16_t>::iterator itMedianReading = std::begin(lstReadings);
         std::advance(itMedianReading, static_cast<size_t>(lstReadings.size() / 2.0f));

         float fAverageRaw = static_cast<float>(*itMedianReading);

         /*
         for(uint16_t un_reading : vecReadings[un_dev_idx]) {
            fAverageRaw += static_cast<float>(un_reading);
         }
         fAverageRaw /= static_cast<float>(vecReadings[un_dev_idx].size());
         */

         float fAverage = 67.0f * std::pow(fAverageRaw + 1, -0.4f);

         vecLEDs[un_dev_idx].SetRed(std::floor(35.0f - std::fmin(35.0f, std::fabs(0 - fAverage))));
         vecLEDs[un_dev_idx].SetGreen(std::floor(35.0f - std::fmin(35.0f, std::fabs(35 - fAverage))));
         vecLEDs[un_dev_idx].SetBlue(std::floor(35.0f - std::fmin(35.0f, std::fabs(70 - fAverage))));
      }
   }

   /* Disable the actuator power domain */
   m_pcPowerManagementInterface->SendPacket(CPacketControlInterface::CPacket::EType::SET_ACTUATOR_POWER_ENABLE, false);
   /* Disable actuator input limit override */
   m_pcPowerManagementInterface->SendPacket(CPacketControlInterface::CPacket::EType::SET_ACTUATOR_INPUT_LIMIT_OVERRIDE,
                                            static_cast<const uint8_t>(EActuatorInputLimit::LAUTO));

}


text:
#ifndef _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_FUNC_H_  // NOLINT
#define _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_FUNC_H_

#include <list>
#include <string>

#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"

#include "clang/AST/Decl.h"

#include "slang_assert.h"
#include "slang_rs_export_type.h"
#include "slang_rs_exportable.h"

namespace llvm {
  class StructType;
}

namespace clang {
  class FunctionDecl;
}   // namespace clang

namespace slang {

class RSContext;

class RSExportFunc : public RSExportable {
  friend class RSContext;

 private:
  std::string mName;
  std::string mMangledName;
  bool mShouldMangle;
  RSExportRecordType *mParamPacketType;

  RSExportFunc(RSContext *Context, const llvm::StringRef &Name,
               const clang::FunctionDecl *FD)
    : RSExportable(Context, RSExportable::EX_FUNC),
      mName(Name.data(), Name.size()),
      mMangledName(),
      mShouldMangle(false),
      mParamPacketType(NULL) {

    mShouldMangle = Context->getMangleContext().shouldMangleDeclName(FD);

    if (mShouldMangle) {
      llvm::raw_string_ostream BufStm(mMangledName);
      Context->getMangleContext().mangleName(FD, BufStm);
      BufStm.flush();
    }

    return;
  }

 public:
  static RSExportFunc *Create(RSContext *Context,
                              const clang::FunctionDecl *FD);

  typedef RSExportRecordType::const_field_iterator const_param_iterator;

  inline const_param_iterator params_begin() const {
    slangAssert((mParamPacketType != NULL) &&
                "Get parameter from export function having no parameter!");
    return mParamPacketType->fields_begin();
  }
  inline const_param_iterator params_end() const {
    slangAssert((mParamPacketType != NULL) &&
                "Get parameter from export function having no parameter!");
    return mParamPacketType->fields_end();
  }

  inline const std::string &getName(bool mangle = true) const {
    return (mShouldMangle && mangle) ? mMangledName : mName;
  }

  inline bool hasParam() const
    { return (mParamPacketType && !mParamPacketType->getFields().empty()); }
  inline size_t getNumParameters() const
    { return ((mParamPacketType) ? mParamPacketType->getFields().size() : 0); }

  inline const RSExportRecordType *getParamPacketType() const
    { return mParamPacketType; }

  // Check whether the given ParamsPacket type (in LLVM type) is "size
  // equivalent" to the one obtained from getParamPacketType(). If the @Params
  // is NULL, means there must be no any parameters.
  bool checkParameterPacketType(llvm::StructType *ParamTy) const;
};  // RSExportFunc

}   // namespace slang

#endif  // _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_FUNC_H_  NOLINT


text:
const should = require('should');

// Stuff we are testing
const helpers = require('../../../core/frontend/helpers');

const almostOneMinute =
    '
Ghost has a number of different user roles for your team
' +
    '
Authors

The base user level in Ghost is an author. Authors can write posts,' +
    ' edit their own posts, and publish their own posts. Authors are trusted users. If you ' +
    'don\'t trust users to be allowed to publish their own posts, you shouldn\'t invite them to Ghost admin.
' +
    '
Editors

Editors are the 2nd user level in Ghost. Editors can do everything that an' +
    ' Author can do, but they can also edit and publish the posts of others - as well as their own. Editors can also invite new' +
    ' authors to the site.

Administrators

The top user level in Ghost is Administrator.' +
    ' Again, administrators can do everything that Authors and Editors can do, but they can also edit all site settings ' +
    'and data, not just content. Additionally, administrators have full access to invite, manage or remove any other' +
    ' user of the site.

The Owner

There is only ever one owner of a Ghost site. ' +
    'The owner is a special user which has all the same permissions as an Administrator, but with two exceptions: ' +
    'The Owner can never be deleted. And in some circumstances the owner will have access to additional special settings ' +
    'if applicable — for example, billing details, if using Ghost(Pro).

It\'s a good idea to ask all of your' +
    ' users to fill out their user profiles, including bio and social links. These will populate rich structured data ' +
    'for posts and generally create more opportunities for themes to fully populate their design.
';

const almostOneAndAHalfMinute = almostOneMinute +
    '
' +
    '
Ghost has a number of different user roles for your team
' +
    '
Authors

The base user level in Ghost is an author. Authors can write posts,' +
    ' edit their own posts, and publish their own posts. Authors are trusted users. If you ' +
    'don\'t trust users to be allowed to publish their own posts, you shouldn\'t invite them to Ghost admin.
' +
    '
Editors

Editors are the 2nd user level in Ghost. Editors can do everything that an' +
    ' Author can do, but they can also edit and publish the posts of others - as well as their own. Editors can also invite new' +
    ' authors to the site.

Administrators

The top user level in Ghost is Administrator.' +
    ' Again, administrators can do everything that Authors and Editors can do, but they can also edit all site settings ' +
    'and data, not just content. Additionally, administrators have full access to invite
' +
    '
';

describe('{{reading_time}} helper', function () {
    it('[success] renders reading time for less than one minute text as one minute', function () {
        const data = {
            html: almostOneMinute,
            title: 'Test',
            slug: 'slug'
        };

        const result = helpers.reading_time.call(data);

        String(result).should.equal('1 min read');
    });

    it('[success] renders reading time for one minute text as one minute', function () {
        const data = {
            html: almostOneMinute +
                      'This needed about twenty-five more words before passing the one minute reading time, ' +
                      'since the word count was 250, and the average speed is 275.',
            title: 'Test',
            slug: 'slug'
        };

        const result = helpers.reading_time.call(data);

        String(result).should.equal('1 min read');
    });

    it('[success] renders reading time for just under 1.5 minutes text as one minute', function () {
        const data = {
            html: almostOneAndAHalfMinute,
            title: 'Test',
            slug: 'slug'
        };

        const result = helpers.reading_time.call(data);

        String(result).should.equal('1 min read');
    });

    it('[success] adds time for feature image', function () {
        const data = {
            html: almostOneAndAHalfMinute,
            title: 'Test',
            slug: 'slug',
            feature_image: '/content/images/someimage.jpg'
        };

        const result = helpers.reading_time.call(data);

        // The reading time for this HTML snippet would 89 seconds without the image
        // Adding the 12 additional seconds for the image results in a readng time of over 1.5 minutes, rounded to 2
        String(result).should.equal('2 min read');
    });

    it('[success] adds time for inline images', function () {
        const data = {
            html: almostOneAndAHalfMinute +
                  '',
            title: 'Test',
            slug: 'slug'
        };

        const result = helpers.reading_time.call(data);

        // The reading time for this HTML snippet would 89 seconds without the image
        // Adding the 12 additional seconds for the image results in a readng time of over 1.5 minutes, rounded to 2
        String(result).should.equal('2 min read');
    });

    it('[failure] does not render reading time when not post', function () {
        const data = {
            author: {
                name: 'abc 123',
                slug: 'abc123'
            }
        };

        const result = helpers.reading_time.call(data);

        should.not.exist(result);
    });
});


text:
[![Build Status](https://travis-ci.org/mikewlange/anything2text.svg?branch=master)](https://travis-ci.org/mikewlange/anything2text)

A Go wrapper library to convert PDF, DOC, DOCX, XML, HTML, RTF, ODT, Pages documents and images (see optional dependencies below) to plain text.

## Installation

If you haven't setup Go before, you need to first set a `GOPATH` (see [https://golang.org/doc/code.html#GOPATH](https://golang.org/doc/code.html#GOPATH)).

To fetch and build the code:

    $ go get github.com/sajari/docconv/...

This will also build the command line tool `docd` into `$GOPATH/bin` (assumed to be in your `PATH` already).

## Dependencies
tidy, wv, popplerutils, unrtf, https://github.com/JalfResi/justext

Example install of dependencies (not all systems):

    $ sudo apt-get install poppler-utils wv unrtf tidy
    $ go get github.com/JalfResi/justext

### Optional Dependencies

To add image support to the `docconv` library you first need to install and build https://github.com/otiai10/gosseract.  Now you can add `-tags ocr` to any `go` command when building/fetching `docconv` to include support for processing images:

    $ go get -tags ocr github.com/sajari/docconv/...

## docd tool

The `docd` tool runs as either

1. a service on port 8000 (by default)

   Documents can be sent as a multipart POST request and the plain text (body) and meta information are then returned as a JSON object

2. a service exposed from within a Docker container

   This also runs as a service, but from within a Docker container. There are two build scripts [./docd/debian.sh](./docd/debian.sh) and [./docd/alpine.sh](./docd/alpine.sh).

   The debian version uses the Debian package repository which can vary with builds. The Alpine version uses a very cut down Linux distribution to produce a container ~40MB. It also locks the dependency versions for consistency, but may miss out on future updates.

3. via the command line.

   Documents can be sent as an argument, e.g.

   ```docd -input document.pdf```

### Optional Flags
 - "addr" - the bind address for the HTTP server, default is ":8000"
 - "log-level"
    - 0: errors & critical info
    - 1: inclues 0 and logs each request as well
    - 2: include 1 and logs the response payloads
 - "readability-length-low" - Sets the readability length low if the ?readability=1 parameter is set
 - "readability-length-high" - Sets the readability length high if the ?readability=1 parameter is set
 - "readability-stopwords-low" - Sets the readability stopwords low if the ?readability=1 parameter is set
 - "readability-stopwords-high" - Sets the readability stopwords high if the ?readability=1 parameter is set
 - "readability-max-link-density" - Sets the readability max link density if the ?readability=1 parameter is set
 - "readability-max-heading-distance" - Sets the readability max heading distance if the ?readability=1 parameter is set
 - "readability-use-classes - Comma separated list of readability classes to use if the ?readability=1 parameter is set

### How to start the service
```docd -log-level 0   # will only log errors & critical info ```

```docd -addr :8000 -log-level 1   # will run on port 8000 and log each request as well ```

## Example Usage (code)
Some basic code is shown below, but normally you would accept the file by http or open it from the file system. It should be enough to get you started though...

Use case 1: run locally
Note: this assumes you have the dependencies installed.

```go
package main

import (
	"fmt"
	"log"

	"github.com/sajari/docconv"
)

func main() {
	res, err := docconv.ConvertPath("your-file.pdf")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res)
}
```

Use case 2: request over the network

```go
package main

import (
	"fmt"
	"log"

	"github.com/sajari/docconv/client"
)

func main() {
	// Create a new client, using the default endpoint (localhost:8000)
	c := client.New()

	res, err := client.ConvertPath(c, "your-file.pdf")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res)
}
```


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

    public $globalVar = array();

    public function __construct()
    {
        parent::__construct();
        $this->load->library("session");

        $this->globalVar['mt_activites'] = $this->db->query('SELECT * FROM type_activite' )->result();
        foreach ($this->globalVar['mt_activites'] as $value) {
           $value->sous_types = $this->db->query('SELECT * FROM sous_activite WHERE menu = 1 AND id_type ='.(int)$value->id )->result();
        }
        $this->load->vars($this->globalVar);
    }

    public function espace_pro()
    {
        $data = array();
        $data['menu'] = '';

        $this->load->view('espace_pro.php', $data);
    }

    public function mdp_oublie()
    {
        $data = array();
        $data['menu'] = '';

        if($this->input->post())
        {
            $mail = $this->input->post('mail', TRUE);
            $user = $this->db->query('SELECT * FROM users WHERE email = "'.$mail.'"')->row();

            if($user)
            {
               //$mdp = $this->random(8);
            	$mdp = 0;
                $this->db->query('UPDATE users SET password = "'.sha1($mdp).'" WHERE id = '.(int)$user->id);

                $from = 'joo.heler@gmail.com';
                $to = $mail;
                $objet = '[Pays de la Drôme] Demande de nouveau mot de passe';

                $contenu = '';
                $contenu .= 'Bonjour,
';
                $contenu .= 'Vous avez effectué une demande de nouveau mot de passe sur le site www.paysdeladrome.com.

';
                $contenu .= 'Voici vos nouveaux identifiants de connexion:
';
                $contenu .= '- Email: '.$mail.'
';
                $contenu .= '- Mot de passe: '.$mdp.'
';
                $contenu .= '
Vous pouvez modifier ce mot de passe via votre espace personnel sur le site www.paysdeladrome.com : Mon Compte, rubrique Mes Infos Personnelles.';

                //$this->mail_action($to, $from, $objet, $contenu);
				set_alert('success', 'Un email vous a été envoyé avec votre nouveau mot de passe.');
            }
            else{
                set_alert('danger', 'Aucun compte n\'est associé à cette adresse email.');
            }

            redirect( current_url() );
        }

        $this->load->view('mot_de_passe_oublie.php', $data);
    }

    public function inscription(){
    	$data = array();
        $data['menu'] = '';

    	if($this->input->post())
        {
            $nom = $this->input->post('nom', TRUE);
            $prenom = $this->input->post('prenom', TRUE);
            $tel = $this->input->post('telephone', TRUE);
            $mail = $this->input->post('mail', TRUE);
            $mdp = $this->input->post('password', TRUE);
            $mdp_re = $this->input->post('repassword', TRUE);
            $rcs = $this->input->post('rcs', TRUE);
            $role = $this->input->post('type', TRUE);

            if($mdp == $mdp_re)
            {
                $user = $this->db->query("SELECT * FROM users WHERE email = " . $this->db->escape($mail))->row();

                if(!$user)
                {
                    $this->db->query('
                        INSERT INTO users(nom, prenom, telephone, email,rcs,role, password) VALUES(
                            ' . $this->db->escape($nom) . ',
                            ' . $this->db->escape($prenom) . ',
                            ' . $this->db->escape($tel) . ',
                            ' . $this->db->escape($mail) . ',
                            ' . $this->db->escape($rcs) . ',
                            ' . $this->db->escape($type) . ',
                            ' . $this->db->escape(sha1($mdp)) . ' )'
                    );

                    $from = 'joo.heler@gmail.com';
	                $to = $mail;
	                $objet = '[Pays de la Drôme] Demande de nouveau mot de passe';

	                $contenu = '';
	                $contenu .= 'Bonjour,
';
	                $contenu .= 'Vous avez effectué une demande de nouveau mot de passe sur le site www.paysdeladrome.com.

';
	                $contenu .= 'Voici vos nouveaux identifiants de connexion:
';
	                $contenu .= '- Email: '.$mail.'
';
	                $contenu .= '- Mot de passe: '.$mdp.'
';
	                $contenu .= '
Vous pouvez modifier ce mot de passe via votre espace personnel sur le site www.paysdeladrome.com : Mon Compte, rubrique Mes Infos Personnelles.';

	                //$this->mail_action($to, $from, $objet, $contenu);

                    set_alert('success', 'Un email vous a été envoyé avec un récapitulatif de vos informations.');

                }
                else
                {
                	set_alert('danger', 'Le compte existe déjà.');
                }
            }
            else
            {
            	set_alert('danger', 'Les mots de passe ne sont pas identiques.');
            }

         	redirect( current_url() );
        }

        $this->load->view('inscription.php', $data);
    }

}


text:
import sys
import unittest
from PyQt4 import QtGui
from FlatCAMApp import App, tclCommands
from FlatCAMObj import FlatCAMGerber, FlatCAMGeometry, FlatCAMCNCjob
from ObjectUI import GerberObjectUI, GeometryObjectUI
from time import sleep
import os
import tempfile

class GerberFlowTestCase(unittest.TestCase):
    """
    This is a top-level test covering the Gerber-to-GCode
    generation workflow.

    THIS IS A REQUIRED TEST FOR ANY UPDATES.

    """

    filename = 'simple1.gbr'

    def setUp(self):
        self.app = QtGui.QApplication(sys.argv)

        # Create App, keep app defaults (do not load
        # user-defined defaults).
        self.fc = App(user_defaults=False)

        self.fc.open_gerber('tests/gerber_files/' + self.filename)

    def tearDown(self):
        del self.fc
        del self.app

    def test_flow(self):
        # Names of available objects.
        names = self.fc.collection.get_names()
        print names

        #--------------------------------------
        # Total of 1 objects.
        #--------------------------------------
        self.assertEquals(len(names), 1,
                          "Expected 1 object, found %d" % len(names))

        #--------------------------------------
        # Object's name matches the file name.
        #--------------------------------------
        self.assertEquals(names[0], self.filename,
                          "Expected name == %s, got %s" % (self.filename, names[0]))

        #---------------------------------------
        # Get object by that name, make sure it's a FlatCAMGerber.
        #---------------------------------------
        gerber_name = names[0]
        gerber_obj = self.fc.collection.get_by_name(gerber_name)
        self.assertTrue(isinstance(gerber_obj, FlatCAMGerber),
                        "Expected FlatCAMGerber, instead, %s is %s" %
                        (gerber_name, type(gerber_obj)))

        #----------------------------------------
        # Object's GUI matches Object's options
        #----------------------------------------
        # TODO: Open GUI with double-click on object.
        # Opens the Object's GUI, populates it.
        gerber_obj.build_ui()
        for option, value in gerber_obj.options.iteritems():
            try:
                form_field = gerber_obj.form_fields[option]
            except KeyError:
                print ("**********************************************************\n"
                       "* WARNING: Option '{}' has no form field\n"
                       "**********************************************************"
                       "".format(option))
                continue
            self.assertEqual(value, form_field.get_value(),
                             "Option '{}' == {} but form has {}".format(
                                 option, value, form_field.get_value()
                             ))

        #--------------------------------------------------
        # Changes in the GUI should be read in when
        # running any process. Changing something here.
        #--------------------------------------------------

        form_field = gerber_obj.form_fields['isotooldia']
        value = form_field.get_value()
        form_field.set_value(value * 1.1)  # Increase by 10%
        print "'isotooldia' == {}".format(value)

        #--------------------------------------------------
        # Create isolation routing using default values
        # and by clicking on the button.
        #--------------------------------------------------
        # Get the object's GUI and click on "Generate Geometry" under
        # "Isolation Routing"
        assert isinstance(gerber_obj, FlatCAMGerber)  # Just for the IDE
        # Changed: UI has been build already
        #gerber_obj.build_ui()  # Open the object's UI.
        ui = gerber_obj.ui
        assert isinstance(ui, GerberObjectUI)
        ui.generate_iso_button.click()  # Click

        #---------------------------------------------
        # Check that GUI has been read in.
        #---------------------------------------------
        value = gerber_obj.options['isotooldia']
        form_value = form_field.get_value()
        self.assertEqual(value, form_value,
                         "Form value for '{}' == {} was not read into options"
                         "which has {}".format('isotooldia', form_value, value))
        print "'isotooldia' == {}".format(value)

        #---------------------------------------------
        # Check that only 1 object has been created.
        #---------------------------------------------
        names = self.fc.collection.get_names()
        self.assertEqual(len(names), 2,
                         "Expected 2 objects, found %d" % len(names))

        #-------------------------------------------------------
        # Make sure the Geometry Object has the correct name
        #-------------------------------------------------------
        geo_name = gerber_name + "_iso"
        self.assertTrue(geo_name in names,
                        "Object named %s not found." % geo_name)

        #-------------------------------------------------------
        # Get the object make sure it's a geometry object
        #-------------------------------------------------------
        geo_obj = self.fc.collection.get_by_name(geo_name)
        self.assertTrue(isinstance(geo_obj, FlatCAMGeometry),
                        "Expected a FlatCAMGeometry, got %s" % type(geo_obj))

        #------------------------------------
        # Open the UI, make CNCObject
        #------------------------------------
        geo_obj.build_ui()
        ui = geo_obj.ui
        assert isinstance(ui, GeometryObjectUI)  # Just for the IDE
        ui.generate_cnc_button.click()  # Click

        # Work is done in a separate thread and results are
        # passed via events to the main event loop which is
        # not running. Run only for pending events.
        #
        # I'm not sure why, but running it only once does
        # not catch the new object. Might be a timing issue.
        # http://pyqt.sourceforge.net/Docs/PyQt4/qeventloop.html#details
        for _ in range(2):
            sleep(0.1)
            self.app.processEvents()

        #---------------------------------------------
        # Check that only 1 object has been created.
        #---------------------------------------------
        names = self.fc.collection.get_names()
        self.assertEqual(len(names), 3,
                         "Expected 3 objects, found %d" % len(names))

        #-------------------------------------------------------
        # Make sure the CNC Job Object has the correct name
        #-------------------------------------------------------
        cnc_name = geo_name + "_cnc"
        self.assertTrue(cnc_name in names,
                        "Object named %s not found." % geo_name)

        #-------------------------------------------------------
        # Get the object make sure it's a CNC Job object
        #-------------------------------------------------------
        cnc_obj = self.fc.collection.get_by_name(cnc_name)
        self.assertTrue(isinstance(cnc_obj, FlatCAMCNCjob),
                        "Expected a FlatCAMCNCJob, got %s" % type(geo_obj))

        #-----------------------------------------
        # Export G-Code, check output
        #-----------------------------------------
        assert isinstance(cnc_obj, FlatCAMCNCjob)
        output_filename = ""
        # get system temporary file(try create it and  delete also)
        with tempfile.NamedTemporaryFile(prefix='unittest.',
                                         suffix="." + cnc_name + '.gcode',
                                         delete=True) as tmp_file:
            output_filename = tmp_file.name
        cnc_obj.export_gcode(output_filename)
        self.assertTrue(os.path.isfile(output_filename))
        os.remove(output_filename)

        print names


text:
import React from 'react';
import { styledMount as mount } from 'spec/helpers/theming';
import Security from 'src/profile/components/Security';
import Label from 'src/components/Label';
import { user, userNoPerms } from './fixtures';

describe('Security', () => {
  const mockedProps = {
    user,
  };
  it('is valid', () => {
    expect(React.isValidElement(<Security {...mockedProps} />)).toBe(true);
  });
  it('renders 2 role labels', () => {
    const wrapper = mount(<Security {...mockedProps} />);
    expect(wrapper.find('.roles').find(Label)).toHaveLength(2);
  });
  it('renders 2 datasource labels', () => {
    const wrapper = mount(<Security {...mockedProps} />);
    expect(wrapper.find('.datasources').find(Label)).toHaveLength(2);
  });
  it('renders 3 database labels', () => {
    const wrapper = mount(<Security {...mockedProps} />);
    expect(wrapper.find('.databases').find(Label)).toHaveLength(3);
  });
  it('renders no permission label when empty', () => {
    const wrapper = mount(<Security user={userNoPerms} />);
    expect(wrapper.find('.datasources').find(Label)).not.toExist();
    expect(wrapper.find('.databases').find(Label)).not.toExist();
  });
});


text:
namespace Builder.Build.BuildParseNodes
{
    public abstract class BuildItem
    {
        public Wax.BuildArg[] BuildArgs { get; set; }
        public Wax.ExtensionArg[] ExtensionArgs { get; set; }
        public BuildVar[] BuildVars { get; set; }
    }
}


text:
package stsc.algorithms.indices.primitive.stock;

import java.util.Optional;

import stsc.common.BadSignalException;
import stsc.common.Day;
import stsc.common.algorithms.BadAlgorithmException;
import stsc.common.algorithms.StockAlgorithm;
import stsc.common.algorithms.StockAlgorithmInit;
import stsc.common.signals.SerieSignal;
import stsc.common.signals.SignalContainer;
import stsc.common.signals.SignalsSerie;
import stsc.signals.DoubleSignal;
import stsc.signals.series.LimitSignalsSerie;

public final class Level extends StockAlgorithm {

	final double level;
	final String factorName;

	public Level(StockAlgorithmInit initialize) throws BadAlgorithmException {
		super(initialize);
		level = Math.abs(initialize.getSettings().getDoubleSetting("f", 0.0));
		factorName = initialize.getSettings().getSubExecutions().get(0);
	}

	@Override
	public Optional<SignalsSerie<SerieSignal>> registerSignalsClass(StockAlgorithmInit initialize) throws BadAlgorithmException {
		return Optional.of(new LimitSignalsSerie<SerieSignal>(DoubleSignal.class));
	}

	@Override
	public void process(Day day) throws BadSignalException {
		final SignalContainer<? extends SerieSignal> signal = getSignal(factorName, day.getDate());
		if (!signal.isPresent()) {
			return;
		}
		final DoubleSignal s = signal.getContent(DoubleSignal.class);
		if (s.getValue() > level || s.getValue() < -level) {
			addSignal(day.getDate(), new DoubleSignal(s.getValue()));
		}
	}
}


text:
(function() {
	window.tmdb = {
		"api_key": "",
		"base_uri": "http://api.themoviedb.org/3",
		"images_uri": "http://image.tmdb.org/t/p",
		"timeout": 5000,
		call: function(url, params, success, error){
			var params_str ="api_key="+tmdb.api_key;
			for (var key in params) {
				if (params.hasOwnProperty(key)) {
					params_str+="&"+key+"="+encodeURIComponent(params[key]);
				}
			}
			var xhr = new XMLHttpRequest();
			xhr.timeout = tmdb.timeout;
			xhr.ontimeout = function () {
				throw("Request timed out: " + url +" "+ params_str);
			};
			xhr.open("GET", tmdb.base_uri + url + "?" + params_str, true);
			xhr.setRequestHeader('Accept', 'application/json');
			xhr.responseType = "text";
			xhr.onreadystatechange = function () {
				if (this.readyState === 4) {
					if (this.status === 200){
						if (typeof success == "function") {
							success(JSON.parse(this.response));
						}else{
							throw('No success callback, but the request gave results')
						}
					}else{
						if (typeof error == "function") {
							error(JSON.parse(this.response));
						}else{
							throw('No error callback')
						}
					}
				}
			};
			xhr.send();
		}
	}
})()


text:
using StockExchange.Common;
using StockExchange.Task.App.Helpers;
using StockExchange.Task.Business;
using System.Collections.Generic;

namespace StockExchange.Task.App.Commands
{
    /// <summary>
    /// Fixes incorrect data from the GPW sources. Should be run once after
    /// syncing all historical data.
    /// </summary>
    [CommandName(Consts.Commands.FixData, "Fixes incorrect data from GPW")]
    internal class FixDataCommand : ICommand
    {
        private readonly IDataFixer _dataFixer;

        public FixDataCommand(IDataFixer dataFixer)
        {
            _dataFixer = dataFixer;
        }

        public void Execute(IEnumerable<string> parameters)
        {
            System.Threading.Tasks.Task.Run(() => _dataFixer.FixData()).Wait();
        }
    }
}


text:
package me.macjuul.chexodius.events;

import com.laytonsmith.abstraction.MCEntity;
import com.laytonsmith.core.events.BindableEvent;

public interface MCEntityCombustEvent extends BindableEvent {

	public int getDuration();
	public void setDuration(int d);
	public MCEntity getEntity();

}


text:
<html>
<body>

Iterates over enumerable collection.
</body>
</html>


text:
FUEL-utils
===========

Set of tool for maintance installed Openstack cluster

* **fuel-fdb-cleaner** -- utility for clean fdb table on compute and router
  nodes while active l3-agent migrate from one node to another.


text:
import * as React from 'react';
import { compose, withHandlers, withState, shouldUpdate } from 'recompose';
import { withRaf } from 'enhancers';
import { get } from 'lodash';
import styled from 'styled-components';

const NO_SUGGESTIONS_DESCRIPTION = 'no suggestions';

const enhance = compose(
  withState('description', 'setDescription', NO_SUGGESTIONS_DESCRIPTION),
  withHandlers({
    handleAnimationLoop: props => dt => {
      const { measure } = window.ss.maestro.snapshot.data.score;

      if (measure && window.ss.maestro.options.showMoreNotes) {
        const description = measure.noteSuggestions.map(suggestion => suggestion.description).join(", ");
        props.setDescription(description || NO_SUGGESTIONS_DESCRIPTION);
      } else {
        if (props.description) {
          props.setDescription('');
        }
      }
    }
  }),
  withRaf(
    () => window.ss.rafLoop,
    props => ({
      name: 'SuggestionNoteDescription.handleAnimationLoop',
      precedence: 9,
      onAnimationLoop: props.handleAnimationLoop
    })
  ),
  shouldUpdate((currProps, nextProps) => currProps.description !== nextProps.description)
);

const SuggestedNoteDescription = enhance(({ description }) => (
  <Outer>
    {description}
  </Outer>
));

const Outer = styled.div`
  color: fuchsia;
`;

export default SuggestedNoteDescription;


text:
<form action="{{ url_for('funds') }}" method="post" enctype="multipart/form-data" name="funds" id="funds">

    {{ form.hidden_tag() }}

    How much funds you want to add?
    {{ form.funds(autofocus=true, class='form-control select') }}

    How much bitcoins you want to add?
    {{ form.Bitcoin(autofocus=true, class='form-control select') }}

    How much dogecoins you want to add?
    {{ form.Dogecoin(autofocus=true, class='form-control select') }}

    <button type="button" class="btn btn-primary pull-right" align="center" onclick="ajax_post_submit('funds');">Add funds</button>

</form>


text:
package org.dcm4chee.xdsib.retrieve.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.activation.DataSource;

import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.io.DicomInputStream;
import org.dcm4che2.io.StopTagInputHandler;

public class DicomObjectDataSource implements DataSource {

    private DicomObject header;
    private DicomInputStream dis;

    public DicomObjectDataSource(DicomObject o) throws IOException {
        this(o, null);
    }
    public DicomObjectDataSource(DicomObject o, DicomInputStream dis ) throws IOException {
        header = o;
        this.dis = dis;
    }

    public String getContentType() {
        return "application/dicom";
    }

    public InputStream getInputStream() throws IOException {
        return new DicomObjectInputStream(header, dis);
    }

    public String getName() {
        return header == null ? "DICOM object" : header.getString(Tag.SOPInstanceUID);
    }

    public OutputStream getOutputStream() throws IOException {
        return null;
    }

}


text:
"""
Webstreaming

Supports:
* 2x Ethernet RTP cameras

In Development
* 1x CAN 3-axis gyroscope
* 4x Analog voltage sensor

"""

__author__      = "Trevor Stanhope"
__copyright__   = "MIT"
__date__ = "2021-08-19"

# Import necessary packages
from imutils.video import VideoStream
from flask import Response
from flask import Flask
from flask import render_template
import threading
import argparse
import datetime
import imutils
import time
import cv2
import numpy as np
import socket
import os
import logging
import sys
import zmq
import random

## Constants
DEBUG = False
VIDEO_HEIGHT = 240
VIDEO_WIDTH = 320
HOST = "0.0.0.0"
PORT = 8000
FRAMERATE = 5
BOOT_DELAY = 2.0
J1939_ZMQ_RECV_SOCKET = 'tcp://127.0.0.1:5678'
J1939_ZMQ_SEND_SOCKET = 'tcp://127.0.0.1:5555'
MTLT305D_ANGLES_PGN = 0xF029
MTLT305D_ACCEL_PGN = 0xF02D
MTLT305D_ANGLERATE_PGN = 0xF02A
J1939_PGN_LIST = [MTLT305D_ANGLES_PGN, MTLT305D_ACCEL_PGN, MTLT305D_ANGLERATE_PGN]
ANGLE_GREEN = 0
ANGLE_YELLOW = 15
ANGLE_ORANGE = 30
ANGLE_RED = 45
STEERING_RTP_ADDR = "rtp://192.168.40.181:50008"
UNDERBODY_RTP_ADDR = "rtp://192.168.40.40:50004"

## Globals
logging.basicConfig(level=logging.DEBUG, filename="/tmp/chractor.log")
log = logging.getLogger(__name__)
consolehandler = logging.StreamHandler(sys.stdout)
log.addHandler(consolehandler)
log.info("initiating globals ...")
outputFrame_steering = np.zeros((VIDEO_HEIGHT,VIDEO_WIDTH,3), np.uint8)
outputFrame_underbody = np.zeros((VIDEO_HEIGHT,VIDEO_WIDTH,3), np.uint8)
lock = threading.Lock()
app = Flask(__name__) # initialize a flask object
gyrox = 0
gyroy = 0
gyroz = 0
accelx = 0
accely = 0
accelz = 0
pitch = 0
roll = 0
v0 = 0
v1 = 0
v2 = 0
v3 = 0

## Classes
class j1939_msg:
    data = bytearray(8)
    id = bytearray(4)

## Functions
def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

def MTLT305D_accel_handler(msg):

	id = 0xCF02D80
	pgn = 0xF02D
	sa = 0x80
	da = 0xFF
	dlc = 8
	data = {
		'accelx_uint16' : (msg.data[0] << 8 | msg.data[1]) & 0xffff,
		'accely_uint16' : (msg.data[2] << 8 | msg.data[3]) & 0xffff,
		'accelz_uint16' : (msg.data[4] << 8 | msg.data[5]) & 0xffff,
		'lateralacc_figure_ofmerit_int2' : msg.data[6] >> 0 & 0b11,
		'longiacc_figure_ofmerit_int2' : msg.data[6] >> 2 & 0b11,
		'vertiacc_figure_ofmerit_int2' : msg.data[6] >> 4 & 0b11,
		'support_rate_acc_int8' : msg.data[7]
	}
	factor = 0.1
	offset = -320
	vmin = -320
	vmax = 335.35
	accelx = clamp(data['accelx_uint16'] * factor + offset, vmin, vmax) # m/s^2
	accely = clamp(data['accely_uint16'] * factor + offset, vmin, vmax) # m/s^2
	accelz = clamp(data['accelz_uint16'] * factor + offset, vmin, vmax) # m/s^2
	return accelx, accely, accelz

def MTLT305D_angles_handler(msg):

	pgn = 0xF029
	sa = 0x80
	da = 0xFF
	dlc = 8
	data = {
		'pitch_uint24' : msg.data[0] | (msg.data[1] << 8) | (msg.data[2] << 16) & 0xffffff,
		'roll_uint24' : msg.data[3] | (msg.data[4] << 8) | (msg.data[5] << 16) & 0xffffff,
		'pitch_compensation_int2' : msg.data[6] >> 0 & 0b11,
		'pitch_figure_ofmerit_int2' : msg.data[6] >> 2 & 0b11,
		'roll_compensation_int2' : msg.data[6] >> 4 & 0b11,
		'roll_figure_ofmerit_int2' : msg.data[6] >> 6 & 0b11,
		'pitchroll_latency_int8' : msg.data[7]
	}
	factor = 3.0517578125e-05
	offset = -250
	vmin = -90 # default is -250
	vmax = 90 # default is 252
	pitch = clamp(data['pitch_uint24'] * factor + offset, vmin, vmax) # deg
	roll = clamp(data['roll_uint24'] * factor + offset, vmin, vmax) # deg
	return pitch, roll

def MTLT305D_anglerate_handler(msg):

	pgn = 0xF029
	sa = 0x80
	da = 0xFF
	dlc = 8
	data = {
		'gyrox_uint16' : (msg.data[0] << 8 | msg.data[1]) & 0xffff,
		'gyroy_uint16' : (msg.data[2] << 8 | msg.data[3]) & 0xffff,
		'gyroz_uint16' : (msg.data[4] << 8 | msg.data[5]) & 0xffff,
		'pitchrate_figure_ofmerit_int2' : msg.data[6] >> 0 & 0b11,
		'rollrate_figure_ofmerit_int2' : msg.data[6] >> 2 & 0b11,
		'yawrate_figure_ofmerit_int2' : msg.data[6] >> 4 & 0b11,
		'anglerate_latency_int8' : msg.data[7],
	}
	factor = 0.0078125
	offset = -250
	vmin = -250
	vmax = 261.9921875
	gyrox = clamp(data['gyrox_uint16'] * factor + offset, vmin, vmax) # deg/s
	gyroy = clamp(data['gyroy_uint16'] * factor + offset, vmin, vmax) # deg/s
	gyroz = clamp(data['gyroz_uint16'] * factor + offset, vmin, vmax) # deg/s
	return gyrox, gyroy, gyroz

def capture_j1939():
	# Socket to talk to J1939 Stack
	global gyrox, gyroy, gyroz
	global pitch, roll
	global accelx, accely, accelz

    # Socket to Receive
	log.info("initiating ZMQ RECV socket ...")
	context = zmq.Context()
	socket_recv = context.socket(zmq.SUB)
	socket_recv.connect(J1939_ZMQ_RECV_SOCKET)
	socket_recv.setsockopt_string(zmq.SUBSCRIBE, '')
	poller = zmq.Poller()
	poller.register(socket_recv, zmq.POLLIN)
	log.info("ZMQ RECV socket open ...")

	# Socket to Send
#	socket_send = context.socket(zmq.PUSH)
#	socket_send.connect(J1939_ZMQ_SEND_SOCKET)
#	log.info("ZMQ SEND socket open ...")
#	data = bytearray([])
#	data.append(0x18)
#	data.append(0xEF)
#	data.append(0x5A)
#	data.append(0x44)
#	data.append(0x11)
#	data.append(0x22)
#	data.append(0x33)
#	data.append(0x44)
#	data.append(0x55)
#	data.append(0x66)
#	data.append(0x77)
#	data.append(0x88)
#   socket_send.send(data)

	while not False:
		message_bytes = bytearray()
		socks = dict(poller.poll(250)) # waits 250ms before timing out
		if socks:
			if socks.get(socket) == zmq.POLLIN:
				message = socket.recv_multipart()
				message_bytes.extend(message[1])
				pgn = (message_bytes[1] << 8 | message_bytes[2]) & 0xffff
				if pgn in J1939_PGN_LIST:
					j1939_msg.id = list(message_bytes[0:4])
					j1939_msg.data = list(message_bytes[4:])
					if pgn == MTLT305D_ACCEL_PGN:
						accelx, accely, accelz = MTLT305D_accel_handler(j1939_msg)
					if pgn == MTLT305D_ANGLES_PGN:
						pitch, roll = MTLT305D_angles_handler(j1939_msg)
					if pgn == MTLT305D_ANGLERATE_PGN:
						gyrox, gyroy, gyroz = MTLT305D_anglerate_handler(j1939_msg)

	socket_recv.close()
	#socket_send.close()

def capture_streams():
	# capture RTP video streams

	# grab global references to the video stream(s), output frame, and
	# lock variables
	global cam_steering, cam_underbody, outputFrame_steering, outputFrame_underbody, lock

	# loop over frames from the video stream
	while True:
		time.sleep(1.0/FRAMERATE)
		# read the next frame from the video stream, resize it,
		if cam_steering is not None:
			frame_steering = cam_steering.read()
			if frame_steering is not None:
				frame_steering = imutils.resize(frame_steering, width=VIDEO_WIDTH, height=VIDEO_HEIGHT)
				with lock:
					outputFrame_steering = frame_steering.copy()
			else:
				outputFrame_steering = np.zeros((VIDEO_HEIGHT,VIDEO_WIDTH,3), np.uint8)
				cv2.putText(
					 outputFrame_steering, #numpy array on which text is written
					 str("NO CAM"), #text
					 (int(VIDEO_WIDTH/3), int(VIDEO_HEIGHT/2)), # position at which writing has to start
					 cv2.FONT_HERSHEY_SIMPLEX, #font family
					 1, #font size
					 (255,255,255), #font color
					 3 #font stroke
				)

		# read the next frame from the video stream, resize it,
		if cam_underbody is not None:
			frame_underbody = cam_underbody.read()
			if frame_underbody is not None:
				frame_underbody = imutils.resize(frame_underbody, width=VIDEO_WIDTH, height=VIDEO_HEIGHT)
				with lock:
					outputFrame_underbody = frame_underbody.copy()
			else:
				outputFrame_underbody = np.zeros((VIDEO_HEIGHT,VIDEO_WIDTH,3), np.uint8)
				cv2.putText(
					 outputFrame_underbody, #numpy array on which text is written
					 str("NO CAM"), #text
					 (int(VIDEO_WIDTH/3),int(VIDEO_HEIGHT/2)), # position at which writing has to start
					 cv2.FONT_HERSHEY_SIMPLEX, #font family
					 1, #font size
					 (255,255,255), #font color
					 3 #font stroke
				)

def color_picker(val):
	if abs(val) < ANGLE_YELLOW: return (0, 255, 0)
	elif abs(val) < ANGLE_ORANGE: return (0, 255, 255)
	elif abs(val) < ANGLE_RED: return (0, 128, 255)
	else: return (0, 0, 255)

def generate_display():
	# generate display graphic for web UI

	# grab global references to the output frame and lock variables
	global outputFrame_steering, outputFrame_underbody, lock
	global roll, pitch
	global accelx, accely, accelz
	global gyrox, gyroy, gyroz

	# loop over frames from the output stream
	while True:
		# wait until the lock is acquired
		with lock:
			# check if the output frame is available, otherwise skip
			# the iteration of the loop
			outputFrame_combo = np.hstack((outputFrame_steering, outputFrame_underbody))
			color = color_picker(roll)
			cv2.putText(
				 outputFrame_combo, #numpy array on which text is written
				 str("roll: %+05.1f" % roll), #text
				 (10,30), # position at which writing has to start
				 cv2.FONT_HERSHEY_SIMPLEX, #font family
				 1, #font size
				 color, #font color
				 3 #font stroke
			)
			color = color_picker(pitch)
			cv2.putText(
				 outputFrame_combo, #numpy array on which text is written
				 str("pitch: %+05.1f" % pitch), #text
				 (430,30), # position at which writing has to start
				 cv2.FONT_HERSHEY_SIMPLEX, #font family
				 1, #font size
				 color, # font color
				 3 #font stroke
			)
			# encode the frame in JPEG format
			(flag, encodedImage_combo) = cv2.imencode(".jpg", outputFrame_combo)
			# ensure the frame was successfully encoded
			if not flag:
				continue

		# yield the output frame in the byte format
		yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage_combo) + b'\r\n')

def read_volts(id):
	# read volts from device
	devname = "/dev/hbinvolt{}".format(id)
	try:
		infile = os.open(devname, os.O_RDONLY)
		v = float(os.read(infile, 16))
		os.close(infile)
	except OSError:
		log.info("couldn't read ADIO device")
		v = 0.000
	return v

def capture_adio():
	global v0, v1, v2, v3
	while True:
		try:
			v0 = read_volts(0)
			v1 = read_volts(1)
			v2 = read_volts(2)
			v3 = read_volts(3)
			log.info("%f, %f, %f, %f" % (v0, v1, v2, v3))
		except Exception as E:
			log.info(str(E))

## Flask Handlers
@app.route("/")
def index():

	# return the rendered template
	return render_template("index.html")

@app.route("/video_feed")
def video_feed():
	# return the response generated along with the specific media
	# type (mime type)
	return Response(generate_display(), mimetype = "multipart/x-mixed-replace; boundary=frame")

## Main
# initialize the video stream and allow the camera sensor to  warmup
log.info("initiating video streams ...")
try:
	cam_steering = VideoStream(STEERING_RTP_ADDR).start() #!TODO: Create centralized config for this (SHARED WITH LAUNCH XMLS)
	log.info("started steering video stream ...")
except:
	log.warning("failed to start steering stream ...")
	cam_steering = None

# initialize the video stream and allow the camera sensor to  warmup
try:
	cam_underbody = VideoStream(UNDERBODY_RTP_ADDR).start() #!TODO: Create centralized config for this (SHARED WITH LAUNCH XMLS)
	log.info("started underbody video stream ...")
except:
	log.warning("failed to start underbody stream ...")
	cam_underbody = None
time.sleep(BOOT_DELAY)
log.info("boot complete ...")

if __name__ == '__main__': # check to see if this is the main thread of execution

	# start a thread that will perform stream capture
	t = threading.Thread(target=capture_streams, args=(args["frame_count"],))
	log.info("initiating RTP videostreams thread ...")
	t_streams = threading.Thread(target=capture_streams)
	t_streams.daemon = True
	t_streams.start()

	# start a thread that will perform UDP CAN capture
	log.info("initiating ZMQ J1939 thread ...")
	t_capture_j1939 = threading.Thread(target=capture_j1939)
	t_capture_j1939.daemon = True
	t_capture_j1939.start()

	# start a thread that will perform voltage readings
	log.info("initiating ADIO thread ...")
	t_capture_adio = threading.Thread(target=capture_adio)
	t_capture_adio.daemon = True
	t_capture_adio.start()

	# start the flask app
	log.info("initiating Flask web app ...")
	app.run(host=HOST, port=PORT, debug=DEBUG, threaded=True, use_reloader=False)

## Shutdown
log.info("shutting down ...")

# release the video stream pointer
if cam_steering is not None:
	log.info("releasing steering stream ...")
	cam_steering.stop()

# release the video stream pointer
if cam_underbody is not None:
	log.info("releasing underbody stream ...")
	cam_underbody.stop()

# release the zmq socket
if  is not None:


text:
module RSpec
  module Mocks
    # Support for `patch_marshal_to_support_partial_doubles` configuration.
    #
    # @private
    class MarshalExtension
      def self.patch!
        return if Marshal.respond_to?(:dump_with_rspec_mocks)

        Marshal.instance_eval do
          class << self
            def dump_with_rspec_mocks(object, *rest)
              if !::RSpec::Mocks.space.registered?(object) || NilClass === object
                dump_without_rspec_mocks(object, *rest)
              else
                dump_without_rspec_mocks(object.dup, *rest)
              end
            end

            alias_method :dump_without_rspec_mocks, :dump
            undef_method :dump
            alias_method :dump, :dump_with_rspec_mocks
          end
        end
      end

      def self.unpatch!
        return unless Marshal.respond_to?(:dump_with_rspec_mocks)

        Marshal.instance_eval do
          class << self
            undef_method :dump_with_rspec_mocks
            undef_method :dump
            alias_method :dump, :dump_without_rspec_mocks
            undef_method :dump_without_rspec_mocks
          end
        end
      end
    end
  end
end


text:
/**
 * Creates an informational panel for Apps, based on some general app info.
 * Needs the following keys in its config:
 * appId - the full id of the app (module/app_name)
 * appModule - the name of the module that the app comes from
 * tag - the tag of the app to display (release, beta, or dev)
 * node - the jQuery node (I know...) where this panel should show itself
 */
define([
    'bluebird',
    'common/runtime',
    'kb_service/client/catalog',
    'kb_service/client/narrativeMethodStore',
    'handlebars',
    'text!kbase/templates/app_info_panel.html',
], (Promise, Runtime, Catalog, NarrativeMethodStore, Handlebars, appInfoPanelTmpl) => {
    'use strict';

    function factory(config) {
        const runtime = Runtime.make(),
            nms = new NarrativeMethodStore(runtime.config('services.narrative_method_store.url')),
            catalog = new Catalog(runtime.config('services.catalog.url')),
            appId = config.appId,
            appModule = config.appModule,
            tag = config.tag || 'release',
            infoPanel = Handlebars.compile(appInfoPanelTmpl);
        let container,
            info = {};

        function start(arg) {
            container = arg.node;

            const infoProms = [
                /* Get the method full info so we can populate the description */
                nms.get_method_full_info({ ids: [appId], tag: tag }).then((methodInfo) => {
                    methodInfo = methodInfo[0] || {};
                    const desc = methodInfo.description || '';
                    info.description = new Handlebars.SafeString(desc);

                    const authorList = methodInfo.authors || [];
                    info.authorList = authorList.join(', ');
                    info.multiAuthors = authorList.length > 1;
                }),

                /* Get the method stats so we know how many times it was run. */
                catalog.get_exec_aggr_stats({ full_app_ids: [appId] }).then((appStats) => {
                    appStats = appStats[0] || {};
                    info.runCount = appStats.number_of_calls || 'unknown';
                }),

                /* Get the module info so we know when it was last updated. */
                catalog.get_module_info({ module_name: appModule }).then((moduleInfo) => {
                    moduleInfo = moduleInfo[tag] || {};
                    const timestamp = moduleInfo.timestamp || 'unknown';
                    let dateString = 'unknown';
                    try {
                        dateString = new Date(timestamp).toLocaleDateString();
                    } catch (e) {
                        //pass
                    }
                    info.updateDate = dateString;
                }),
            ];
            return Promise.all(infoProms).then(() => {
                container.html(infoPanel(info));
            });
        }

        function stop() {
            return Promise.resolve(container.html(''));
        }

        return {
            start: start,
            stop: stop,
        };
    }

    return {
        make: function (config) {
            return factory(config);
        },
    };
});


text:
package com.palantir.common.concurrent;

import com.google.common.base.Throwables;
import com.palantir.logsafe.Preconditions;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class BlockingWorkerPool {
    private final CompletionService<Void> service;
    private final int concurrentTaskLimit;

    private final AtomicInteger currentTaskCount = new AtomicInteger();

    public BlockingWorkerPool(ExecutorService executor, int concurrentTaskLimit) {
        this.service = new ExecutorCompletionService<Void>(executor);
        this.concurrentTaskLimit = concurrentTaskLimit;
    }

    /**
     * Submits a task to the pool. If the pool is currently executing the
     * maximum number of tasks allowed, this call will block until one of the
     * currently executing tasks has finished.
     *
     * @throws RuntimeException wrapping an ExecutionException if a previously
     *                          submitted task threw an exception.
     */
    public synchronized void submitTask(Runnable task) throws InterruptedException {
        waitForAvailability();

        Preconditions.checkState(
                currentTaskCount.get() < concurrentTaskLimit, "currentTaskCount must be less than currentTaskLimit");
        service.submit(task, null);
        currentTaskCount.incrementAndGet();
    }

    private void waitForSingleTask() throws InterruptedException {
        if (currentTaskCount.get() <= 0) {
            return;
        }

        Future<Void> f = service.take();
        currentTaskCount.decrementAndGet();
        try {
            f.get();
        } catch (ExecutionException e) {
            throw Throwables.propagate(e.getCause());
        }
    }

    /**
     * Waits for all tasks that have been previously submitted to the pool to
     * finish.
     *
     * @throws RuntimeException wrapping an ExecutionException if a previously
     *                          submitted task threw an exception.
     */
    public synchronized void waitForSubmittedTasks() throws InterruptedException {
        while (currentTaskCount.get() > 0) {
            waitForSingleTask();
        }
    }

    /**
     * Waits until the number of tasks drops below the concurrent task limit.
     */
    public synchronized void waitForAvailability() throws InterruptedException {
        if (currentTaskCount.get() >= concurrentTaskLimit) {
            waitForSingleTask();
        }
    }
}


text:
<?php
    $articles = getArticles();
    require_once("/app/view/home.php");
?>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--
  ~ Copyright 2016 OPEN TONE Inc.
  ~
  ~ 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.
  -->

<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="customField">

  <resultMap id="CustomFieldAdmin" class="jp.co.opentone.bsol.linkbinder.dto.CustomField">
    <result property="id"                        column="id" />
    <result property="label"                     column="label" />
    <result property="no"                        column="no" />
    <result property="orderNo"                   column="order_no" />
    <result property="useWhole"                  column="use_whole" />
    <result property="createdBy.empNo"           column="created_by" />
    <result property="createdBy.nameE"           column="created_by_name" />
    <result property="createdAt"                 column="created_at" />
    <result property="updatedBy.empNo"           column="updated_by" />
    <result property="updatedBy.nameE"           column="updated_by_name" />
    <result property="updatedAt"                 column="updated_at" />
    <result property="versionNo"                 column="version_no" />
    <result property="deleteNo"                  column="delete_no" />
  </resultMap>

  <resultMap id="customFieldProject" class="jp.co.opentone.bsol.linkbinder.dto.CustomField">
    <result property="id"                        column="id" />
    <result property="no"                        column="no" />
    <result property="projectCustomFieldId"      column="project_custom_field_id" />
    <result property="projectId"                 column="project_id" />
    <result property="projectNameE"              column="project_name_e" />
    <result property="label"                     column="label" />
    <result property="orderNo"                   column="order_no" />
    <result property="useWhole"                  column="use_whole" />
    <result property="createdBy.empNo"           column="pc_created_by" />
    <result property="createdBy.nameE"           column="pc_created_by_name" />
    <result property="createdAt"                 column="pc_created_at" />
    <result property="updatedBy.empNo"           column="pc_updated_by" />
    <result property="updatedBy.nameE"           column="pc_updated_by_name" />
    <result property="updatedAt"                 column="pc_updated_at" />
    <result property="versionNo"                 column="version_no" />
    <result property="deleteNo"                  column="delete_no" />
  </resultMap>

  <resultMap id="resultNotProject" class="jp.co.opentone.bsol.linkbinder.dto.CustomField">
    <result property="id"                        column="id" />
    <result property="label"                     column="label" />
    <result property="orderNo"                   column="order_no" />
  </resultMap>

  <resultMap id="resultForUpdate" class="jp.co.opentone.bsol.linkbinder.dto.CustomField">
    <result property="versionNo"             column="version_no" />
  </resultMap>

  <!-- findById,findCustomFieldで共通的に利用するSELECT,FROM句 -->
  <sql id="selectFromAdmin">
    SELECT
      id,
      no,
      label,
      order_no,
      use_whole,
      created_by,
      created_by_name,
      created_at,
      updated_by,
      updated_by_name,
      updated_at,
      version_no,
      delete_no
    FROM
      v_custom_field
  </sql>

  <!--  findByIdProjectId,findByProjectId,findProjectCustomField,で共通的に利用するSELECT,FROM句 -->
  <sql id="selectFrom">
    SELECT
      id,
      no,
      project_custom_field_id,
      project_id,
      project_name_e,
      label,
      order_no,
      use_whole,
      pc_created_by,
      pc_created_by_name,
      pc_created_at,
      pc_updated_by,
      pc_updated_by_name,
      pc_updated_at,
      version_no,
      delete_no
    FROM
      v_project_custom_field
  </sql>

  <select id="findByIdProjectId" resultMap="customFieldProject">
    <include refid="selectFrom"/>
	WHERE
      id = #id#
    AND
      project_id = #projectId#
  </select>

  <select id="findByProjectId" resultMap="customFieldProject">
    <include refid="selectFrom"/>
    WHERE
      project_id = #projectId#
  </select>

  <select id="findCustomField" resultMap="CustomFieldAdmin">
    <include refid="selectFromAdmin"/>
    WHERE
      use_whole = 0
    <dynamic>
      <isNotNull prepend="AND" property="label">
        label      like  #label# || '%' {escape #escapeChar#}
      </isNotNull>
    </dynamic>
    ORDER BY
      order_no,
      id
  </select>

  <select id="findProjectCustomField" resultMap="customFieldProject">
    <include refid="selectFrom"/>
    WHERE
      project_id = #projectId#
    <dynamic>
      <isNotNull prepend="AND" property="label">
        label      like  #label# || '%' {escape #escapeChar#}
      </isNotNull>
    </dynamic>
    ORDER BY
      order_no
  </select>

  <select id="count" resultClass="int">
    SELECT
      COUNT
        (
        DISTINCT
          id)
    FROM
      v_project_custom_field
      <dynamic prepend="WHERE">
        <isNotNull prepend="AND" property="projectId">
          project_id = #projectId#
        </isNotNull >
        <isNotNull prepend="AND" property="label">
          label      like  #label# || '%' {escape #escapeChar#}
        </isNotNull>
        <isEqual prepend="AND" property="adminHome" compareValue="true">
          project_id is not null
        </isEqual>
        <isNotNull prepend="AND" property="id">
          id         = #id#
        </isNotNull>
        <isNotNull prepend="AND" property="useWhole">
          use_whole = #useWhole#
        </isNotNull>
      </dynamic>
  </select>

  <select id="findNotAssignTo" resultMap="resultNotProject">
    SELECT DISTINCT
      id,
      label,
      order_no
    FROM
      custom_field
    WHERE
      id not in
         (
         SELECT
           custom_field_id
         FROM
           project_custom_field
         WHERE
           project_id = #value#
         AND
           delete_no = 0
         )
    AND
      use_whole = 0
    AND
      delete_no = 0
    ORDER BY
      order_no
  </select>

  <select id="findById" resultMap="CustomFieldAdmin">
    <include refid="selectFromAdmin"/>
    WHERE
      id         =   #value#
  </select>

  <insert id="create">
    <selectKey resultClass="long" keyProperty="id">
        SELECT s_custom_field_id.NEXTVAL AS id FROM dual
    </selectKey>
    INSERT INTO custom_field (
      id,
      label,
      order_no,
      use_whole,
      created_by,
      updated_by
    ) VALUES (
      #id#,
      #label#,
      #orderNo#,
      #useWhole#,
      #createdBy.empNo#,
      #updatedBy.empNo#
    )
  </insert>

  <update id="update">
    UPDATE custom_field
    SET
      updated_by = #updatedBy.empNo#,
      updated_at = SYSTIMESTAMP,
      version_no = (version_no + 1)
      <dynamic>
        <isNotNull prepend="," property="label">
          label = #label#
        </isNotNull>
        <isNotNull prepend="," property="orderNo">
          order_no       = #orderNo#
        </isNotNull>
      </dynamic>
    WHERE
      id = #id#
  </update>

  <select id="findByIdForUpdate" resultMap="resultForUpdate">
    SELECT
      version_no
    FROM
      custom_field
    WHERE
      id = #id#
    FOR UPDATE
  </select>

  <update id="delete">
    UPDATE
      custom_field
    SET
      updated_by = #updatedBy.empNo#,
      updated_at = SYSTIMESTAMP,
      version_no = (version_no + 1),
      delete_no  = s_custom_field_dno.NEXTVAL
    WHERE
      id         = #id#
  </update>

  <select id="countCheck" resultClass="int">
    SELECT
      count(id) cnt
    FROM
      v_project_custom_field
    <dynamic prepend="WHERE">
      <isNotNull prepend="AND" property="label">
        label                   = #label#
      </isNotNull>
      <isNotNull prepend="AND" property="id">
        id                      <![CDATA[<>]]> #id#
      </isNotNull>
      <isNotNull prepend="AND" property="projectId">
        project_id              = #projectId#
      </isNotNull>
      <isNull prepend="AND" property="projectId">
        project_id              is null
      </isNull>
    </dynamic>
  </select>

</sqlMap>


text:
CandleSmall * CandleSmall::instance = 0;
CandleSmall * CandleSmall::getInstance()
{
	if (instance==0)
	{
		instance = new CandleSmall();
	}
	return instance;
}

bool CandleSmall::update()
{
	if (!MovableObject::update())
		return false;
	return true;
}

bool CandleSmall::draw()
{
	if (MovableObject::draw())
	{
		return true;
	}
	return false;
}

CandleSmall::CandleSmall()
{
	objectFilter = CF_CandleSmall;
	ay = 0;
}

CandleSmall::~CandleSmall()
{
}


text:
SYNONYM

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

#### Published in
Revis. gen. pl. (Leipzig) 3: 461 (1898)

#### Original name
Nectria suffulta Berk. & M.A. Curtis, 1868

### Remarks
null


text:
import { ERRORS as COMMON_ERRORS } from '../common/config'

export const SECRET = 'server_secret'

export const ROLES = {
  reader: 'reader',
  publisher: 'publisher',
  admin: 'admin',
}

export const ERRORS = COMMON_ERRORS


text:
using System;
using RockLib.Configuration;

namespace Example.AppConfig.DotNetFramework
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("App.Config File Example Harness");

            var key100 = Config.AppSettings["Key100"];

            Console.WriteLine($"Key100: {key100}");

            Console.ReadLine();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hooker's J. Bot. 2: 45 (1850)

#### Original name
Agaricus dicupellus Berk.

### Remarks
null


text:
package be.echostyle.moola.persistence.db;

import be.echostyle.dbQueries.JdbcRepository;
import be.echostyle.dbQueries.Mapper;
import be.echostyle.dbQueries.RowAdapter;
import be.echostyle.moola.*;
import be.echostyle.moola.category.Category;
import be.echostyle.moola.category.CategoryRepository;
import be.echostyle.moola.filters.TransactionFilter;
import be.echostyle.moola.peer.Peer;
import be.echostyle.moola.peer.PeerRepository;
import be.echostyle.moola.persistence.cache.CachedCategoryRepository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static be.echostyle.moola.persistence.db.DbAccountEntry.*;

public class SimpleDbAccount extends DbAccount implements SimpleAccount {

    private final PeerRepository peerRepository;
    private final CategoryRepository categoryRepository;

    SimpleDbAccount(String id, String name, AccountType type, DbAccountRepository repository, PeerRepository peerRepository, CategoryRepository categoryRepository, IdGenerator idGenerator) {
        super(id, name, type, repository, idGenerator);
        this.peerRepository = peerRepository;
        this.categoryRepository = categoryRepository;
    }

    @Override
    public AccountEntry addEntry(String batchId, LocalDateTime timestamp, int orderNr, long amount, long balance, String comment, AccountEntryType type, PeerInfo peerInfo, TerminalInfo terminalInfo) {
        DbAccountEntry r = find(timestamp, amount, comment, type, balance);
        if (r==null) {
            String id = idGenerator.generate();
            repository
                    .insert(DbAccountEntry.TABLE,
                            COL_ID, COL_BATCH_ID, COL_ACCOUNT_ID,
                            COL_TIMESTAMP, COL_ORDERNR, COL_AMOUNT, COL_COMMENT, COL_BALANCE, COL_TYPE,
                            COL_PEER_ACCOUNTNR, COL_PEER_NAME,
                            COL_TERMINAL_NAME, COL_TERMINAL_LOCATION, COL_TERMINAL_CARD)
                    .values(id, batchId, this.id,
                            timestamp, orderNr, amount, comment, balance, type,
                            peerInfo == null ? null : peerInfo.getAccountNr(), peerInfo == null ? null : peerInfo.getName(),
                            terminalInfo == null ? null : terminalInfo.getName(), terminalInfo == null ? null : terminalInfo.getLocation(), terminalInfo == null ? null : terminalInfo.getCard());
            r = new DbAccountEntry(id, repository, timestamp, orderNr, amount, balance, comment, peerInfo, terminalInfo, type, null, null, null);
        }
        return r;
    }

    @Override
    public List<AccountEntry> getTransactions(LocalDateTime from, LocalDateTime to) {
        CacheMapper mapper = cacheMapper();
        return repository
                .from(DbAccountEntry.TABLE)
                .where(COL_ACCOUNT_ID +" = ?", this.id)
                .whereBetween(COL_TIMESTAMP, from, to)
                .orderDesc(COL_TIMESTAMP)
                .list(mapper, ALL_COLS);
    }

    @Override
    public List<AccountEntry> getTransactions(LocalDateTime to, int count, int from) {
        CacheMapper mapper = cacheMapper();
        return repository
                .from(DbAccountEntry.TABLE)
                .where(COL_ACCOUNT_ID +" = ?", this.id)
                .where(COL_TIMESTAMP +" < ?", to)
                .orderDesc(COL_TIMESTAMP)
                .limit(count, from)
                .list(mapper, ALL_COLS);
    }

    @Override
    public List<AccountEntry> getTransactions(LocalDateTime to, TransactionFilter filter, int count, int from) {
        CacheMapper mapper = cacheMapper();
        try (Stream<AccountEntry> stream = repository
                .from(DbAccountEntry.TABLE)
                .where(COL_ACCOUNT_ID + " = ?", this.id)
                .where(COL_TIMESTAMP + " < ?", to)
                .orderDesc(COL_TIMESTAMP)
                .stream(mapper, ALL_COLS)){
            return stream.filter(filter::match)
                    .skip(from)
                    .limit(count)
                    .collect(Collectors.toList());
        }
    }

    @Override
    public List<AccountEntry> getTransactions(String batchId) {
        CacheMapper mapper = cacheMapper();
        return repository
                .from(DbAccountEntry.TABLE)
                .where(COL_ACCOUNT_ID +" = ?", this.id)
                .where(COL_BATCH_ID + " = ?", batchId)
                .orderDesc(COL_TIMESTAMP)
                .list(mapper, ALL_COLS);
    }

    @Override
    public AccountEntry getTransaction(String transactonId) {
        return repository
                .from(DbAccountEntry.TABLE)
                .where(COL_ACCOUNT_ID +" = ?", this.id)
                .where(COL_ID + " = ?", transactonId)
                .one(cacheMapper(), ALL_COLS).orElse(null);
    }

    @Override
    void removeAll() {
        repository.from(DbAccountEntry.TABLE).where(COL_ACCOUNT_ID+"=?",id).delete();
        super.removeAll();
    }

    private DbAccountEntry find(LocalDateTime timestamp, long amount, String comment, AccountEntryType type, long balance) {
        return (DbAccountEntry) repository.from(DbAccountEntry.TABLE)
                .where(COL_ACCOUNT_ID +" = ?", this.id)
                .where(COL_TIMESTAMP +" = ?", timestamp)
                .where(COL_AMOUNT+" = ?", amount)
                .where(COL_TYPE+" = ?", type)
                .where(COL_BALANCE+" = ?", balance)
                .one(cacheMapper(), ALL_COLS).orElse(null);
    }

    @Override
    public boolean contains(AccountEntry entry) {
        return false;
    }

    private CacheMapper cacheMapper() {
        return new CacheMapper(repository, categoryRepository, peerRepository);
    }

    static class CacheMapper implements Mapper<AccountEntry> {
        private JdbcRepository repository;
        private CategoryRepository categoryRepository;
        private PeerRepository peerRepository;

        public CacheMapper(JdbcRepository repository, CategoryRepository categoryRepository, PeerRepository peerRepository) {
            this.repository = repository;
            this.categoryRepository = categoryRepository;
            this.peerRepository = peerRepository;
        }

        public AccountEntry map(RowAdapter row) {
            CachedCategoryRepository cachedCategories = new CachedCategoryRepository(categoryRepository);
            PeerInfo peerInfo = PeerInfo.of(row.string(COL_PEER_ACCOUNTNR), row.string(COL_PEER_NAME));
            TerminalInfo terminalInfo = TerminalInfo.of(row.string(COL_TERMINAL_NAME), row.string(COL_TERMINAL_LOCATION), row.string(COL_TERMINAL_CARD));
            AccountEntryType type = row.value(COL_TYPE, AccountEntryType.class);
            Peer peer = row.reference(COL_PEER_ID, peerRepository::getPeer);
            Category category = row.reference(COL_CATEGORY_ID, cachedCategories::getCategory);
            DbAccountEntry r = new DbAccountEntry(row.string(COL_ID), repository, row.dateTime(COL_TIMESTAMP), row.integer(COL_ORDERNR), row.longInt(COL_AMOUNT), row.longInt(COL_BALANCE), row.string(COL_COMMENT), peerInfo, terminalInfo, type, row.string(COL_DESCRIPTION), peer, category);
            return r;
        }
    }
}


text:
define([
//	'../../../../src/utils/domInstance'
], function(
//	domInstance
){

	var domInstance = hello.utils.domInstance;

//
// Events
//
describe('utils / domInstance', function(){

	it('should return true, if type is an HTMLInputElement matches "input"', function(){

		var type = 'input';

		var value = domInstance(type, document.createElement(type));

		expect( value ).to.equal( true );

	});

	it('should return false, if type is an HTMLInputElement matches "form"', function(){

		var type = 'input';

		var value = domInstance('form', document.createElement(type));

		expect( value ).to.equal( false );

	});

	it('should return false, if an object posess as an HTMLInputElement', function(){

		var type = 'input';

		var value = domInstance('input', {tagName : type});

		expect( value ).to.equal( false );

	});

	it('should return false, if second parameter is ommited or null', function(){

		expect( domInstance('input') ).to.equal( false );

		expect( domInstance('input', false) ).to.equal( false );

		expect( domInstance('input', true) ).to.equal( false );

		expect( domInstance('input', null) ).to.equal( false );

	});

});

});


text:
<?php
/**
 * Created by PhpStorm.
 * User: xiaohongyang
 * Date: 2016/1/12
 * Time: 22:18
 */

namespace app\modules\adminshop\controllers;

use app\modules\adminshop\models\User_rank;
use app\modules\adminshop\models\Users;
use app\modules\adminshop\models\UsersSearch;
use yii\data\ActiveDataProvider;
use yii\web\User;

class UsersController extends BaseController{

    public function actionList(){

        $rankList = User_rank::find()->orderBy('min_points asc')->all();

        $userList = array();
        $userList['rankList'] = $rankList;

        $searchModel = new UsersSearch();
        $dataProvider = $searchModel->search(\Yii::$app->request->get());

        return $this->render('list', [
                                    'model'=> $searchModel,
                                    'dataProvider'=>$dataProvider,
                                    'rankList' => $rankList
                                ]
                            );

    }

    public function actionEdit(){
        echo 33;
    }

}


text:
package com.innowil.ziweiyang;

import org.appcelerator.titanium.TiRootActivity;

public final class ZiweiyangActivity extends TiRootActivity
{
}


text:
/*
    CLWeb // _stats.css

    Stylesheet for all stat-related styles
*/

#stats {
    float: left;
    font-family: 'Montserrat', sans-serif;
    overflow: auto;
    text-align: center;
    min-width: 128px;
}

#statsTitle {
    background: #3C92CA;
}

#statsTitle, #stats div:first-child img {
    padding: 12px;
}

#stats img, #stats h2, #stats .statsButton {
    display: inline-block;
    vertical-align: middle;
}

#stats h2 {
    color: #EFEFEF;
    font-size: 16px;
    letter-spacing: 2px;
}

#stats .statContainer {
    margin-top: 24px;
}

#stats .statContainer h3 {
    border-bottom: 2px dotted #32322C;
    color: #32322C;
    font-size: 12px;
    padding: 8px;
    width: 65%;
}

#stats .statContainer h3, #statsWrapper .advStatsChartWrapper {
    margin: 16px auto;
}

#stats .statContainer p {
    color: #3C92CA;
    font-size: 32px;
    margin: 16px 8px;
}

.statsButton {
    background: #3C92CA;
    color: #EFEFEF;
    cursor: pointer;
    font-size: 12px;
    margin: 16px 0;
    padding: 4px;
}

#statsWrapper .advStatsChartWrapper {
    width: 84%;
}


text:
require 'formula'

class Torrentcheck < Formula
  homepage 'http://torrentcheck.sourceforge.net/'
  url 'https://downloads.sourceforge.net/project/torrentcheck/torrentcheck-1.00.zip'
  sha256 'a839f9ac9669d942f83af33db96ce9902d84f85592c99b568ef0f5232ff318c5'

  def install
    inreplace "torrentcheck.c", "#include <malloc.h>", ""
    system ENV.cc, ENV.cflags, "torrentcheck.c", "sha1.c", "-o", "torrentcheck"
    bin.install 'torrentcheck'
  end

  test do
    system "#{bin}/torrentcheck"
  end
end


text:
<?php

namespace Entvalley\AppBundle\Domain;

use Entvalley\AppBundle\Entity\Project;

class TaskFilter
{
    private $map = [
        'unresolved' => [
            Status::UNASSIGNED
        ],
        'inprogress' => [
            Status::REOPENED,
            Status::ACCEPTED
        ]
    ];

    private $project = null;
    private $statusGroup = '';

    public function thatAre($statusGroup)
    {
        $this->statusGroup = strtolower($statusGroup);
    }

    public function withinProject(Project $project)
    {
        $this->project = $project;
    }

    public function getWithinProject()
    {
        return $this->project;
    }

    public function getStatuses()
    {
        if (isset($this->map[$this->statusGroup])) {
            return $this->map[$this->statusGroup];
        }

        return null;
    }
}


text:
package sa.com.is.store.imap;

/**
 * Represents a single response from the IMAP server.
 *
 * <p>
 * Tagged responses will have a non-null tag. Untagged responses will have a null tag. The
 * object will contain all of the available tokens at the time the response is received.
 * </p>
 */
public class ImapResponse extends ImapList {
    private static final long serialVersionUID = 6886458551615975669L;

    private ImapResponseCallback mCallback;

    private final boolean mCommandContinuationRequested;
    private final String mTag;

    public ImapResponse(ImapResponseCallback callback,
                        boolean mCommandContinuationRequested, String mTag) {
        this.mCallback = callback;
        this.mCommandContinuationRequested = mCommandContinuationRequested;
        this.mTag = mTag;
    }

    public boolean isContinuationRequested() {
        return mCommandContinuationRequested;
    }

    public String getTag() {
        return mTag;
    }

    public ImapResponseCallback getCallback() {
        return mCallback;
    }

    public void setCallback(ImapResponseCallback mCallback) {
        this.mCallback = mCallback;
    }

    public String getAlertText() {
        if (size() > 1 && ImapResponseParser.equalsIgnoreCase("[ALERT]", get(1))) {
            StringBuilder sb = new StringBuilder();
            for (int i = 2, count = size(); i < count; i++) {
                sb.append(get(i).toString());
                sb.append(' ');
            }
            return sb.toString();
        } else {
            return null;
        }
    }

    @Override
    public String toString() {
        return "#" + (mCommandContinuationRequested ? "+" : mTag) + "# " + super.toString();
    }
}


text:
module.exports = function () {
  // Size Report
  // https://github.com/ActivearkJWT/grunt-size-report
  // Generate a size report of build

  this.config('size_report', {
    build: {
      files: {
        src: '<%= path.build.root %>/{,**/}*.*'
      }
    }
  })

  // Watch
  // https://github.com/gruntjs/grunt-contrib-watch
  // Watches scss, js etc for changes and compiles them

  this.config.merge({
    watch: {
      configs: {
        files: ['gruntfile.js', '<%= path.tasks.root %>/{,**/}*'],
        options: {
          reload: true
        }
      }
    }
  })
}


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

namespace Eimbo.Aplicativo.Visao.Cadastro
{
    public interface IVisaoCadastroEmpresa
    {
        #region Busca
        Boolean AchouCidade(out long idCidade, out String nomeCidade);
        #endregion

        #region Ações
        void AdicionarDocumentoNoGrid(String ValorDocumento, String TipoDocumento);
        void AdicionarEnderecoNoGrid(String Logradouro, String Numero, String CEP, long IDCidade, String Cidade, String TipoEndereco);
        void AdicionarTelefoneNoGrid(String Telefone, String TipoTelefone);

        void LimparCamposDocumento();
        void LimparCamposEndereco();
        void LimparCamposTelefone();

        void LimparGridDeDocumentos();
        void LimparGridDeTelefones();
        void LimparGridDeEnderecos();

        void RemoverDocumentoDoGrid(int LinhaSelecionada);
        void RemoverEnderecoDoGrid(int LinhaSelecionada);
        void RemoverTelefoneDoGrid(int LinhaSelecionada);

        void VoltarParaTelaAnterior();
        #endregion

        #region Get
        String GetCEP();
        String GetCidade();
        DateTime GetDtFundacao();
        int GetLinhaDocumentoSelecionado();
        int GetLinhaEnderecoSelecionado();
        int GetLinhaTelefoneSelecionado();
        String GetLogradouro();
        long GetID();
        long GetIDCidade();
        String GetNome();
        String GetNumero();
        String GetTelefone();
        String GetTipoDocumento();
        String GetTipoEndereco();
        String GetTipoTelefone();
        String GetValorDocumento();

        String GetCEPDoGrid(int Indice);
        String GetCidadeDoGrid(int Indice);
        String GetLogradouroDoGrid(int Indice);
        long GetIDCidadeDoGrid(int Indice);
        String GetNumeroDoGrid(int Indice);
        String GetTelefoneDoGrid(int Indice);
        String GetTipoDocumentoDoGrid(int Indice);
        String GetTipoEnderecoDoGrid(int Indice);
        String GetTipoTelefoneDoGrid(int Indice);
        int GetTotalDeDocumentosDoGrid();
        int GetTotalDeEnderecosDoGrid();
        int GetTotalDeTelefonesDoGrid();
        String GetValorDocumentoDoGrid(int Indice);
        #endregion

        #region Set
        void SetDtFundacao(DateTime dtFundacao);
        void SetID(long id);
        void SetIDCidade(long id);
        void SetNome(String nome);
        void SetNomeCidade(String nomeCidade);
        #endregion

        #region Focus
        void MandarFocoNaDtFundacao();
        void MandarFocoNoLogradouro();
        void MandarFocoNoIDCidade();
        void MandarFocoNoNome();
        void MandarFocoNoTelefone();
        void MandarFocoNoTipoEndereco();
        void MandarFocoNoValorDocumento();
        #endregion
    }
}


text:
module Freshmail
  class Client
    attr_accessor :api_key, :api_secret

    URL = 'https://api.freshmail.com/'

    def initialize(api_key, api_secret)
      @api_key = api_key || self.class.api_key || ENV['FRESHMAIL_API_KEY']
      @api_key = @api_key.strip if @api_key
      @api_secret = api_secret || self.class.api_secret || ENV['FRESHMAIL_API_secret']
      @api_secret = @api_secret.strip if @api_secret

      raise Freshmail::CredentialsMissingError, 'api_key or api_secret are missing' unless @api_secret or @api_key
      raise Freshmail::CredentialsInvalidError, 'api_key or api_secret are invalid' unless self.ping['data'] == 'pong'
    end

    def ping
      call_freshmail(:get, 'ping')
    end

    def mail(mail_data = {})
      call_freshmail(:post, 'mail', mail_data)
    end

    def subscriber(sub_info = {})
      list = sub_info[:list]
      email = sub_info[:email]

      call_freshmail(:get, "subscriber/get/#{list}/#{email}")
    end

    def subscribers(sub_info = {})
      call_freshmail(:post, 'subscriber/getMultiple', sub_info)
    end

    def add_subscriber(sub_info = {})
      call_freshmail(:post, 'subscriber/add', sub_info)
    end

    def edit_subscriber(sub_info = {})
      call_freshmail(:post, 'subscriber/edit', sub_info)
    end

    def batch_add_subscriber(sub_info = {})
      call_freshmail(:post, 'subscriber/addMultiple', sub_info)
    end

    def batch_edit_subscriber(sub_info = {})
       call_freshmail(:post, 'subscriber/editMultiple', sub_info)
    end

    def delete_subscriber(sub_info = {})
      call_freshmail(:post, 'subscriber/delete', sub_info)
    end

    def batch_delete_subscriber(sub_info = {})
      call_freshmail(:post, 'subscriber/deleteMultiple', sub_info)
    end

    def lists
      call_freshmail(:get, 'subscribers_list/lists')
    end

    def create_list(list_info = {})
      call_freshmail(:post, 'subscribers_list/create', list_info)
    end

    def update_list(list_info = {})
      call_freshmail(:post, 'subscribers_list/update', list_info)
    end

    def delete_list(list_info = {})
      call_freshmail(:post, 'subscribers_list/delete', list_info)
    end

    protected
      def call_freshmail(call_type, get_data, json_data = nil)
        json_data_converted = json_data ? json_data.to_json : ''
        endpoint = "/rest/#{get_data}"

        conn = Faraday.new(:url => URL) do |faraday|
          faraday.request  :url_encoded
          # faraday.response :logger
          faraday.adapter  Faraday.default_adapter
        end

        response = conn.send(call_type) do |req|
          req.url endpoint
          req.headers['Content-Type'] = 'application/json'
          req.headers['X-Rest-ApiKey'] = self.api_key
          req.headers['X-Rest-ApiSign'] = api_sign(endpoint, json_data_converted)
          req.body = json_data_converted if req.method == :post
        end

        JSON.parse(response.body)
      end

      def api_sign(get_data, json_data)
        Digest::SHA1.hexdigest [
          self.api_key,
          get_data,
          json_data,
          self.api_secret
        ].join
      end
  end
end


text:
<?php
/**
 * Created by Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>.
 * Author: Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>
 * Project: jungle
 * IDE: PhpStorm
 * Date: 29.09.2016
 * Time: 16:26
 */
namespace Jungle\Application\Access {

	use Jungle\Application\Dispatcher\ProcessInterface;
	use Jungle\Di\InjectionAwareInterface;
	use Jungle\Di\InjectionAwareTrait;
	use Jungle\User\AccessControl\Context\ContextInterface;
	use Jungle\User\UserInterface;

	/**
	 * Class Context
	 * @package Jungle\Application\Access
	 */
	class Context extends \Jungle\User\AccessControl\Context\Context implements InjectionAwareInterface, ContextInterface{

		use InjectionAwareTrait;

		/**
		 * @return UserInterface
		 */
		public function getUser(){
			return isset($this->properties['user'])?$this->properties['user']:$this->getDi()->account->getUser();
		}

		/**
		 * @return mixed
		 */
		public function getProcess(){
			return isset($this->properties['process'])?$this->properties['process']:$this->getDi()->process;
		}

		/**
		 * @param $name
		 * @return mixed|null
		 */
		public function __get($name){
			switch($name){
				case 'process': return $this->getProcess();
			}
			return parent::__get($name);
		}

		/**
		 * @param $name
		 * @return bool
		 */
		public function __isset($name){
			switch($name){
				case 'process': return !!$this->getProcess();
			}
			return parent::__isset($name);
		}

		/**
		 * @param ProcessInterface $process
		 * @return $this
		 */
		public function setProcess(ProcessInterface $process){
			$this->properties['process'] = $process;
			return $this;
		}

	}
}