text:
{% load i18n %}
      {% if instances %}

          Name
          Image
          Size
          IP
          State

        {% for instance in instances %}

          {% if instance.id == selected_instance.id %}

                    Instance ID:
                    {{ selected_instance.id }}

                    Name:
                    {% if selected_instance.displayName != "" %}{{ selected_instance.displayName }}{% else %} None {% endif %}

                    Description:
                    {{ selected_instance.displayDescription }}

                    Region:
                    {{ selected_instance.region.name }}

                    Size:
                    {{ selected_instance.instance_type }}

                    State:
                    {{ selected_instance.state }}

                    Image ID:
                    {{ selected_instance.image_id }}

                    IP Address:
                    {{ selected_instance.dns_name }}

                  {% if instance.state == "running" %}
                  Show Console
                  {% if enable_vnc %}
                    VNC{% endif %}
                  {% endif %}
                  Edit Instance

                    <form id="form_terminate_{{ instance.id }}" class="form-terminate" method="post" action="{% url nova_instances_terminate project.projectname %}" >
                      <input name="instance_id" type="hidden" value="{{ instance.id }}" />
                      <input name="is_floating_ip" type="hidden" value="{% if "10." in instance.dns_name %}IS_PRIVATE_IP{% else %}IS_FLOATING_IP{% endif %}" />
                      <input id="terminate_{{instance.id}}" class="terminate" type="submit" value="Terminate" />
                      {% csrf_token %}
                    </form>

          {% else %}

            {% if instance.displayName %}{{ instance.displayName }}{% endif %} ({{ instance.id }})

            {{ instance.image_id }}
            {{ instance.instance_type }}
            {{ instance.dns_name }}
            {{ instance.state }}

              <form id="form_terminate_{{ instance.id }}" class="form-terminate" method="post" action="{% url nova_instances_terminate project.projectname %}" >
                <input name="instance_id" type="hidden" value="{{ instance.id }}" />
                <input name="is_floating_ip" type="hidden" value="{% if "10." in instance.dns_name %}IS_PRIVATE_IP{% else %}IS_FLOATING_IP{% endif %}" />
                <input id="terminate_{{instance.id}}" class="terminate" type="submit" value="Terminate" />
                {% csrf_token %}
              </form>
              {% if instance.state == "running" %}
              Show Console
              {% endif %}

          {% endif %}

        {% endfor %}

      {% else %}

            {% trans "No instances are currently running. You may start a new instance from the"%} images tab.

      {% endif %}


text:
package ssa

// This file defines a number of miscellaneous utility functions.

import (
	"fmt"
	"go/ast"
	"go/token"
	"io"
	"os"

	"github.com/polaris1119/go.tools/go/types"
)

func unreachable() {
	panic("unreachable")
}

//// AST utilities

// unparen returns e with any enclosing parentheses stripped.
func unparen(e ast.Expr) ast.Expr {
	for {
		p, ok := e.(*ast.ParenExpr)
		if !ok {
			break
		}
		e = p.X
	}
	return e
}

// isBlankIdent returns true iff e is an Ident with name "_".
// They have no associated types.Object, and thus no type.
//
func isBlankIdent(e ast.Expr) bool {
	id, ok := e.(*ast.Ident)
	return ok && id.Name == "_"
}

//// Type utilities.  Some of these belong in go/types.

// isPointer returns true for types whose underlying type is a pointer.
func isPointer(typ types.Type) bool {
	_, ok := typ.Underlying().(*types.Pointer)
	return ok
}

// deref returns a pointer's element type; otherwise it returns typ.
func deref(typ types.Type) types.Type {
	if p, ok := typ.Underlying().(*types.Pointer); ok {
		return p.Elem()
	}
	return typ
}

// DefaultType returns the default "typed" type for an "untyped" type;
// it returns the incoming type for all other types.  The default type
// for untyped nil is untyped nil.
//
// Exported to ssa/interp.
//
// TODO(gri): this is a copy of go/types.defaultType; export that function.
//
func DefaultType(typ types.Type) types.Type {
	if t, ok := typ.(*types.Basic); ok {
		k := t.Kind()
		switch k {
		case types.UntypedBool:
			k = types.Bool
		case types.UntypedInt:
			k = types.Int
		case types.UntypedRune:
			k = types.Rune
		case types.UntypedFloat:
			k = types.Float64
		case types.UntypedComplex:
			k = types.Complex128
		case types.UntypedString:
			k = types.String
		}
		typ = types.Typ[k]
	}
	return typ
}

// logStack prints the formatted "start" message to stderr and
// returns a closure that prints the corresponding "end" message.
// Call using 'defer logStack(...)()' to show builder stack on panic.
// Don't forget trailing parens!
//
func logStack(format string, args ...interface{}) func() {
	msg := fmt.Sprintf(format, args...)
	io.WriteString(os.Stderr, msg)
	io.WriteString(os.Stderr, "\n")
	return func() {
		io.WriteString(os.Stderr, msg)
		io.WriteString(os.Stderr, " end\n")
	}
}

// newVar creates a 'var' for use in a types.Tuple.
func newVar(name string, typ types.Type) *types.Var {
	return types.NewParam(token.NoPos, nil, name, typ)
}

// anonVar creates an anonymous 'var' for use in a types.Tuple.
func anonVar(typ types.Type) *types.Var {
	return newVar("", typ)
}

var lenResults = types.NewTuple(anonVar(tInt))

// makeLen returns the len builtin specialized to type func(T)int.
func makeLen(T types.Type) *Builtin {
	lenParams := types.NewTuple(anonVar(T))
	return &Builtin{
		name: "len",
		sig:  types.NewSignature(nil, nil, lenParams, lenResults, false),
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace DrewM\Drip;

class Response
{
    public $status  = null;
    public $error   = null;
    public $message = null;

    protected $data = [];

    public function __construct($meta, $body)
    {
        $this->process_meta($meta);
        $this->process_body($body);
        $this->handle_errors();
    }

    protected function process_meta($meta)
    {
        if (isset($meta['http_code'])) {
            $this->status = (int) $meta['http_code'];
        }
    }

    protected function process_body($body)
    {
        $decoded_body = json_decode($body, true);
        if (is_array($decoded_body)) {
            $this->data = $decoded_body;
        }
    }

    protected function handle_errors()
    {
        if (is_array($this->data) && isset($this->data['errors'])) {
            $this->error   = $this->data['errors'][0]['code'];
            $this->message = $this->data['errors'][0]['message'];
        }
    }

    public function __get($name)
    {
        if (is_array($this->data) && isset($this->data[$name])) {
            return $this->data[$name];
        }

        return false;
    }

    public function get()
    {
        return $this->data;
    }

    public function __toString()
    {
        return print_r($this->data, true);
    }

    public function __debugInfo()
    {
        return $this->data;
    }
}


text:
@implementation MJExtensionConfig

+ (void)load {
    [NSObject mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"ID":@"id"
                 };
    }];

    [Creator mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"descriptionField":@"description"
                 };
    }];

    [Creator mj_setupReplacedKeyFromPropertyName121:^id(NSString *propertyName) {
        return [propertyName mj_underlineFromCamel];
    }];

    [Live mj_setupReplacedKeyFromPropertyName121:^id(NSString *propertyName) {
        return [propertyName mj_underlineFromCamel];
    }];

    [Extra mj_setupReplacedKeyFromPropertyName121:^id(NSString *propertyName) {
        return [propertyName mj_underlineFromCamel];
    }];

    [Label mj_setupReplacedKeyFromPropertyName121:^id(NSString *propertyName) {
        return [propertyName mj_underlineFromCamel];
    }];

    [RootClass mj_setupReplacedKeyFromPropertyName121:^id(NSString *propertyName) {
        return [propertyName mj_underlineFromCamel];
    }];
}

@end


text:
<?php

namespace app\models;

/**
 * This is the ActiveQuery class for [[Memo]].
 *
 * @see Memo
 */
class MemoQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        $this->andWhere('[[status]]=1');
        return $this;
    }*/

    /**
     * @inheritdoc
     * @return Memo[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return Memo|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
/*
 * http_server_test.cpp
 *
 *  Created on: Oct 26, 2014
 *      Author: liao
 */
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <unistd.h>
#include "simple_log.h"
#include "http_server.h"
#include "threadpool.h"

void file_action(Request &request, Json::Value &root) {
	/*
    std::string fileId = request.get_param("fileId");
	std::string files = request.get_param("files");
	std::string files2 = request.get_param("files2");

	LOG_INFO("get fileId:%s", fileId.c_str());
	LOG_INFO("get files:%s", files.c_str());
	LOG_INFO("get files2:%s", files2.c_str());
    */
    // get file items
    std::vector<FileItem> *items = request.get_body()->get_file_items();
    for (size_t i = 0; i < items->size(); i++) {
        FileItem &item = (*items)[i];
        if (item.is_file()) {
            LOG_INFO("item name:%s, filename:%s, content-type:%s, data:%d",
                    item.get_fieldname()->c_str(), item.get_filename()->c_str(),
                    item.get_content_type()->c_str(), item.get_data()->size());
        } else {
            LOG_INFO("item name:%s, data:%s",
                    item.get_fieldname()->c_str(), item.get_data()->c_str());
        }
    }
	root["code"] = 0;
	root["msg"] = "login success!";
}

void response_file(Request &request, Response &response) {
    Json::Value root;
    std::string file_path = "." + request.get_request_uri();
    std::ifstream is(file_path.c_str());
    if (!is.good()) {
        root["code"] = -1;
        root["msg"] = "file not found:" + file_path;
        response.set_body(root);
        return;
    }
    std::stringstream ss;
    ss << is.rdbuf();//read the file
    std::string file_content = ss.str();
    response._body = file_content;
    response.set_head("Content-Type", "text/html");
}

int main(int argc, char **args) {
    int ret = log_init("./conf", "simple_log.conf");
    if (ret != 0) {
        printf("log init error!");
        return 0;
    }
    if (argc < 2) {
        LOG_ERROR("usage: ./http_server_test [port]");
        return -1;
    }

    HttpServer http_server;

    http_server.add_mapping("/test/issue5/issue5.html", response_file);
    http_server.add_mapping("/file_action", file_action, POST_METHOD);

    http_server.set_port(atoi(args[1]));
    http_server.set_backlog(100000);
    http_server.set_max_events(100000);
    http_server.start_sync();
    return 0;
}


text:
try:
    import jug
    from jug import value
    import jug.options
    from jug.tests.utils import task_reset, simple_execute
except ImportError:
    from nose import SkipTest
    def task_reset(f):
        def g():
            raise SkipTest()
        return g

@task_reset
def test_nfoldcrossvalidation():
    store, space = jug.jug.init('milk/tests/data/jugparallel_jugfile.py', 'dict_store')
    simple_execute()
    assert len(jug.value(space['classified'])) == 2
    assert len(jug.value(space['classified_wpred'])) ==3

@task_reset
def test_kmeans():
    store, space = jug.jug.init('milk/tests/data/jugparallel_kmeans_jugfile.py', 'dict_store')
    simple_execute()
    assert len(value(space['clustered'])) == 2


text:
package com.cardpay.pccredit.intopieces.model;

import java.util.Date;

import com.wicresoft.jrad.base.database.model.ModelParam;
import com.wicresoft.jrad.base.database.model.BusinessModel;

@ModelParam(table = "qz_appln_dbrxx")
public class QzApplnDbrxx extends BusinessModel {

	private static final long serialVersionUID = 1L;

	private String customerId;
	private String applicationId;
	private String name;
	private String sex;
	private Date birthday;
	private String yeah;
	private String globalType;
	private String globalId;
	private String haveGlobalIdCopy;
	private String phone_1;
	private String phone_2;
	private String phoneOther;
	private String workUnitName;
	private String workYear;
	private String workUnitAddr;
	private String workUnitPhone;
	private String yeahIncome;
	private String haveProveFile;
	private String fileName;
	private String marriage;
	private String homePhone;
	private String homeAddr;
	private String homeType;

	public String getCustomerId() {
		return customerId;
	}
	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}
	public String getApplicationId() {
		return applicationId;
	}
	public void setApplicationId(String applicationId) {
		this.applicationId = applicationId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getYeah() {
		return yeah;
	}
	public void setYeah(String yeah) {
		this.yeah = yeah;
	}
	public String getGlobalType() {
		return globalType;
	}
	public void setGlobalType(String globalType) {
		this.globalType = globalType;
	}
	public String getGlobalId() {
		return globalId;
	}
	public void setGlobalId(String globalId) {
		this.globalId = globalId;
	}
	public String getHaveGlobalIdCopy() {
		return haveGlobalIdCopy;
	}
	public void setHaveGlobalIdCopy(String haveGlobalIdCopy) {
		this.haveGlobalIdCopy = haveGlobalIdCopy;
	}
	public String getPhone_1() {
		return phone_1;
	}
	public void setPhone_1(String phone_1) {
		this.phone_1 = phone_1;
	}
	public String getPhone_2() {
		return phone_2;
	}
	public void setPhone_2(String phone_2) {
		this.phone_2 = phone_2;
	}
	public String getPhoneOther() {
		return phoneOther;
	}
	public void setPhoneOther(String phoneOther) {
		this.phoneOther = phoneOther;
	}
	public String getWorkUnitName() {
		return workUnitName;
	}
	public void setWorkUnitName(String workUnitName) {
		this.workUnitName = workUnitName;
	}
	public String getWorkYear() {
		return workYear;
	}
	public void setWorkYear(String workYear) {
		this.workYear = workYear;
	}
	public String getWorkUnitAddr() {
		return workUnitAddr;
	}
	public void setWorkUnitAddr(String workUnitAddr) {
		this.workUnitAddr = workUnitAddr;
	}
	public String getWorkUnitPhone() {
		return workUnitPhone;
	}
	public void setWorkUnitPhone(String workUnitPhone) {
		this.workUnitPhone = workUnitPhone;
	}
	public String getYeahIncome() {
		return yeahIncome;
	}
	public void setYeahIncome(String yeahIncome) {
		this.yeahIncome = yeahIncome;
	}
	public String getHaveProveFile() {
		return haveProveFile;
	}
	public void setHaveProveFile(String haveProveFile) {
		this.haveProveFile = haveProveFile;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getMarriage() {
		return marriage;
	}
	public void setMarriage(String marriage) {
		this.marriage = marriage;
	}
	public String getHomePhone() {
		return homePhone;
	}
	public void setHomePhone(String homePhone) {
		this.homePhone = homePhone;
	}
	public String getHomeAddr() {
		return homeAddr;
	}
	public void setHomeAddr(String homeAddr) {
		this.homeAddr = homeAddr;
	}
	public String getHomeType() {
		return homeType;
	}
	public void setHomeType(String homeType) {
		this.homeType = homeType;
	}
}


text:
import AbstractFormView from 'OpenOrchestra/Service/Form/View/AbstractFormView'
import ApplicationError from 'OpenOrchestra/Service/Error/ApplicationError'
import FlashMessage     from 'OpenOrchestra/Service/FlashMessage/FlashMessage'
import FlashMessageBag  from 'OpenOrchestra/Service/FlashMessage/FlashMessageBag'

/**
 * @class NewNodeFormView
 */
class NewNodeFormView extends AbstractFormView
{
    /**
     * Initialize
     * @param {Form}   form
     * @param {Array}  siteLanguages
     * @param {string} parentId
     * @param {string} language
     * @param {int}    order
     */
    initialize({form, siteLanguages, parentId, language, order}) {
        super.initialize({form : form});
        this._siteLanguages = siteLanguages;
        this._parentId = parentId;
        this._language = language;
        this._order = order;
    }

    /**
     * @inheritdoc
     */
    render() {
        let template = this._renderTemplate('Node/newNodeView',
            {
                language: this._language,
                parentId: this._parentId,
                order: this._order,
                siteLanguages: this._siteLanguages
            }
        );
        this.$el.html(template);
        this._$formRegion = $('.form-new', this.$el);
        super.render();

        return this;
    }

    /**
     * @return {Object}
     */
    getStatusCodeForm(event) {
        return {
            '201': $.proxy(this._redirectNew, this),
            '422': $.proxy(this.refreshRender, this)
        }
    }

    /**
     * Redirect after created new node
     *
     * @private
     */
    _redirectNew(data, textStatus, jqXHR) {
        let nodeId = jqXHR.getResponseHeader('nodeId');
        if (null === nodeId) {
            throw new ApplicationError('Invalid nodeId');
        }
        let url = Backbone.history.generateUrl('showNode', {nodeId: nodeId, language: this._language});
        if (data != '') {
            let message = new FlashMessage(data, 'success');
            FlashMessageBag.addMessageFlash(message);
        }
        Backbone.Events.trigger('form:deactivate', this);
        Backbone.history.navigate(url, true);
    }
}

export default NewNodeFormView;


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.example.switchbutton.SwitchButton
        android:id="@+id/wiperSwitch1"
        android:layout_width="40dp"
        android:layout_height="20dp" />

</LinearLayout>


text:
module ImageAttributes
  include AttributeReference

  def image val=nil
    attribute_reference 'IMAGE', ImageWidget, val
  end

  def iminactive val=nil
    attribute_reference 'IMINACTION', ImageWidget, val
  end

  def impress val=nil
    attribute_reference 'IMPRESS', ImageWidget, val
  end
end


text:
FOUNDATION_EXPORT double SYAlipaySDKVersionNumber;
FOUNDATION_EXPORT const unsigned char SYAlipaySDKVersionString[];


text:
require_relative '../spec_helper'
require_relative '../helpers/matchers'

describe 'netapp::lif' do
  context 'without :step_into' do
    let(:chef_run) { ChefSpec::Runner.new.converge(described_recipe)}

    it 'creates a network interface' do
      expect(chef_run).to create_netapp_lif('demo-interface').with(
        address: "192.168.1.200",
        home_node: "cluster1-01",
        home_port: "e0a",
        role: "cluster_mgmt",
        svm: "cluster1",
        netmask: "255.255.255.0"
        )
    end

    it 'deletes a network interface' do
      expect(chef_run).to delete_netapp_lif('demo-del-interface').with(
          svm: "cluster1"
        )
    end
  end
end


text:
<?php

/**
 *
 * @author ero <choeringa@gmail.com>
 */
abstract class DataObject {

  public abstract function save();

  protected function edit() {

  }

  protected function __create() {

  }

  public abstract function delete();

  public abstract static function inStore($id, $parent = null);

  public abstract static function fromStore($id, $parent = null);
}

?>


text:
import os
import unittest
os.environ.setdefault('HRZ_CONFIG', 'conf.py')

from hrz import hrz

class HrzTestCase(unittest.TestCase):
    """
    Horizon test base class
    """
    def setUp(self):
        self.app = hrz.app.test_client()


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>DocStrap Index</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cosmo.css">

		DocStrap
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">

        </button>

				Modules

app.components

app.core

app.shared

core.internals

internals.exception

internals.logger

internals.router

app

shared.spinner

				Global

error

info

moment

success

warning

            <form class="navbar-form" role="search">

                    <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">

                        <button class="btn btn-default" id="search-submit"></button>

            </form>

QANGULARS - work in progress

Quick Angularjs Scaffolding is my alternation of a project template built with a popular Yeoman's Angular generator.

Yeoman's Angular Generator is a great tool and I enjoy using it, but every time when I start an AngularJS project, I find myself tweaking the project template  (mostly in the same way) to suit my needs. That leads me to spend time on unnecessary things, which is not productive, especially when I am under a deadline constraint.

This project will evolve with time and needs, but main idea behind this project is to minimize that waste of time as much as possible, if not to eliminate it completely in some cases.

NOTE

All files are using 2 space indentation, if you wish to use 4 space indentation and be consistent throughout the project, you will have to manually update every file.

How to use it?

Simply clone the repo to your working directory and start using it

# clone the project
git clone https://github.com/Devgaze/qangulars.git

# run grunt server
grunt serve

# to build the project
grunt build

and then start developing, or modify it to meet your requirements.

For testing you have available following commands

# run tests
grunt test

# run end-to-end tests with protractor
grunt e2e

For deployment to your live server, use the following

# deploy to live server
grunt deploy

And for creating a documentation use following command

# create documentation
grunt bookify

Documentation is generated in doc/ folder.

What is changed?

Mostly focusing on project structure and updating deprecated packages where some were added, some deleted and some marked deprecated updated with the favoured versions.

For initial version (1.0.0) following things were done:

replaced deprecated autoprefixer-core with autoprefixer

updated grunt-postcss to newer version

removed grunt-angular-templates but feel free to use it if you usually do

added karma-spec-reporter for more descriptive test output

if you prefer default reporter, in config/karma.config.js file just comment out line saying reporters: ['spec'],

added load-grunt-config module to de-clutter Gruntfile.js

moved grunt config files into grunt/ directory to keep everything neat and tidy (grunt tasks are defined in grunt/aliases.js)

added connect_modrewrite module for easier mod rewrites on connect (dev) server

added grunt-karma

replaced Yeoman's way of running tests to grunt test

removed grunt-contrib-compass and added grunt-sass package

project restructured to be more aligned to what Papa John's and AngularJs Team recommends

some things were omitted and some altered though

not using toastr

blocks renamed to internals

added additional global object to IIFE's called projectName which should ideally be renamed per project

added grunt-jsdoc and ink-docstrap for building documentation - it is standalone command, but you can integrate it in build process

stay tuned - more will be added here before official release

Project structure

.
├── app
│   ├── images
│   ├── scripts
│   │   ├── components
│   │   │   ├── welcome
│   │   │   │   ├── _header.partial.html
│   │   │   │   ├── _welcome.scss
│   │   │   │   ├── welcome.controller.js
│   │   │   │   ├── welcome.controller.spec.js
│   │   │   │   ├── welcome.module.js
│   │   │   │   ├── welcome.routes.js
│   │   │   │   └── welcome.view.html
│   │   │   └── components.module.js
│   │   ├── core
│   │   │   ├── internals
│   │   │   │   ├── exception
│   │   │   │   │   ├── exception-handler.provider.js
│   │   │   │   │   ├── exception.factory.js
│   │   │   │   │   └── exception.module.js
│   │   │   │   ├── logger
│   │   │   │   │   ├── logger.factory.js
│   │   │   │   │   └── logger.module.js
│   │   │   │   ├── router
│   │   │   │   │   ├── router-helper.provider.js
│   │   │   │   │   └── router.module.js
│   │   │   │   └── internals.module.js
│   │   │   ├── core.constants.js
│   │   │   └── core.module.js
│   │   ├── shared
│   │   │   ├── spinner
│   │   │   │   ├── _spinner.style.scss
│   │   │   │   ├── spinner.directive.js
│   │   │   │   ├── spinner.module.js
│   │   │   │   └── spinner.view.html
│   │   │   └── shared.module.js
│   │   └── app.module.js
│   ├── styles
│   │   └── main.scss
│   ├── 404.html
│   ├── favicon.ico
│   ├── humans.txt
│   ├── index.html
│   └── robots.txt
├── config
│   └── karma.conf.js
├── grunt
│   ├── aliases.js
│   ├── cdnify.js
│   ├── clean.js
│   ├── concurrent.js
│   ├── connect.js
│   ├── copy.js
│   ├── filerev.js
│   ├── htmlmin.js
│   ├── imagemin.js
│   ├── jscs.js
│   ├── jshint.js
│   ├── karma.js
│   ├── ngAnnotate.js
│   ├── postcss.js
│   ├── sass.js
│   ├── svgmin.js
│   ├── usemin.js
│   ├── useminPrepare.js
│   ├── watch.js
│   └── wiredep.js
├── Gruntfile.js
├── LICENSE
├── README.md
├── bower.json
└── package.json

Maintenance - what is the plan?

As I will primarily use this repo for creating my future projects, I will check, and if necessary update, both bower and npm modules on a monthly basis.

If you have suggestions or doubts feel free to create an issue.

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Search results

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

	DocStrap Copyright © 2012-2015 The contributors to the JSDoc3 and DocStrap projects.

	Documentation generated by JSDoc 3.4.0

		on Sun May 29th 2016

	using the DocStrap template.


text:
// This file is automatically generated.

package adila.db;

/*
 * Huawei Y6 Pro
 *
 * DEVICE: HWTIT-U6582
 * MODEL: HUAWEI TIT-U02
 */
final class hwtit2du6582_huawei20tit2du02 {
    public static final String DATA = "Huawei|Y6 Pro|";
}


text:
class IdsPlease
  module Parsers
    class Reddit < IdsPlease::Parsers::Base

      MASK = /reddit/i

      class << self
        def parse_link(link)
          link.path.split('/')[2]
        end
      end

    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:jaxws="http://cxf.apache.org/jaxws"

	xsi:schemaLocation="
	        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
	        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
	        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
			http://cxf.apache.org/jaxws     http://cxf.apache.org/schemas/jaxws.xsd
			">
	<context:annotation-config />
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<jaxws:endpoint id="echoWs" implementor="org.bachelor.demo.test.ws.EchoWsImpl"
		address="/Echo" />

</beans>


text:
const { isString } = require('lodash');
const { createToken } = require('chevrotain');
const { NAME, KEYWORD, namePattern } = require('./shared-tokens');

module.exports = {
  createTokenFromConfig,
};

function createTokenFromConfig(config) {
  if (!config) {
    throw new Error("Can't create a token without the proper config.");
  }
  // JDL has a great many keywords. Keywords can conflict with identifiers in a parsing
  // library with a separate lexing phase.
  // See: https://github.com/SAP/chevrotain/blob/master/examples/lexer/keywords_vs_identifiers/keywords_vs_identifiers.js
  // a Concise way to resolve the problem without manually adding the "longer_alt" property dozens of times.
  if (isString(config.pattern) && namePattern.test(config.pattern)) {
    config.longer_alt = NAME;
    if (!config.categories) {
      config.categories = [];
    }
    config.categories.push(KEYWORD);
  }

  // readable labels for diagrams
  if (isString(config.pattern) && !config.label) {
    config.label = `'${config.pattern}'`;
  }

  return createToken(config);
}


text:
using Skele.Core;
using Skele.Interop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Skele.Migrations
{
    class InitCommandHandler : CommandHandlerBase<InitCommand>
    {
        private DatabaseDriver driver;

        public InitCommandHandler(DatabaseDriver driver)
        {
            this.driver = driver;
        }

        public override void Execute(InitCommand input)
        {
            var session = GetOrCreateSession("Katana");
            var metadata = session.Describe();

            if (!metadata.Tables.Contains("__Version"))
            {
                Log.WriteLine("Version table not found, creating...");

                var table = new TableDescriptor();
                table.Name = "__Version";
                table.Columns.Add(new ColumnDescriptor { Name = "Major", DataType = typeof(int) });
                table.Columns.Add(new ColumnDescriptor { Name = "Minor", DataType = typeof(int) });
                table.Columns.Add(new ColumnDescriptor { Name = "Patch", DataType = typeof(int) });
                table.Columns.Add(new ColumnDescriptor { Name = "InstallDate", DataType = typeof(DateTime) });

                session.CreateTable(table);
            }

            Log.WriteLine("Database initialized.");
        }

        private DatabaseSession GetOrCreateSession(string name)
        {
            if (!driver.Exists(name))
            {
                Log.WriteLine("Database '{0}' not found, creating...", name);
                return driver.Create(name);
            }
            else
            {
                return driver.Open(name);
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta charset="utf-8"/>
    <title>    Phing API Documentation » \IdentityMapper
</title>
    <meta name="author" content=""/>
    <meta name="description" content=""/>

            <link href="../css/template.css" rel="stylesheet" media="all"/>

            <link rel="shortcut icon" href="../img/favicon.ico"/>
        <link rel="apple-touch-icon" href="../img/apple-touch-icon.png"/>
        <link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png"/>
        <link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png"/>

                Phing API Documentation

                                API Documentation

                                Charts

                                         Class hierarchy diagram

                                Reports

                                         Errors

                                         Markers

                                         Deprecated

            Back to top

                Javascript is disabled; several features are only available if Javascript is enabled.

        <button class="btn details" title="Show descriptions and method names"></button>
        <button class="btn simple" title="Show only method names"></button>

        <button class="btn public active" title="Show public elements">Public</button>
        <button class="btn protected" title="Show protected elements">Protected</button>
        <button class="btn private" title="Show private elements">Private</button>
        <button class="btn inherited active" title="Show inherited elements">Inherited</button>

             Methods

            The mapper implementation. Basically does nothing in this case.
main

            Ignored here.
setFrom

            Ignored here.
setTo

» Protected

» Private

             Constants

IdentityMapper

                                                                Implements \FileNameMapper

This mapper does nothing ;)

                                        author

Andreas Aderhold andi@binarycloud.com

                                        author

Hans Lellelid hans@xmpl.org

                                        version

$Id: c534489effaaf9876a0ec7d087e5b37f8521c43c $

                                        package

phing.mappers

 Methods

The mapper implementation. Basically does nothing in this case.

main(string $sourceFileName) : array

Arguments

$sourceFileName

                                                string

The data the mapper works on.

Response

                                        array

The data after the mapper has been applied

Ignored here.

setFrom(string $from) : void

Arguments

$from

                                                string

On what this mapper should work

Ignored here.

setTo(string $to) : void

Arguments

$to

                                                string

To what this mapper should convert the from string

\\

\IdentityMapper

            Template is built using Twitter Bootstrap 2 and icons provided by
            Glyphicons.

            Documentation is powered by phpDocumentor  and

            generated on Thu, 13 Oct 2016 11:15:01 +0200.


text:
Zabbix monitoring template for Mesos 1.0.1 and Zabbix 3.0

### Zabbix server
1. Put getMesosStats.py in your external scripts directory
2. Make it executable (chmod +x ...)

### Zabbix frontend
4. Import templates for master and agent
5. Link it with desired hosts
6. Set {$MESOS_PORT} macro (5050 for masters, 5051 for agents)
6. Enable or disable items at your will


text:
require 'spec_helper'

feature Organization do
  let!(:organization) { create(:organization) }
  let!(:organization_admin_role) { Role.find_by(name: 'organization_admin', resource: organization) }
  let(:organization_admin) { create(:user, role_ids: [organization_admin_role.id]) }
  let(:admin_user) { create(:admin) }

  shared_examples 'successfully updates an organization' do
    scenario 'updates a exsisting organization', feature: true, js: true do
      visit edit_admin_organization_path(organization)
      fill_in 'organization_name', with: 'changed name'

      click_button 'Update Organization'

      organization.reload
      expect(flash).to eq('Organization successfully updated')
      expect(organization.name).to eq('changed name')
    end
  end

  context 'signed in as site admin' do
    before do
      sign_in admin_user
    end
    scenario 'creates a new organization', feature: true, js: true do
      visit new_admin_organization_path
      fill_in 'organization_name', with: 'Organization name'

      click_button 'Create Organization'

      expect(flash).to eq('Organization successfully created')
      expect(Organization.last.name).to eq('Organization name')
    end

    it_behaves_like 'successfully updates an organization'
  end

  context 'signed in as organization admin' do
    before do
      sign_in organization_admin
    end
    scenario "can't create new organization", feature: true, js: true do
      visit new_admin_organization_path

      expect(flash).to eq('You are not authorized to access this page.')
    end

    it_behaves_like 'successfully updates an organization'
  end

  context 'anonymously' do
    scenario 'index should link to conferences list' do
      visit organizations_path

      expect(page).to have_link('Conferences', href: "/organizations/#{organization.id}/conferences")
    end
  end
end


text:
@implementation OWSegmentingAppleEncoder
@synthesize segmentationTimer, queuedAssetWriter;
@synthesize queuedAudioEncoder, queuedVideoEncoder;
@synthesize audioBPS, videoBPS, shouldBeRecording;
@synthesize segmentCount;
@synthesize manifestGenerator;
@synthesize ffmpegWrapper;

- (void) dealloc {
    if (self.segmentationTimer) {
        [self performSelectorOnMainThread:@selector(invalidateTimer) withObject:nil waitUntilDone:NO];
    }
}

- (void) finishEncoding {
    self.readyToRecordAudio = NO;
    self.readyToRecordVideo = NO;
    self.shouldBeRecording = NO;
    if (self.segmentationTimer) {
        [self performSelectorOnMainThread:@selector(invalidateTimer) withObject:nil waitUntilDone:NO];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super finishEncoding];
    //[[OWCaptureAPIClient sharedClient] finishedRecording:self.recording];
}

- (void) invalidateTimer {
    [self.segmentationTimer invalidate];
    self.segmentationTimer = nil;
}

- (void) createAndScheduleTimer {
    self.segmentationTimer = [NSTimer scheduledTimerWithTimeInterval:segmentationInterval target:self selector:@selector(segmentRecording:) userInfo:nil repeats:YES];
    //[[NSRunLoop mainRunLoop] addTimer:segmentationTimer forMode:NSDefaultRunLoopMode];
}

- (id) initWithBasePath:(NSString *)newBasePath segmentationInterval:(NSTimeInterval)timeInterval {
    if (self = [super init]) {
        self.basePath = newBasePath;
        self.shouldBeRecording = YES;
        segmentationInterval = timeInterval;
        [self performSelectorOnMainThread:@selector(createAndScheduleTimer) withObject:nil waitUntilDone:NO];
        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedBandwidthUpdateNotification:) name:kOWCaptureAPIClientBandwidthNotification object:nil];
        segmentingQueue = dispatch_queue_create("Segmenting Queue", DISPATCH_QUEUE_SERIAL);
        self.segmentCount = 0;
        self.ffmpegWrapper = [[FFmpegWrapper alloc] init];
        NSString *manifestFileName = @"chunklist.m3u8";
        NSString *m3u8Path = [newBasePath stringByAppendingPathComponent:manifestFileName];
        self.manifestGenerator = [[OWManifestGenerator alloc] initWithM3U8Path:m3u8Path targetSegmentDuration:(int)timeInterval];

        NSError *error = nil;
        NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
        NSString *crossDomainPath = [[NSBundle mainBundle] pathForResource:@"crossdomain" ofType:@"xml"];
        NSString *crossdomainOutputPath = [self.basePath stringByAppendingPathComponent:@"crossdomain.xml"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager copyItemAtPath:crossDomainPath toPath:crossdomainOutputPath error:&error];
        if (error) {
            NSLog(@"error copying cross domain file: %@", error.userInfo);
        }
        NSString *rootPlaylistPath = [[NSBundle mainBundle] pathForResource:@"playlist" ofType:@"m3u8"];
        NSString *rootPlaylistOutputPath = [self.basePath stringByAppendingPathComponent:@"playlist.m3u8"];
        [fileManager copyItemAtPath:rootPlaylistPath toPath:rootPlaylistOutputPath error:&error];
        if (error) {
            NSLog(@"error copying cross domain file: %@", error.userInfo);
        }

        NSString *html = [NSString stringWithContentsOfFile:htmlFilePath encoding:NSUTF8StringEncoding error:&error];
        if (error) {
            NSLog(@"error loading html: %@", error.userInfo);
        }
        NSString *newHTML = [html stringByReplacingOccurrencesOfString:@"{% manifest_file_name %}" withString:manifestFileName];
        NSString *htmlIndexPath = [self.basePath stringByAppendingPathComponent:@"index.html"];
        [newHTML writeToFile:htmlIndexPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if (error) {
            NSLog(@"error writing index.html: %@", error.userInfo);
        }

        NSString *playlistPath = [[NSBundle mainBundle] pathForResource:@"playlist" ofType:@"m3u8"];
        NSString *playlistKey = [NSString stringWithFormat:@"%@/%@",self.uuid, [playlistPath lastPathComponent]];
        [[OWSharedS3Client sharedClient] postObjectWithFile:playlistPath bucket:BUCKET_NAME key:playlistKey acl:@"public-read" success:^(S3PutObjectResponse *responseObject) {
            NSLog(@"success sending first manifest");
        } failure:^(NSError *error) {
            NSLog(@"error: %@", error.userInfo);
        }];
    }
    return self;
}

- (void) receivedBandwidthUpdateNotification:(NSNotification*)notification {
    double bps = [[[notification userInfo] objectForKey:@"bps"] doubleValue];
    double vbps = (bps*0.5) - audioBPS;
    if (vbps < kMinVideoBitrate) {
        vbps = kMinVideoBitrate;
    }
    if (vbps > kMaxVideoBitrate) {
        vbps = kMaxVideoBitrate;
    }
    self.videoBPS = vbps;
    //self.videoBPS = videoBPS * 0.75;
    NSLog(@"bps: %f\tvideoBPS: %d\taudioBPS: %d", bps, videoBPS, audioBPS);
}

- (void) segmentRecording:(NSTimer*)timer {
    if (!shouldBeRecording) {
        [timer invalidate];
    }
    AVAssetWriter *tempAssetWriter = self.assetWriter;
    AVAssetWriterInput *tempAudioEncoder = self.audioEncoder;
    AVAssetWriterInput *tempVideoEncoder = self.videoEncoder;
    self.assetWriter = queuedAssetWriter;
    self.audioEncoder = queuedAudioEncoder;
    self.videoEncoder = queuedVideoEncoder;
    NSLog(@"Switching encoders");

    dispatch_async(segmentingQueue, ^{
        if (tempAssetWriter.status == AVAssetWriterStatusWriting) {
            @try {
                [tempAudioEncoder markAsFinished];
                [tempVideoEncoder markAsFinished];
                [tempAssetWriter finishWritingWithCompletionHandler:^{
                    if (tempAssetWriter.status == AVAssetWriterStatusFailed) {
                        [self showError:tempAssetWriter.error];
                    } else {
                        [self uploadLocalURL:tempAssetWriter.outputURL];
                    }
                }];
            }
            @catch (NSException *exception) {
                NSLog(@"Caught exception: %@", [exception description]);
                //[BugSenseController logException:exception withExtraData:nil];
            }
        }
        self.segmentCount++;
        if (self.readyToRecordAudio && self.readyToRecordVideo) {
            NSError *error = nil;
            self.queuedAssetWriter = [[AVAssetWriter alloc] initWithURL:[OWUtilities urlForRecordingSegmentCount:segmentCount basePath:self.basePath] fileType:(NSString *)kUTTypeMPEG4 error:&error];
            if (error) {
                [self showError:error];
            }
            self.queuedVideoEncoder = [self setupVideoEncoderWithAssetWriter:self.queuedAssetWriter formatDescription:videoFormatDescription bitsPerSecond:videoBPS];
            self.queuedAudioEncoder = [self setupAudioEncoderWithAssetWriter:self.queuedAssetWriter formatDescription:audioFormatDescription bitsPerSecond:audioBPS];
            //NSLog(@"Encoder switch finished");
        }
    });
}

- (void) setupVideoEncoderWithFormatDescription:(CMFormatDescriptionRef)formatDescription bitsPerSecond:(int)bps {
    videoFormatDescription = formatDescription;
    videoBPS = bps;
    if (!self.assetWriter) {
        NSError *error = nil;
        self.assetWriter = [[AVAssetWriter alloc] initWithURL:[OWUtilities urlForRecordingSegmentCount:segmentCount basePath:self.basePath] fileType:(NSString *)kUTTypeMPEG4 error:&error];
        if (error) {
            [self showError:error];
        }
    }
    self.videoEncoder = [self setupVideoEncoderWithAssetWriter:self.assetWriter formatDescription:formatDescription bitsPerSecond:bps];

    if (!queuedAssetWriter) {
        self.segmentCount++;
        NSError *error = nil;
        self.queuedAssetWriter = [[AVAssetWriter alloc] initWithURL:[OWUtilities urlForRecordingSegmentCount:segmentCount basePath:self.basePath] fileType:(NSString *)kUTTypeMPEG4 error:&error];
        if (error) {
            [self showError:error];
        }
    }
    self.queuedVideoEncoder = [self setupVideoEncoderWithAssetWriter:self.queuedAssetWriter formatDescription:formatDescription bitsPerSecond:bps];
    self.readyToRecordVideo = YES;
}

- (void) setupAudioEncoderWithFormatDescription:(CMFormatDescriptionRef)formatDescription bitsPerSecond:(int)bps {
    audioFormatDescription = formatDescription;
    audioBPS = bps;
    if (!self.assetWriter) {
        NSError *error = nil;
        self.assetWriter = [[AVAssetWriter alloc] initWithURL:[OWUtilities urlForRecordingSegmentCount:segmentCount basePath:self.basePath] fileType:(NSString *)kUTTypeMPEG4 error:&error];
        if (error) {
            [self showError:error];
        }
    }
    self.audioEncoder = [self setupAudioEncoderWithAssetWriter:self.assetWriter formatDescription:formatDescription bitsPerSecond:bps];

    if (!queuedAssetWriter) {
        self.segmentCount++;
        NSError *error = nil;
        self.queuedAssetWriter = [[AVAssetWriter alloc] initWithURL:[OWUtilities urlForRecordingSegmentCount:segmentCount basePath:self.basePath] fileType:(NSString *)kUTTypeMPEG4 error:&error];
        if (error) {
            [self showError:error];
        }
    }
    self.queuedAudioEncoder = [self setupAudioEncoderWithAssetWriter:self.queuedAssetWriter formatDescription:formatDescription bitsPerSecond:bps];
    self.readyToRecordAudio = YES;
}

- (void) handleException:(NSException *)exception {
    [super handleException:exception];
    [self segmentRecording:nil];
}

- (void) uploadLocalURL:(NSURL*)url {
    NSLog(@"upload local url: %@", url);
    NSString *inputPath = [url path];
    NSString *outputPath = [inputPath stringByReplacingOccurrencesOfString:@".mp4" withString:@".ts"];
    NSString *outputFileName = [outputPath lastPathComponent];
    NSDictionary *options = @{kFFmpegOutputFormatKey: @"mpegts"};
    NSLog(@"%@ conversion...", outputFileName);
    [ffmpegWrapper convertInputPath:[url path] outputPath:outputPath options:options progressBlock:nil completionBlock:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"%@ conversion complete", outputFileName);
            NSString *segmentKey = [NSString stringWithFormat:@"%@/%@", self.uuid, outputFileName];
            [[OWSharedS3Client sharedClient] postObjectWithFile:outputPath bucket:BUCKET_NAME key:segmentKey acl:@"public-read" success:^(S3PutObjectResponse *responseObject) {
                [manifestGenerator appendSegmentPath:outputPath duration:(int)segmentationInterval sequence:segmentCount completionBlock:^(BOOL success, NSError *error) {
                    if (success) {
                        NSString *manifestKey = [NSString stringWithFormat:@"%@/%@", self.uuid, [manifestGenerator.manifestPath lastPathComponent]];
                        [[OWSharedS3Client sharedClient] postObjectWithFile:manifestGenerator.manifestPath bucket:BUCKET_NAME key:manifestKey acl:@"public-read" success:^(S3PutObjectResponse *responseObject) {
                            NSLog(@"success updating manifest after uploading %@", outputFileName);
                        } failure:^(NSError *error) {
                            NSLog(@"error uplaoding manifest after %@", outputFileName);
                        }];
                    } else {
                        NSLog(@"Error creating manifest: %@", error.userInfo);
                    }
                }];
                NSLog(@"%@ upload complete: %@", outputFileName, responseObject.description);
            } failure:^(NSError *error) {
                NSLog(@"error posting segment %@: %@", outputFileName, error.userInfo);
            }];
        } else {
            NSLog(@"conversion error: %@", error.userInfo);
        }
    }];
}

@end


text:
package org.efaps.esjp.mail;

import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;

/**
 * This class must be replaced for customization, therefore it is left empty.
 * Functional description can be found in the related "<code>_Base</code>"
 * class.
 *
 * @author The eFaps Team
 */
@EFapsUUID("29493dd1-9387-4f4c-95b5-66b1ea8210cd")
@EFapsApplication("eFapsApp-Mail")
public class Template
    extends Template_Base
{

}


text:
<?php

namespace Greg\Support\Tests\Validation;

use Greg\Support\Validation\MaxLengthValidator;
use PHPUnit\Framework\TestCase;

class MaxLengthValidatorTest extends TestCase
{
    /** @test */
    public function it_should_validate_if_is_less_than_length()
    {
        $validation = new MaxLengthValidator(6);

        $this->assertTrue(!$validation->validate('Hello'));
    }

    /** @test */
    public function it_should_not_validate_if_is_more_than_length()
    {
        $validation = new MaxLengthValidator(6);

        $this->assertArrayHasKey('MaxLengthError', $validation->validate('Hello World!'));
    }
}


text:
using System;
using System.Linq;
using System.Collections.Generic;
using ForEvolve.Api.Contracts.Errors;
using ForEvolve.DynamicInternalServerError.TestWebServer;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace ForEvolve.DynamicInternalServerError
{
    public class ModelStateValidationFilterTest
    {
        protected TestServer _server;
        protected HttpClient _client;

        public ModelStateValidationFilterTest()
        {
            // Arrange
            _server = new TestServer(new WebHostBuilder()
                .UseStartup<Startup>()
            );
            _client = _server.CreateClient();
        }

        [Fact]
        public async Task SomeModelWithOneProperty_should_return_ErrorResponse()
        {
            // Arrange
            var model = new SomeModelWithOneProperty();

            // Act
            var response = await _client.PostAsync("/api/validate/oneproperty", model.ToJsonHttpContent());
            var responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.NotNull(responseString);
            var obj = JsonConvert.DeserializeObject<ErrorResponse>(responseString);
            Assert.NotNull(obj);
        }

        [Fact]
        public async Task SomeModelWithMultipleProperties_should_return_ErrorResponse()
        {
            // Arrange
            var model = new SomeModelWithMultipleProperties();

            // Act
            var response = await _client.PostAsync("/api/validate/multipleproperties", model.ToJsonHttpContent());
            var responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.NotNull(responseString);
            var obj = JsonConvert.DeserializeObject<ErrorResponse>(responseString);
            Assert.NotNull(obj);
        }
    }
}


text:
#include <stdint.h>
#include <sylvan.h>

#ifndef SIGREF_UTIL_H
#define SIGREF_UTIL_H

namespace sigref {

/**
 * Calculate A & B & C
 */
TASK_DECL_3(BDD, three_and, BDD, BDD, BDD);
#define three_and(a, b, c) CALL(three_and, a, b, c)

/**
 * Substitute each s by a t and vice versa
 */
TASK_DECL_1(MTBDD, swap_prime, MTBDD);
#define swap_prime(set) CALL(swap_prime, set)

/**
 * Compute \BigSatCount sets
 */
TASK_DECL_4(long double, big_satcount, MTBDD*, size_t, size_t, MTBDD);
#define big_satcount(sets, count, nvars, filter) CALL(big_satcount, sets, count, nvars, filter)

/**
 * Compute \BigUnion sets
 */
TASK_DECL_2(MTBDD, big_union, MTBDD*, size_t)
#define big_union(sets, count) CALL(big_union, sets, count)

/**
 * Count number of transitions using the signatures
 */
TASK_DECL_3(double, count_transitions, size_t, size_t, size_t);
#define count_transitions(first, count, nvars) CALL(count_transitions, first, count, nvars)

/**
 * Extend a relation <rel> defined on variables <vars> to the full domain,
 * which has <state_length> state variables (and <state_length> prime variables)
 */
TASK_DECL_3(BDD, extend_relation, BDD, BDD, int);
#define extend_relation(rel, vars, state_length) CALL(extend_relation, rel, vars, state_length)

/**
 * -RICHARD-
 * Rename variables old_vars in BDD a to new_vars
 */
TASK_DECL_3(BDD, rename_vars, BDD, BDD, BDD)
#define rename_vars(a, old_vars, new_vars) CALL(rename_vars, a, old_vars, new_vars)

} // namespace sigref

#endif


text:
@interface OrgApacheLuceneIndexLeafReaderContext () {
 @public
  OrgApacheLuceneIndexLeafReader *reader_;
}

@end

J2OBJC_FIELD_SETTER(OrgApacheLuceneIndexLeafReaderContext, reader_, OrgApacheLuceneIndexLeafReader *)

@implementation OrgApacheLuceneIndexLeafReaderContext

- (instancetype)initWithOrgApacheLuceneIndexCompositeReaderContext:(OrgApacheLuceneIndexCompositeReaderContext *)parent
                                withOrgApacheLuceneIndexLeafReader:(OrgApacheLuceneIndexLeafReader *)reader
                                                           withInt:(jint)ord
                                                           withInt:(jint)docBase
                                                           withInt:(jint)leafOrd
                                                           withInt:(jint)leafDocBase {
  OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexCompositeReaderContext_withOrgApacheLuceneIndexLeafReader_withInt_withInt_withInt_withInt_(self, parent, reader, ord, docBase, leafOrd, leafDocBase);
  return self;
}

- (instancetype)initWithOrgApacheLuceneIndexLeafReader:(OrgApacheLuceneIndexLeafReader *)leafReader {
  OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexLeafReader_(self, leafReader);
  return self;
}

- (id<JavaUtilList>)leaves {
  if (!isTopLevel_) {
    @throw create_JavaLangUnsupportedOperationException_initWithNSString_(@"This is not a top-level context.");
  }
  return JavaUtilCollections_singletonListWithId_(self);
}

- (id<JavaUtilList>)children {
  return nil;
}

- (OrgApacheLuceneIndexLeafReader *)reader {
  return reader_;
}

- (NSString *)description {
  return JreStrcat("$@$I$IC", @"LeafReaderContext(", reader_, @" docBase=", docBase_, @" ord=", ord_, ')');
}

- (void)dealloc {
  RELEASE_(reader_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x0, -1, 0, -1, -1, -1, -1 },
    { NULL, NULL, 0x0, -1, 1, -1, -1, -1, -1 },
    { NULL, "LJavaUtilList;", 0x1, -1, -1, -1, 2, -1, -1 },
    { NULL, "LJavaUtilList;", 0x1, -1, -1, -1, 3, -1, -1 },
    { NULL, "LOrgApacheLuceneIndexLeafReader;", 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, "LNSString;", 0x1, 4, -1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithOrgApacheLuceneIndexCompositeReaderContext:withOrgApacheLuceneIndexLeafReader:withInt:withInt:withInt:withInt:);
  methods[1].selector = @selector(initWithOrgApacheLuceneIndexLeafReader:);
  methods[2].selector = @selector(leaves);
  methods[3].selector = @selector(children);
  methods[4].selector = @selector(reader);
  methods[5].selector = @selector(description);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "ord_", "I", .constantValue.asLong = 0, 0x11, -1, -1, -1, -1 },
    { "docBase_", "I", .constantValue.asLong = 0, 0x11, -1, -1, -1, -1 },
    { "reader_", "LOrgApacheLuceneIndexLeafReader;", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "LOrgApacheLuceneIndexCompositeReaderContext;LOrgApacheLuceneIndexLeafReader;IIII", "LOrgApacheLuceneIndexLeafReader;", "()Ljava/util/List<Lorg/apache/lucene/index/LeafReaderContext;>;", "()Ljava/util/List<Lorg/apache/lucene/index/IndexReaderContext;>;", "toString" };
  static const J2ObjcClassInfo _OrgApacheLuceneIndexLeafReaderContext = { "LeafReaderContext", "org.apache.lucene.index", ptrTable, methods, fields, 7, 0x11, 6, 3, -1, -1, -1, -1, -1 };
  return &_OrgApacheLuceneIndexLeafReaderContext;
}

@end

void OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexCompositeReaderContext_withOrgApacheLuceneIndexLeafReader_withInt_withInt_withInt_withInt_(OrgApacheLuceneIndexLeafReaderContext *self, OrgApacheLuceneIndexCompositeReaderContext *parent, OrgApacheLuceneIndexLeafReader *reader, jint ord, jint docBase, jint leafOrd, jint leafDocBase) {
  OrgApacheLuceneIndexIndexReaderContext_initWithOrgApacheLuceneIndexCompositeReaderContext_withInt_withInt_(self, parent, ord, docBase);
  self->ord_ = leafOrd;
  self->docBase_ = leafDocBase;
  JreStrongAssign(&self->reader_, reader);
}

OrgApacheLuceneIndexLeafReaderContext *new_OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexCompositeReaderContext_withOrgApacheLuceneIndexLeafReader_withInt_withInt_withInt_withInt_(OrgApacheLuceneIndexCompositeReaderContext *parent, OrgApacheLuceneIndexLeafReader *reader, jint ord, jint docBase, jint leafOrd, jint leafDocBase) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneIndexLeafReaderContext, initWithOrgApacheLuceneIndexCompositeReaderContext_withOrgApacheLuceneIndexLeafReader_withInt_withInt_withInt_withInt_, parent, reader, ord, docBase, leafOrd, leafDocBase)
}

OrgApacheLuceneIndexLeafReaderContext *create_OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexCompositeReaderContext_withOrgApacheLuceneIndexLeafReader_withInt_withInt_withInt_withInt_(OrgApacheLuceneIndexCompositeReaderContext *parent, OrgApacheLuceneIndexLeafReader *reader, jint ord, jint docBase, jint leafOrd, jint leafDocBase) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneIndexLeafReaderContext, initWithOrgApacheLuceneIndexCompositeReaderContext_withOrgApacheLuceneIndexLeafReader_withInt_withInt_withInt_withInt_, parent, reader, ord, docBase, leafOrd, leafDocBase)
}

void OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexLeafReader_(OrgApacheLuceneIndexLeafReaderContext *self, OrgApacheLuceneIndexLeafReader *leafReader) {
  OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexCompositeReaderContext_withOrgApacheLuceneIndexLeafReader_withInt_withInt_withInt_withInt_(self, nil, leafReader, 0, 0, 0, 0);
}

OrgApacheLuceneIndexLeafReaderContext *new_OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexLeafReader_(OrgApacheLuceneIndexLeafReader *leafReader) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneIndexLeafReaderContext, initWithOrgApacheLuceneIndexLeafReader_, leafReader)
}

OrgApacheLuceneIndexLeafReaderContext *create_OrgApacheLuceneIndexLeafReaderContext_initWithOrgApacheLuceneIndexLeafReader_(OrgApacheLuceneIndexLeafReader *leafReader) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneIndexLeafReaderContext, initWithOrgApacheLuceneIndexLeafReader_, leafReader)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneIndexLeafReaderContext)


text:
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;

namespace System.Net
{
    internal unsafe class ListenerClientCertAsyncResult : LazyAsyncResult
    {
        private ThreadPoolBoundHandle _boundHandle;
        private NativeOverlapped* _pOverlapped;
        private byte[] _backingBuffer;
        private Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* _memoryBlob;
        private uint _size;

        internal NativeOverlapped* NativeOverlapped
        {
            get
            {
                return _pOverlapped;
            }
        }

        internal Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* RequestBlob
        {
            get
            {
                return _memoryBlob;
            }
        }

        private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(WaitCallback);

        internal ListenerClientCertAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object userState, AsyncCallback callback, uint size) : base(asyncObject, userState, callback)
        {
            // we will use this overlapped structure to issue async IO to ul
            // the event handle will be put in by the BeginHttpApi2.ERROR_SUCCESS() method
            _boundHandle = boundHandle;
            Reset(size);
        }

        internal void Reset(uint size)
        {
            if (size == _size)
            {
                return;
            }
            if (_size != 0)
            {
                _boundHandle.FreeNativeOverlapped(_pOverlapped);
            }
            _size = size;
            if (size == 0)
            {
                _pOverlapped = null;
                _memoryBlob = null;
                _backingBuffer = null;
                return;
            }
            _backingBuffer = new byte[checked((int)size)];
            _pOverlapped = _boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: _backingBuffer);
            _memoryBlob = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)Marshal.UnsafeAddrOfPinnedArrayElement(_backingBuffer, 0);
        }

        internal unsafe void IOCompleted(uint errorCode, uint numBytes)
        {
            IOCompleted(this, errorCode, numBytes);
        }

        private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult, uint errorCode, uint numBytes)
        {
            HttpListenerRequest httpListenerRequest = (HttpListenerRequest)asyncResult.AsyncObject;
            object result = null;
            try
            {
                if (errorCode == Interop.HttpApi.ERROR_MORE_DATA)
                {
                    //There is a bug that has existed in http.sys since w2k3.  Bytesreceived will only
                    //return the size of the inital cert structure.  To get the full size,
                    //we need to add the certificate encoding size as well.

                    Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob;
                    asyncResult.Reset(numBytes + pClientCertInfo->CertEncodedSize);

                    uint bytesReceived = 0;
                    errorCode =
                        Interop.HttpApi.HttpReceiveClientCertificate(
                            httpListenerRequest.HttpListenerContext.RequestQueueHandle,
                            httpListenerRequest._connectionId,
                            (uint)Interop.HttpApi.HTTP_FLAGS.NONE,
                            asyncResult._memoryBlob,
                            asyncResult._size,
                            &bytesReceived,
                            asyncResult._pOverlapped);

                    if (errorCode == Interop.HttpApi.ERROR_IO_PENDING ||
                       (errorCode == Interop.HttpApi.ERROR_SUCCESS && !HttpListener.SkipIOCPCallbackOnSuccess))
                    {
                        return;
                    }
                }

                if (errorCode != Interop.HttpApi.ERROR_SUCCESS)
                {
                    asyncResult.ErrorCode = (int)errorCode;
                    result = new HttpListenerException((int)errorCode);
                }
                else
                {
                    Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult._memoryBlob;
                    if (pClientCertInfo != null)
                    {
                        if (NetEventSource.IsEnabled)
                            NetEventSource.Info(null,
  $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}");
                        if (pClientCertInfo->pCertEncoded != null)
                        {
                            try
                            {
                                byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize];
                                Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length);
                                result = httpListenerRequest.ClientCertificate = new X509Certificate2(certEncoded);
                            }
                            catch (CryptographicException exception)
                            {
                                if (NetEventSource.IsEnabled)
                                    NetEventSource.Info(null,
          $"HttpListenerRequest: {httpListenerRequest} caught CryptographicException: {exception}");
                                result = exception;
                            }
                            catch (SecurityException exception)
                            {
                                if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"HttpListenerRequest: {httpListenerRequest} caught SecurityException: {exception}");
                                result = exception;
                            }
                        }
                        httpListenerRequest.SetClientCertificateError((int)pClientCertInfo->CertFlags);
                    }
                }

                // complete the async IO and invoke the callback
                if (NetEventSource.IsEnabled) NetEventSource.Info(null, "Calling Complete()");
            }
            catch (Exception exception) when (!ExceptionCheck.IsFatal(exception))
            {
                result = exception;
            }
            finally
            {
                if (errorCode != Interop.HttpApi.ERROR_IO_PENDING)
                {
                    httpListenerRequest.ClientCertState = ListenerClientCertState.Completed;
                }
            }

            asyncResult.InvokeCallback(result);
        }

        private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
        {
            ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped);
            if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"errorCode:[{errorCode}] numBytes:[{numBytes}] nativeOverlapped:[{((long)nativeOverlapped)}]");
            IOCompleted(asyncResult, errorCode, numBytes);
        }

        // Will be called from the base class upon InvokeCallback()
        protected override void Cleanup()
        {
            if (_pOverlapped != null)
            {
                _memoryBlob = null;
                _boundHandle.FreeNativeOverlapped(_pOverlapped);
                _pOverlapped = null;
                _boundHandle = null;
            }
            GC.SuppressFinalize(this);
            base.Cleanup();
        }

        ~ListenerClientCertAsyncResult()
        {
            if (_pOverlapped != null && !Environment.HasShutdownStarted)
            {
                _boundHandle.FreeNativeOverlapped(_pOverlapped);
                _pOverlapped = null;  // Must do this in case application calls GC.ReRegisterForFinalize().
                _boundHandle = null;
            }
        }
    }
}


text:
<?php
namespace Application\Domain\Company\Department;

use Application\Domain\Company\Contracts\DefaultDepartment;
use Application\Domain\Util\Tree\AbstractTree;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
abstract class AbstractDepartmentTree extends AbstractTree
{

    public function createRoot()
    {
        return parent::createTree(DefaultDepartment::ROOT, 1);
    }
}


text:
/**
 * Worker
 * ======
 *
 * This class is for running CPU-heavy, blocking operations. It either runs in
 * a separate process (in node), or in a web worker thread (in a browser). It
 * receives messages from outside, performs the computation, and then sends
 * back the result. You probably don't want to use this file directly, but
 * rather Work, which will automatically spawn workers if necessary and send
 * commands to them. Note that the source code for worker-node and
 * worker-browser are almost equivalent, except for code that manages the
 * differences at the bottom. This is done deliberately, so that the browser
 * version can be minimized properly.
 */
"use strict";

// The fullnode "classes" that the worker can access. Objects sent from the
// main process/thread must be one of these types. They are defined below in a
// different way for node and the browser.
let classes;

// The function to send data back to the main process/thread. This is different
// for node and browsers and thus is defined below.
let send;

/**
 * The generic "receive data" method that works both in node and the browser.
 * It reconstitutes the data into an object of class classname, and then runs
 * the method methodname on it with arguments args.
 */
function receive(data) {
  let obj, result;
  try {
    obj = classes[data.classname]().fromBuffer(data.objbuf);
    result = obj[data.methodname].apply(obj, data.args);
  } catch (error) {
    send({
      id: data.id,
      error: error.toString()
    });
    return;
  }
  send({
    id: data.id,
    result: result
  });
};

// Load the main fullnode library so we have access to classes like Msg; it
// is assumed the full library is available. It is usually called
// fullnode.js. It sets a global object called fullnode.
importScripts(process.env.FULLNODE_JS_BASE_URL + process.env.FULLNODE_JS_BUNDLE_FILE);
classes = fullnode;
// Web workers use the global functions onmessage to receive, and postMessage
// to send.
onmessage = function(event) {
  let data = event.data;
  data.objbuf = new fullnode.deps.Buffer(data.objbuf);
  return receive(data);
};
send = postMessage;


text:
package zeusro.specialalarmclock.service;

import android.app.IntentService;
import android.content.Intent;

import zeusro.specialalarmclock.activity.AlarmAlertActivity;
import zeusro.specialalarmclock.bean.Alarm;
import zeusro.specialalarmclock.receiver.AlarmServiceBroadcastReceiver;

/**
 *
 *
 * @author zeusro
 * @since 2017/8/18 下午3:47
 */
public class SchedulingService extends IntentService {
    public SchedulingService() {
        super("SchedulingService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        final Alarm alarm = (Alarm) intent.getExtras().getSerializable("alarm");
        Intent alarmAlertActivityIntent = new Intent(getApplicationContext(), AlarmAlertActivity.class);
        alarmAlertActivityIntent.putExtra("alarm", alarm);
        alarmAlertActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(alarmAlertActivityIntent);
        AlarmServiceBroadcastReceiver.completeWakefulIntent(intent);
    }

}


text:
class CreateOrganizations < ActiveRecord::Migration
  def change
    create_table :organizations do |t|
      t.string :name, null: false
      t.text :description
      t.string :picture
    end
  end
end


text:
"use strict";
var events = require("./events");
var utils  = require("./browser.utils").utils;
var sync   = exports;

var options = {

    tagNames: {
        "css":  "link",
        "jpg":  "img",
        "jpeg": "img",
        "png":  "img",
        "svg":  "img",
        "gif":  "img",
        "js":   "script"
    },
    attrs: {
        "link":   "href",
        "img":    "src",
        "script": "src"
    }
};

var hiddenElem;
var OPT_PATH = "codeSync";

var current = function () {
    return window.location.pathname;
};

/**
 * @param {BrowserSync} bs
 */
sync.init = function (bs) {
    if (bs.options.tagNames) {
        options.tagNames = bs.options.tagNames;
    }
    sync.saveScroll(utils.getWindow(), utils.getDocument());
    bs.socket.on("file:reload", sync.reload(bs));
    bs.socket.on("browser:reload", function () {
        if (bs.canSync({url: current()}, OPT_PATH)) {
            sync.reloadBrowser(true);
        }
    });
};

/**
 * Use a cookie-drop to save scroll position of
 * @param $window
 * @param $document
 */
sync.saveScroll = function ($window, $document) {

    if (!utils.isOldIe()) {
        return;
    }

    if ($document.readyState === "complete") {
        utils.restoreScrollPosition();
    } else {
        events.manager.addEvent($document, "readystatechange", function() {
            if ($document.readyState === "complete") {
                utils.restoreScrollPosition();
            }
        });
    }

    events.manager.addEvent(window, "beforeunload", utils.saveScrollPosition);
};

/**
 * @param elem
 * @param attr
 * @param options
 * @returns {{elem: HTMLElement, timeStamp: number}}
 */
sync.swapFile = function (elem, attr, options) {

    var currentValue = elem[attr];
    var timeStamp = new Date().getTime();
    var suffix = "?rel=" + timeStamp;

    var justUrl = sync.getFilenameOnly(currentValue);

    if (justUrl) {
        currentValue = justUrl[0];
    }

    if (options) {
        if (!options.timestamps) {
            suffix = "";
        }
    }

    elem[attr] = currentValue + suffix;

    var body = document.body;

    setTimeout(function () {
        if (!hiddenElem) {
            hiddenElem = document.createElement("DIV");
            body.appendChild(hiddenElem);
        } else {
            hiddenElem.style.display = "none";
            hiddenElem.style.display = "block";
        }
    }, 200);

    return {
        elem: elem,
        timeStamp: timeStamp
    };
};

sync.getFilenameOnly = function (url) {
    return /^[^\?]+(?=\?)/.exec(url);
};

/**
 * @param {BrowserSync} bs
 * @returns {*}
 */
sync.reload = function (bs) {

    /**
     * @param data - from socket
     */
    return function (data) {

        if (!bs.canSync({url: current()}, OPT_PATH)) {
            return;
        }
        var transformedElem;
        var options    = bs.options;
        var emitter = bs.emitter;

        if (data.url || !options.injectChanges) {
            sync.reloadBrowser(true);
        }

        if (data.basename && data.ext) {

            var domData = sync.getElems(data.ext);
            var elems   = sync.getMatches(domData.elems, data.basename, domData.attr);

            if (elems.length && options.notify) {
                emitter.emit("notify", {message: "Injected: " + data.basename});
            }

            for (var i = 0, n = elems.length; i < n; i += 1) {
                transformedElem = sync.swapFile(elems[i], domData.attr, options);
            }
        }

        return transformedElem;
    };
};

/**
 * @param fileExtension
 * @returns {*}
 */
sync.getTagName = function (fileExtension) {
    return options.tagNames[fileExtension];
};

/**
 * @param tagName
 * @returns {*}
 */
sync.getAttr = function (tagName) {
    return options.attrs[tagName];
};

/**
 * @param elems
 * @param url
 * @param attr
 * @returns {Array}
 */
sync.getMatches = function (elems, url, attr) {

    if (url[0] === "*") {
        return elems;
    }

    var matches = [];

    for (var i = 0, len = elems.length; i < len; i += 1) {
        if (elems[i][attr].indexOf(url) !== -1) {
            matches.push(elems[i]);
        }
    }

    return matches;
};

/**
 * @param fileExtension
 * @returns {{elems: NodeList, attr: *}}
 */
sync.getElems = function(fileExtension) {

    var tagName = sync.getTagName(fileExtension);
    var attr    = sync.getAttr(tagName);

    return {
        elems: document.getElementsByTagName(tagName),
        attr: attr
    };
};

/**
 * @returns {window}
 */
sync.getWindow = function () {
    return window;
};

/**
 * @param confirm
 */
sync.reloadBrowser = function (confirm) {
    var $window = sync.getWindow();
    if (confirm) {
        $window.location.reload(true);
    }
};


text:
package datad

import (
	"log"
	"strings"
	"time"
)

var RegistrationTTL = 60 * time.Second

// A Registry contains a bidirectional mapping between data keys and nodes: (1)
// for a given data key, a list of cluster nodes that have the underlying data
// on disk; and (2) for a given node, a list of data keys that it should
// fetch/compute and store on disk.
type Registry struct {
	backend Backend
}

func NewRegistry(b Backend) *Registry {
	return &Registry{b}
}

func (r *Registry) KeysForNode(node string) ([]string, error) {
	return r.backend.ListKeys(keysForNodeDir(node), true)
}

func (r *Registry) NodesForKey(key string) ([]string, error) {
	return r.backend.ListKeys(nodesForKeyDir(key), true)
}

// KeyMap returns a map of keys to a list of their registered nodes.
func (r *Registry) KeyMap() (map[string][]string, error) {
	bkeys, err := r.backend.List(keyPathJoin(registryPrefix, keysPrefix), true)
	if err != nil {
		return nil, err
	}

	// TODO(sqs): divide len(bkeys) by replica count once replicas exist (just an
	// optimization)
	km := make(map[string][]string, len(bkeys))
	for _, bk := range bkeys {
		suffix := "/" + keyNodesSubdir
		if !strings.Contains(bk, suffix) {
			// This backend key is some parent node that is returned in the
			// results but is unneeded for this operation.
			continue
		}

		// Parse the backend key to determine the data key and the registered
		// node.
		parts := strings.Split(bk, suffix)
		if len(parts) != 2 {
			log.Printf("In KeyMap, skipping bad (unparseable) backend key in registry: %q.", bk)
			continue
		}

		key, node := parts[0], strings.TrimPrefix(parts[1], "/")

		if node != "" {
			km[key] = append(km[key], node)
		} else {
			// Record keys that have no nodes.
			km[key] = nil
		}
	}

	return km, nil
}

func (r *Registry) Add(key, node string) error {
	err := r.backend.Set(nodesForKeyDir(key)+"/"+node, "")
	if err != nil {
		return err
	}

	err = r.backend.Set(keysForNodeDir(node)+"/"+key, "")
	if err != nil {
		return err
	}

	return nil
}

func (r *Registry) Remove(key, node string) error {
	err := r.backend.Delete(nodesForKeyDir(key) + "/" + node)
	if err != nil {
		return err
	}

	err = r.backend.Delete(keysForNodeDir(node) + "/" + key)
	if err != nil {
		return err
	}

	return nil
}

const (
	registryPrefix = "registry"
	keyNodesSubdir = "$$nodes"
	nodeKeysSubdir = "$$keys"
)

func nodesForKeyDir(key string) string {
	return keyPathJoin(registryPrefix, keysPrefix, key, keyNodesSubdir)
}

func keysForNodeDir(node string) string {
	return keyPathJoin(registryPrefix, nodesPrefix, node, nodeKeysSubdir)
}

func keyBucket(key string, n int) int {
	var x uint8
	for i := 0; i < len(key); i++ {
		x += key[i]
	}
	return int(x) % n
}


text:
int lock_file(char *filename)
{
	int fd;

	if (!filename)
		return -1;

	if ((fd = open(filename,O_RDONLY | O_CREAT , S_IRWXU)) < 0) {
		print_error("lock_file","open",modsec_rpc_log_file,errno);
		return -1;
	}

	flock(fd,LOCK_EX);

	return fd;
}

int unlock_file(int fd)
{
	flock(fd,LOCK_UN);
	return 0;
}

int print_request(char* url,char *command,parameter_t *parameters, int num_of_parameters, int mask)
{
	char time_str[64], line[1024*1024];
	time_t t;
	int fd;
	int i;

	switch (atoi(modsec_rpc_log_level)) {
	case DEBUG:
			time(&t);
			ctime_r(&t,time_str);
			time_str[strlen(time_str)-1] = '\0';
			if ((fd = open(modsec_rpc_log_file,O_WRONLY | O_CREAT | O_APPEND | O_SYNC , S_IRWXU)) < 0) {
				print_error("print_request","open",modsec_rpc_log_file,errno);
				fd=2;
			}
			flock(fd,LOCK_EX);
			sprintf(line,"%s:REQUEST-BEGIN:======================================\n",time_str);
			line[1024*1024-1]='\0';
			write(fd,line,strlen(line));
			snprintf(line,1024*1024,"URL:%s\nCommand:%s\n",url,command);
			line[1024*1024-1]='\0';
			write(fd,line,strlen(line));
			for (i=0; i<num_of_parameters; i++) {
				snprintf(line,1024*1024,"%s=",parameters[i].name);
				line[1024*1024-1]='\0';
				write(fd,line,strlen(line));
				if (i == mask) {
					sprintf(line,"XXXXXXX\n");
					write(fd,line,strlen(line));
				} else {
					if (parameters[i].value) {
						snprintf(line,1024*1024,"%s\n",parameters[i].value);
						line[1024*1024-1]='\0';
					}
					else sprintf(line,"\n");
					write(fd,line,strlen(line));
				}

			}
			sprintf(line,"%s:REQUEST-END:========================================\n",time_str);
			write(fd,line,strlen(line));
			flock(fd,LOCK_UN);
			if (fd!=2) close(fd);
			break;
	}
	return 0;
}

int print_request_force(char* url,char *command,parameter_t *parameters, int num_of_parameters, int mask)
{
	char real_level[1024];

	strcpy(real_level,modsec_rpc_log_level);
	strcpy(modsec_rpc_log_level,"1");
	print_request(url,command,parameters,num_of_parameters,mask);
	strcpy(modsec_rpc_log_level,real_level);
	return 0;
}

int print_reply(char *reply)
{
	char time_str[64];
	time_t t;
	int fd;

	printf("%s",reply);
	switch (atoi(modsec_rpc_log_level)) {
	case DEBUG:
			time(&t);
			ctime_r(&t,time_str);
			time_str[strlen(time_str)-1] = '\0';
			if ((fd = open(modsec_rpc_log_file,O_WRONLY | O_CREAT | O_APPEND | O_SYNC , S_IRWXU)) < 0) {
				print_error("print_request","open",modsec_rpc_log_file,errno);
				fd=2;
			}
			flock(fd,LOCK_EX);
			write(fd,reply,strlen(reply));
			flock(fd,LOCK_UN);
			if (fd!=2) close(fd);
			break;
	}
	return 0;
}

int print_error(char *func1, char* func2, char* str, int err)
{
	char out[1024], time_str[64], line[1024*1024];
	char str1[1024], str2[1024], str3[1024];
	time_t t;
	int fd;

	time(&t);
	ctime_r(&t,time_str);
	time_str[strlen(time_str)-1] = '\0';
	if (err)
		strcpy(out,strerror(err));
	else
		strcpy(out,"");
	if (!func1)
		strcpy(str1,"");
	else {
		strncpy(str1,func1,1024);
		str1[1023]='\0';
	}
	if (!func2)
		strcpy(str2,"");
	else {
		strncpy(str2,func2,1024);
		str2[1023]='\0';
	}
	if (!str)
		strcpy(str3,"");
	else {
		strncpy(str3,str,1024);
		str3[1023]='\0';
	}

	if ((fd = open(modsec_rpc_log_file,O_WRONLY | O_CREAT | O_APPEND | O_SYNC , S_IRWXU)) < 0) {
		fprintf(stderr,"%s:ERROR:print_error:open:%s:%s\n",time_str,strerror(errno),modsec_rpc_log_file);
		fd=2;
	}
	snprintf(line,1024*1024,"%s:ERROR:%s:%s:%s:%s\n",time_str,str1,str2,out,str3);
	line[1024*1024-1]='\0';
	flock(fd,LOCK_EX);
	write(fd,line,strlen(line));
	flock(fd,LOCK_UN);
	if (fd!=2) close(fd);
	return 0;
}

int is_proxy_up()
{
	int pid;
	FILE *fp;

	if ((fp = fopen(modsec_proxy_pid,"r")) == NULL )
		return 0;

	if (fscanf(fp,"%d",&pid) == 0) {
		print_error("is_proxy_up","fscanf","missing PID",0);
		fclose(fp);
		return 0;
	}
	fclose(fp);

        if (!pid || kill(pid,0))
                return 0;

	return 1;
}

int run_cmd(char *command, char *output, int output_size)
{
	char line[1024];
	FILE *fp;

	if (output_size > 0 && output) output[0]='\0';
	if (!(fp=popen(command,"r"))) {
		print_error("run_cmd","popen",command,errno);
		return -1;
	}

	while (output_size && fgets(line,output_size>1024?1024:output_size,fp)) {
		strcat(output, line);
		output_size -= strlen(line);
	}

	if (!output_size)
		while (fgets(line,1024,fp));

	pclose(fp);
	return 0;
}

int find_param_idx(char *parameter_name, parameter_t *parameters, int max_parameters)
{
	int i, idx=-1;

	for (i = 0; (i < max_parameters) && (idx < 0); i++)
		if ( strstr(parameters[i].name,parameter_name) )
			idx=i;
	return idx;
}

int parse_file(char *filename, parameter_t *parameters, int max_parameters)
{
        char line[1024], *ptr;
	int i;
        FILE *fp;

	if (!max_parameters || (parameters == NULL) || (filename == NULL)) {
		print_error("parse_file","invalid input parameters","none",0);
		return 0;
	}

	if ((fp = fopen(filename,"r")) == NULL ) {
		print_error("parse_file","fopen",filename,errno);
		return 0;
	}

	i=0;
	while ( i < max_parameters && fgets(line,1024,fp)) {
		if (ptr = strstr(line,"#"))
			*ptr='\0';
		if (sscanf(line,"%[^=]=%s",parameters[i].name,parameters[i].value) != 2)
			continue;
		i++;
	}

	fclose(fp);

	return i;
}

int change_file(char *filename, parameter_t parameter)
{
        char line[1024], *name, *value;
	int i, found=0;
        FILE *fp;

	if (filename == NULL)
		return 0;

	if ((fp = fopen(filename,"r+")) == NULL )
		return 0;

	i=0;
	while ( fgets(line,1024,fp)) {
		sscanf(line,"%[^=]=%s",name,value);
		if (name && !strcmp(name,parameter.name)) {
			fprintf(fp,"%s=%s\n",name,parameter.value);
			found=1;
			continue;
		} else fprintf(fp,"%s",line);
	}

	fclose(fp);
	return found;
}

int copy_file(char *src_file, char *dst_file)
{
        char line[1024];
        FILE *sfp, *dfp;

	if (src_file == NULL || dst_file == NULL)
		return 0;

	if ((sfp = fopen(src_file,"r")) == NULL )
		return 0;

	if ((dfp = fopen(dst_file,"w")) == NULL ) {
		fclose(sfp);
		return 0;
	}

	while ( fgets(line,1024,sfp))
		fprintf(dfp,"%s",line);

	fclose(sfp);
	fclose(dfp);
	return 1;
}

int parse_query(char *query, parameter_t *parameters, int max_parameters)
{
	char *ptr, *dst_ptr, num[3];
	int i, len;

	if (!max_parameters || (parameters == NULL) || (query == NULL))
		return 0;

	ptr=query;
	i=0;
	while ((i < max_parameters) && *ptr) {
		parameters[i].name[0] = '\0';
		dst_ptr = parameters[i].name;
		len=0;
		while (*ptr && (*ptr != '=') && (len++ < MAX_NAME_LENGTH)) {
			if (*ptr == '%' && *(ptr+1) && *(ptr+2)) {
					num[0]=*(ptr+1);
					num[1]=*(ptr+2);
					num[2]='\0';
					ptr += 3;
					*dst_ptr=(char)strtol(num,NULL,16);
					if (*dst_ptr) dst_ptr++;
			} else *dst_ptr++ = *ptr++;
		}
		if (len >= MAX_NAME_LENGTH)
			while (*ptr && (*ptr != '='))
				*ptr++;
		if (*ptr) ptr++;
		*dst_ptr = '\0';
		parameters[i].value[0] = '\0';
		dst_ptr = parameters[i].value;
		len=0;
		while (*ptr && (*ptr != '&') && (len++ < MAX_VALUE_LENGTH)) {
			if (*ptr == '%' && *(ptr+1) && *(ptr+2)) {
					num[0]=*(ptr+1);
					num[1]=*(ptr+2);
					num[2]='\0';
					ptr += 3;
					*dst_ptr=(char)strtol(num,NULL,16);
					if (*dst_ptr) dst_ptr++;
			} else *dst_ptr++ = *ptr++;
		}
		if (len >= MAX_VALUE_LENGTH)
			while (*ptr && (*ptr != '&'))
				*ptr++;
		if (*ptr) ptr++;
		*dst_ptr = '\0';
		i++;
	}

	return i;
}

int parse_query_and_body (parameter_t *parameters, int max_parameters)
{
	char *query, *content_length_env;
	int i, num_of_params, body_len, content_length;

	query = getenv("QUERY_STRING");
	if (query && *query)
		return(parse_query(query,parameters,max_parameters));
	else {
		content_length_env = getenv("CONTENT_LENGTH");
		if (!content_length_env)
			return 0;
		if (! *content_length_env)
			return 0;
		content_length=atol(content_length_env);
		if (!(query=malloc(content_length+1)))
			return 0;
	        i = 1; body_len=0;
		while ( (body_len < content_length) && (i>0) ) {
			i = read(0,query+body_len,(content_length-body_len)<1024?(content_length-body_len):1024);
			if (i > 0 ) body_len+=i;
		}
		query[body_len] = '\0';
		num_of_params = parse_query(query,parameters,max_parameters);
		free(query);
		return num_of_params;
	}
}

int parse_cli (parameter_t *parameters, int max_parameters, int num_of_args, char *args[])
{
	char name[MAX_NAME_LENGTH], value[MAX_VALUE_LENGTH];
	int i, num_of_params=0;

	if (num_of_args > 0)
		for (i=0; i<num_of_args && i<max_parameters; i++) {
			if (sscanf(args[i],"%[^=]=%s",name,value) < 2)
				continue;
			if (strlen(name) < MAX_NAME_LENGTH)
				strcpy(parameters[num_of_params].name,name);
			else continue;
			if (strlen(value) < MAX_VALUE_LENGTH) {
				strcpy(parameters[num_of_params].value,value);
				num_of_params++;
			}
		}
	return num_of_params;
}

int send_request(char *request,char *ip,char *port,char *reply,int max_reply_size)
{
	int sock, i, reply_len;
	struct  sockaddr_in servaddr;

	reply[0]='\0';
	reply_len=0;
	if (!request || !*request || !ip || !port || !reply || !max_reply_size)
		return -1;

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons((short)atol(port));
	if ( inet_aton(ip, &servaddr.sin_addr) <= 0 )
		return -1;

	if ( (sock = socket(AF_INET, SOCK_STREAM, 0)) <  0 ) {
		print_error("send_request","socket",ip,errno);
		return -1;
	}
	if ( connect(sock, (struct sockaddr *) &servaddr, sizeof(servaddr) ) < 0 ) {
		print_error("send_request","connect",ip,errno);
		close(sock);
		return -1;
	}

	i = strlen(request);
	if ( write(sock,request,i) < i ) {
		print_error("send_request","write",ip,errno);
		shutdown(sock,SHUT_RDWR);
		close(sock);
		return -1;
	}

	i = 1; reply_len=0;
	while ( (reply_len < max_reply_size) && (i>0) ) {
		i = read(sock,reply+reply_len,(max_reply_size-reply_len)<1024?(max_reply_size-reply_len):1024);
		if (i > 0 ) reply_len+=i;
	}
	reply[reply_len] = '\0';

	shutdown(sock,SHUT_RDWR);
	close(sock);
	return reply_len;
}

int find_ip_idx(char *ip, blocklist_t *blocklist, int num_of_ips)
{
	int i, idx=-1;

	for (i = 0; (i < num_of_ips) && (idx < 0); i++)
		if ( strstr(blocklist[i].ip,ip) )
			idx=i;
	return idx;
}

int remove_ip_idx(char *ip, blocklist_t *blocklist, int num_of_ips)
{
	int i, j, idx=-1;
	time_t t;

	time(&t);
	for (i = 0; i < num_of_ips; i++)
		if ( (ip && strstr(blocklist[i].ip,ip)) || (!ip && (t > blocklist[i].end)) ) {
			idx=i;
			for (j=i; j<(num_of_ips-1); j++) {
				strcpy(blocklist[j].ip,blocklist[j+1].ip);
				blocklist[j].start = blocklist[j+1].start;
				blocklist[j].duration = blocklist[j+1].duration;
				blocklist[j].end = blocklist[j+1].end;
				strcpy(blocklist[j].token,blocklist[j+1].token);
			}
			num_of_ips--;
		}
	return idx;
}

int read_conf_file (char *filename)
{
	int idx, num_of_params;
	parameter_t parameters[MAX_PARAMS];

	num_of_params=parse_file(filename,parameters,MAX_PARAMS);

	if ((idx = find_param_idx("MODSEC_CLI_HOME",parameters,num_of_params)) >= 0)
		strcpy(modsec_cli_home,parameters[idx].value);
	if ((idx = find_param_idx("MODSEC_RPC_HOME",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_home,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_LOG_FILE",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_log_file,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_LOG_LEVEL",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_log_level,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_SSL_LOCKFILE",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_ssl_lockfile,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_SENSOR_LOCKFILE",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_sensor_lockfile,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_REVERSEPROXY_LOCKFILE",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_reverseproxy_lockfile,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_EXTERNALNIC_LOCKFILE",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_externalnic_lockfile,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_MUI_LOCKFILE",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_mui_lockfile,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_LOG_LEVEL",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_log_level,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_HOME",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_home,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_IP",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_ip,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_PORT",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_port,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_NETWORK_PREFIX",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_network_prefix,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_BIN",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_bin,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_CONF",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_conf,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_EXT_NIC",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_ext_nic,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_PID",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_pid,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_WHITELIST",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_whitelist,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_BLACKLIST",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_blacklist,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_TIMEOUT",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_timeout,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_EXCHANGE",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_exchange,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_EXT_IPS",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_ext_ips,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_MUI_UI_ADMIN",parameters,num_of_params)) >= 0)
		strcpy(modsec_mui_ui_admin,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC_PASSWORD_FILE",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc_password_file,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_MUI_UI_IPADDRESS",parameters,num_of_params)) >= 0)
		strcpy(modsec_mui_ui_ipaddress,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_MUI_UI_PORT",parameters,num_of_params)) >= 0)
		strcpy(modsec_mui_ui_port,parameters[idx].value);

	if ((idx = find_param_idx("SENSOR_ID",parameters,num_of_params)) >= 0)
		strcpy(sensor_id,parameters[idx].value);

	if ((idx = find_param_idx("SERIAL",parameters,num_of_params)) >= 0)
		strcpy(serial,parameters[idx].value);

	if ((idx = find_param_idx("VERSION_NUMBER",parameters,num_of_params)) >= 0)
		strcpy(version_number,parameters[idx].value);

	if ((idx = find_param_idx("RELEASE_DATE",parameters,num_of_params)) >= 0)
		strcpy(release_date,parameters[idx].value);

	if ((idx = find_param_idx("BRIDGE_MODE",parameters,num_of_params)) >= 0)
		strcpy(bridge_mode,parameters[idx].value);

	if ((idx = find_param_idx("DATA_DISK_SPACE",parameters,num_of_params)) >= 0)
		strcpy(data_disk_space,parameters[idx].value);

	if ((idx = find_param_idx("CONN_RATE",parameters,num_of_params)) >= 0)
		strcpy(conn_rate,parameters[idx].value);

	if ((idx = find_param_idx("CONN_RATE_PER_ADDR",parameters,num_of_params)) >= 0)
		strcpy(conn_rate_per_addr,parameters[idx].value);

	if ((idx = find_param_idx("CONNS",parameters,num_of_params)) >= 0)
		strcpy(conns,parameters[idx].value);

	if ((idx = find_param_idx("CONNS_PER_ADDR",parameters,num_of_params)) >= 0)
		strcpy(conns_per_addr,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_RPC",parameters,num_of_params)) >= 0)
		strcpy(modsec_rpc,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy,parameters[idx].value);

	if ((idx = find_param_idx("MODSEC_PROXY_SCRIPT",parameters,num_of_params)) >= 0)
		strcpy(modsec_proxy_script,parameters[idx].value);

	return num_of_params;
}

int init_cgi()
{
	char *modsec;

	setresuid(0,0,0);
	setresgid(0,0,0);

	strcpy(modsec_cli_home,"/opt/modsecurity-cli");
	strcpy(modsec_rpc_home,"/opt/modsecurity-rpc");
	strcpy(modsec_rpc_log_file,"/opt/modsecurity-rpc/var/logs/rpc.log");
	strcpy(modsec_rpc_log_level,"0");
	strcpy(modsec_rpc_ssl_lockfile,"/opt/modsecurity-rpc/var/run/ssl.lock");
	strcpy(modsec_rpc_sensor_lockfile,"/opt/modsecurity-rpc/var/run/sensor.lock");
	strcpy(modsec_rpc_externalnic_lockfile,"/opt/modsecurity-rpc/var/run/externalnic.lock");
	strcpy(modsec_rpc_reverseproxy_lockfile,"/opt/modsecurity-rpc/var/run/reverseproxy.lock");
	strcpy(modsec_rpc_mui_lockfile,"/opt/modsecurity-rpc/var/run/mui.lock");
	strcpy(modsec_proxy_home,"/opt/modsecurity-proxy");
	strcpy(modsec_proxy_ip,"127.0.0.2");
	strcpy(modsec_proxy_port,"80");
	strcpy(modsec_proxy_bin,"/bin/modsec-proxyd");
	strcpy(modsec_proxy_script,"/etc/init.d/modsec-proxy");
	strcpy(modsec_proxy_conf,"/etc/httpd.conf");
	strcpy(modsec_proxy_ext_nic,"eth0");
	strcpy(modsec_proxy_network_prefix,"172.16.0.0/12");
	strcpy(modsec_proxy_pid,"/opt/modsecurity-proxy/var/run/httpd.pid");
	strcpy(modsec_proxy_whitelist,"/opt/breach/etc/modsec_whitelist.conf");
	strcpy(modsec_proxy_blacklist,"/opt/breach/etc/modsec_blacklist.conf");
	strcpy(modsec_proxy_timeout,"120");
	strcpy(modsec_proxy_exchange,"/opt/modsecurity-proxy/var/exchange");
	strcpy(modsec_proxy_ext_ips,"/opt/breach/etc/modsec_ips.conf");
	strcpy(modsec_mui_ui_ipaddress,"127.0.0.1");
	strcpy(modsec_mui_ui_port,"443");
	strcpy(modsec_rpc_password_file,"/opt/modsecurity-rpc/etc/.htpasswd");
	strcpy(modsec_mui_ui_admin,"admin");
	strcpy(sensor_id,"1");
	strcpy(serial,"1");
	strcpy(version_number,"2.0");
	strcpy(bridge_mode,"off");
	strcpy(data_disk_space,"60");
	strcpy(release_date,"11-15-2006");
	strcpy(conn_rate,"0");
	strcpy(conn_rate_per_addr,"0");
	strcpy(conns,"0");
	strcpy(conns_per_addr,"0");

	if (modsec = getenv("MODSEC"))
		read_conf_file(modsec);
	else {
		if (!read_conf_file("/opt/breach/etc/modsec.conf"))
			read_conf_file("/etc/modsec.conf");
	}

	return 0;
}


text:
/*	$NetBSD: inet_addr_local.h,v 1.1.1.1 2009/06/23 10:09:00 tron Exp $	*/

#ifndef _INET_ADDR_LOCAL_H_INCLUDED_
#define _INET_ADDR_LOCAL_H_INCLUDED_

/*++
/* NAME
/*	inet_addr_local 3h
/* SUMMARY
/*	determine if IP address is local
/* SYNOPSIS
/*	#include <inet_addr_local.h>
/* DESCRIPTION
/* .nf

 /*
  * Utility library.
  */
#include <inet_addr_list.h>

 /*
  * External interface.
  */
extern int inet_addr_local(INET_ADDR_LIST *, INET_ADDR_LIST *, unsigned *);

/* LICENSE
/* .ad
/* .fi
/*	The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/*	Wietse Venema
/*	IBM T.J. Watson Research
/*	P.O. Box 704
/*	Yorktown Heights, NY 10598, USA
/*--*/

#endif