text:
<!DOCTYPE html>

		<title>HTML test</title>
		<meta charset="utf-8">

        <button onclick="toggleContents()">Click me</button>

            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello

            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
           hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
            hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello


text:
import csv
import json
import os.path

class Paper:
    def __init__(self, title, url, sections):
        self.title = title
        self.url = url
        self.sections = sections + ['References']

def main():
    basepath = os.path.dirname(os.path.abspath(__file__))
    reader = csv.reader(open(basepath + '/data.csv'))
    next(reader)
    papers = [Paper(row[0], row[1], [s.capitalize() for s in row[4:]])
              for row in reader]

    section_paper_indices = {}
    for i, paper in enumerate(papers):
        for section in paper.sections:
            section_paper_indices.setdefault(section, set()).add(i)

    for paper in papers:
        paper.sections = [s for s in paper.sections
                          if not s.startswith('*')
                          and len(section_paper_indices[s]) > 1]

    nodes = set()
    links = set()
    link_paper_indices = {}
    for i, paper in enumerate(papers):
        for section in paper.sections:
            nodes.add(section)
        for head, tail in zip(paper.sections, paper.sections[1:]):
            links.add((head, tail))
            link_paper_indices.setdefault((head, tail), set()).add(i)

    indices = {}
    for i, node in enumerate(nodes):
        indices[node] = i
        section_paper_indices[node] = list(section_paper_indices[node])
    for link in links:
        link_paper_indices[link] = list(link_paper_indices[link])

    nodes = [{'text': node, 'papers': section_paper_indices[node]}
             for node in nodes]
    links = [{'source': indices[link[0]], 'target': indices[link[1]],
              'papers': link_paper_indices[link]}
             for link in links]

    obj = {
        'nodes': nodes,
        'links': links,
        'papers': [{'title': p.title, 'url': p.url} for p in papers],
    }

    json.dump(obj, open(basepath + '/../app/data/graph.json', 'w'))

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
* [Basho basho_bench's repository](https://github.com/basho/basho_bench)
* [Basho basho_bench's documentation](https://docs.basho.com/riak/kv/2.2.0/using/performance/benchmarking/)
* Use the following commands to set up basho_bench.

```bash
$ git clone git://github.com/basho/basho_bench.git
$ git clone https://github.com/leo-project/leofs.git
$ cd basho_bench
$ cp -i ../leofs/test/src/*.erl src/
$ cp -i ../leofs/test/include/*.hrl include/
$ make all
```

### Preparations before testing
#### Create a test bucket

After starting a LeoFS system, you need to create a bucket before getting started with benchmarks. In this example, the bucket name is `test`. It is owned by the user `_test_leofs` that is already registered internally by LeoFS.

```bash
$ leofs-adm add-endpoint <gateway-ip-address>
OK

$ leofs-adm add-bucket test 05236
OK

$ leofs-adm get-buckets
bucket   | owner       | created at
---------+-------------+---------------------------
test     | _test_leofs | 2013-02-27 14:06:54 +0900

$ leofs-adm update-acl test 05236 public-read
OK
```

## Configuration file for basho_bench
### An Example

Some examples are included in LeoFS' repository at [leo-project / leofs / test / conf](https://github.com/leo-project/leofs/tree/master/test/conf). If you would like to learn basho_bench's configuration, you can see [BashoBench's Configuration](https://docs.basho.com/riak/kv/2.2.0/using/performance/benchmarking/#configuration).

```erlang
{mode,      max}.
{duration,   10}.
{concurrent, 50}.

{driver, basho_bench_driver_leofs}.
{code_paths, ["deps/ibrowse"]}.

{http_raw_ips, ["${HOST_NAME_OF_LEOFS_GATEWAY}"]}.
{http_raw_port, 8080}.
{http_raw_path, "/test"}.
%% {http_raw_path, "/${BUCKET}"}.

{key_generator,   {partitioned_sequential_int, 1000000}}.
{value_generator, {fixed_bin, 16384}}. %% 16KB
{operations, [{put,1}]}.               %% PUT:100%
%%{operations, [{put,1}, {get, 4}]}.   %% PUT:20%, GET:80%

{check_integrity, false}.
```

### Description

| Key                              | Value |
|----------------------------------|------------------------------------------------|
| http_raw_ips                     | The LeoFS Gateway nodes we want to benchmark   |
| http_raw_port                    | The port used by the LeoFS Gateway nodes       |
| http_raw_path                    | URL path prefix. The first path segment MUST be a BUCKET name |
| check_integrity (default:false)  | Check integrity of registered object - compare an original MD5 with a retrieved object's MD5 (Only for developers)|

## Running basho_bench (1)

In this example, LeoFS and `basho_bench` are installed locally. The following commands can be used to run `basho_bench`.

```bash
### Loading 1M records of size 16KB
cd basho_bench
./basho_bench ../leofs/test/conf/leofs_16K_LOAD1M.config
```

## Running basho_bench (2)

In this example, LeoFS and `basho_bench` are installed on different hosts.

### Configure the endpoint on LeoManager's console

Allows basho_bench's requests to reach `${HOST_NAME_OF_LEOFS_GATEWAY}`.

```bash
$ leofs-adm add-endpoint <host-name-of-leofs-gateway>
OK

$ leofs-adm get-endpoints
endpoint                      | created at
------------------------------+---------------------------
localhost                     | 2013-03-01 00:14:04 +0000
s3.amazonaws.com              | 2013-03-01 00:14:04 +0000
${HOST_NAME_OF_LEOFS_GATEWAY} | 2013-03-01 00:14:04 +0000
```

### Edit the benchmark's configuration file

You need to modify the values for `http_raw_ips` and `http_raw_port`.

```bash
{mode,      max}.
{duration,   10}.
{concurrent, 50}.

{driver, basho_bench_driver_leofs}.
{code_paths, ["deps/ibrowse"]}.

{http_raw_ips, ["${HOST_NAME_OF_LEOFS_GATEWAY}"]}. %% able to set plural nodes
{http_raw_port, ${PORT}}. %% default: 8080
{http_raw_path, "/test"}.
%% {http_raw_path, "/${BUCKET}"}.

{key_generator,   {partitioned_sequential_int, 1000000}}.
{value_generator, {fixed_bin, 16384}}. %% 16KB
{operations, [{put,1}]}.               %% PUT:100%
%%{operations, [{put,1}, {get, 4}]}.   %% PUT:20%, GET:80%

{check_integrity, false}.
```

### Running basho_bench

```bash
### Loading 1M records each size is 16KB
cd basho_bench
./basho_bench ../leofs/test/conf/leofs_16K_LOAD1M.config
```

## Related Links

- [Getting Started / Quick Installation and Setup](/installation/quick.md)
- [Getting Started / Building a LeoFS' cluster with Ansible](/installation/cluster.md)
- [For Administrators / System Operations / S3-API related Operations](/admin/system_operations/s3.md)


text:
<annotation>
<folder>monitor</folder>
<filename>monitor_1_view_1_pose_13_lit_1_gray.jpg</filename>
<source>
<database>photorealistic	rendering</database>
</source>
<size>
<width>640</width>
<height>480</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>monitor</name>
<pose>Unspecified</pose>
<truncated>0</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>225</xmin>
<ymin>153</ymin>
<xmax>432</xmax>
<ymax>336</ymax>
</bndbox>
</object>
</annotation>


text:
namespace cobalt {
namespace cssom {

// Lower-case names of CSS media types
//  https://www.w3.org/TR/html4/types.html#h-6.13
//  https://www.w3.org/TR/CSS21/media.html#media-types
//  https://www.w3.org/TR/css3-mediaqueries/
// Listed here are the names of all supported media types, except the 'all'
// media type.
extern const char kScreenMediaTypeName[];
extern const char kTVMediaTypeName[];

}  // namespace cssom
}  // namespace cobalt

#endif  // COBALT_CSSOM_MEDIA_TYPE_NAMES_H_


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/vl_title"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:textColor="#ffffff"
        />
</LinearLayout>


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Wait and eat</title>
  <link rel="stylesheet" href="css/app.css"/>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          Toggle navigation

        </button>
        Wait and eat

Log in


text:
<?php
/**
 * @name IndexController
 * @author Luyu
 * @desc 默认控制器
 */
class documentController extends BaseController {

    function __construct(){
        parent::__construct();
        date_default_timezone_set('Asia/Shanghai');
        $_SESSION['project_id'] = '555ede4815d55cdc2900003f';
    }

    public function createProject(){
        $data['name']         = Request::input('name');
        if ($data['name']) {
            $data['user_id']      = 1;
            $data['created_time'] = date('Y-m-d H:i:s');
            $rs =  $this->mongo->insert('projects',$data);
            $this->echoJson(1,$rs);
        }else{
            $this->echoJson(2);
        }
    }

    public function listProject(){
        $condition['user_id'] = 1;
        $rs = $this->mongo->find('projects',$condition);
        foreach ($rs as &$row) {
            $row['_id'] = (string)$row['_id'];
        }
        $this->echoJson(1,$rs);
    }

    /**
     * 添加章节
     */
    public function addChapter() {
        $data['project_id']   = Request::input('project_id');
        $data['user_id']      = 1;
        $data['name']         = Request::input('name');
        $data['content']      = '';
        $data['created_time'] = date('Y-m-d H:i:s');
        $rs = $this->mongo->insert('document',$data);
        $this->echoJson(1,$rs);

    }

    // 加载列表
    public function lists(){
        $condition['project_id'] = Request::input('project_id');
        $fields = array('name','_id');
        $rs = $this->mongo->find('document',$condition,array('sort'=>array('sort'=>1)),$fields);
        foreach ($rs as &$row) {
            $row['_id'] = (string)$row['_id'];
        }
        $this->echoJson(1,$rs);

    }

    // 保存文章
    public function save(){
        $condition['_id']    = new MongoId(Request::input('doc_id')) ;
        $new_data['content'] = $_POST['content'];
        $rs = $this->mongo->update('document',$condition,array('$set'=>$new_data));
        $this->echoJson(1,$rs);

    }

    // 读取文章
    public function read(){
        $condition['_id']    = new MongoId(Request::input('doc_id')) ;
        $rs = $this->mongo->findOne('document',$condition);
        $this->echoJson(1,$rs);
    }

    // 删除文章
    public function delete(){
        $condition['_id'] = new MongoId(Request::input('doc_id')) ;
        $rs = $this->mongo->remove('document',$condition);
        $this->echoJson(1,$rs);
    }

    // 重命名
    public function rename(){
        $condition['_id'] = new MongoId(Request::input('doc_id')) ;
        $new_data['name'] = Request::input('newname','','default',false);
        $rs = $this->mongo->update('document',$condition,array('$set'=>$new_data));
        $this->echoJson(1,$rs);
    }

    // 菜单排序
    public function menuSort(){
        $ids = Request::input('doc_ids');
        foreach ($ids as $i => $id) {
            $condition['_id'] = new MongoId($id) ;
            $new_data['sort'] = $i;
            $rs = $this->mongo->update('document',$condition,array('$set'=>$new_data));
        }
        $this->echoJson(1,$rs);
    }

    public function export(){
        $condition['project_id'] = Request::input('project_id');
        //todo
        $projectName = 'catphp';

        $fields = array('name','_id','content');
        $rs = $this->mongo->find('document',$condition,array('sort'=>array('sort'=>1)),$fields);

        $mk = new Parsedown();
        $docs = array();
        foreach ($rs as $row) {
            $doc            = array();
            $doc['name']    = $row['name'];
            $doc['content'] = $mk->parse($row['content']);
            $docs[] = $doc;
        }

        $this->assign("docs",$docs);
        $content = $this->render('views/document.html',false);
        // $this->staticize('runtime/index.html');
        $download_config   = CatConfig::getInstance(APP_PATH.'/config/download.conf.php');
        $download_zip_name = APP_PATH.'/runtime/'.$projectName.date('YmdHis').'.zip';
        $zip = new Zip($download_zip_name, ZipArchive::OVERWRITE);
        $zip->addContent($content,'index.html');
        foreach ($download_config->get('default') as $file) {
            $zip->addFile(APP_PATH.'/runtime/'.$file,$file);
        }
        $zip->close();
        $this->download($download_zip_name,$projectName.'.zip');
        // $this->zip($this->render('views/document.html'));
        // var_dump($download_config->get('default'));

    }

    private function download($file_path,$file_name){
        if(!file_exists($file_path)){
            echo "export failed!";
            return ;
        }
        $fp=fopen($file_path,"r");
        $file_size=filesize($file_path);
        //下载文件需要用到的头
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:".$file_size);
        Header("Content-Disposition: attachment; filename=".$file_name);
        $buffer=1024;
        $file_count=0;
        //向浏览器返回数据
        while(!feof($fp) && $file_count<$file_size)
        {
            $file_con=fread($fp,$buffer);
            $file_count+=$buffer;
            echo $file_con;
        }
    }

    // private function zip($indexContent){
    //     $zip = new ZipArchive;
    //     $res = $zip->open(APP_PATH.'/runtime/test.zip', ZipArchive::OVERWRITE);
    //     if ($res === TRUE) {
    //         $zip->addFromString('index.html', $indexContent);
    //         $zip->close();
    //         echo 'ok';
    //     } else {
    //         echo 'failed';
    //     }
    // }

}


text:
package net.finmath.time.daycount;

import java.time.LocalDate;

/**
 * Implementation of ACT/365.
 *
 * Calculates the day count by calculating the actual number of days between startDate and endDate.
 *
 * A fractional day is rounded to the approximately nearest day.
 *
 * The day count fraction is calculated using ACT/365 convention, that is, the
 * day count is divided by 365.
 *
 *

 *

 * 		The method {@link #getDaycountFraction(LocalDate, LocalDate) getDaycountFraction} corresponds to the implementation of the "ACT/365 method" of Excel function YEARFRAC, i.e., YEARFRAC(startDate,endDate,3).
 *

 *

 *
 * @author Christian Fries
 */
public class DayCountConvention_ACT_365 extends DayCountConvention_ACT {

	/**
	 * Create an ACT/365 day count convention.
	 */
	public DayCountConvention_ACT_365() {
	}

	/* (non-Javadoc)
	 * @see net.finmath.time.daycount.DayCountConventionInterface#getDaycountFraction(java.util.GregorianCalendar, java.util.GregorianCalendar)
	 */
	@Override
	public double getDaycountFraction(LocalDate startDate, LocalDate endDate) {
		if(startDate.isAfter(endDate)) return -getDaycountFraction(endDate,startDate);

		double daycountFraction = getDaycount(startDate, endDate) / 365.0;

		return daycountFraction;
	}
}


text:
import { Component, OnInit } from '@angular/core';
import {MdDialogRef} from "@angular/material";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {Contact} from "../../contact";

@Component({
  selector: 'app-contact-dialog',
  templateUrl: './contact-dialog.component.html',
  styleUrls: ['./contact-dialog.component.css']
})
export class ContactDialogComponent implements OnInit {

  contact: Contact;
  title: string;
  action: string;
  contactForm: FormGroup;

  constructor(private dialogRef: MdDialogRef<ContactDialogComponent>) { }

  //Reactive forms are used

  onSubmit(form: FormGroup) {
    let saveContact: Contact = new Contact();
    saveContact.id = this.contact.id;
    Object.assign(saveContact, this.contactForm.value);
    this.dialogRef.close(saveContact);
  }

  ngOnInit() {
    this.contactForm = new FormGroup({
      firstName: new FormControl('', Validators.required),
      lastName: new FormControl('', Validators.required),
      phone: new FormControl('', Validators.required),
      streetAddress: new FormControl('', Validators.required),
      city: new FormControl('', Validators.required)
    });
    this.contactForm.setValue({
      firstName: this.contact.firstName || '',
      lastName: this.contact.lastName || '',
      phone: this.contact.phone || '',
      streetAddress: this.contact.streetAddress || '',
      city: this.contact.city || ''
    });
  }
}


text:
require "google/cloud/metastore/v1beta"

##
# Example demonstrating basic usage of
# Google::Cloud::Metastore::V1beta::DataprocMetastore::Client#restore_service
#
def restore_service
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Metastore::V1beta::DataprocMetastore::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Metastore::V1beta::RestoreServiceRequest.new

  # Call the restore_service method.
  result = client.restore_service request

  # The returned object is of type Gapic::Operation. You can use this
  # object to check the status of an operation, cancel it, or wait
  # for results. Here is how to block until completion:
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "Error!"
  end
end
# [END metastore_v1beta_generated_DataprocMetastore_RestoreService_sync]


text:
#ifndef _NL_ITEM
#define _NL_ITEM
#include <_types.h>
typedef __darwin_nl_item nl_item;
#endif /* _NL_ITEM */


text:
#include "vxmfc.h"
#include "mfc/framectr.h"
#include "util/vxarcball.h"

namespace Vixen {
namespace MFC {

IMPLEMENT_DYNCREATE(DemoView, View)

DemoView::DemoView()
{
	m_bSpinScene = false;
	m_bSpinLight = false;
	m_bWireframe = false;
	m_bShowInfo = false;
	m_sceneMenu = NULL;
}

DemoView::~DemoView()
{
}

void DemoView::SetWireframe(bool bOn)
{
	Scene *scene = GetMainScene();
	Model* root;

	scene->Suspend();
	root = scene->GetModels();
	if (root)
		if (bOn)
			Appearance::Apply(root, Appearance::SHADING, Appearance::WIRE);
		else
			Appearance::Apply(root, Appearance::SHADING, Appearance::SMOOTH);
	scene->Resume();
}

void DemoView::ToggleWireframe()
{
	m_bWireframe = !m_bWireframe;
	SetWireframe(m_bWireframe);
}

void DemoView::ZoomAll()
{
	Demo*		app = Demo::Get();
	Scene*	scene = GetScene();
	Camera*	cam;
	Transformer* eng;

	if (!scene)
		return;
	cam = scene->GetCamera();
	eng = (Transformer*) app->GetNavigator();
	scene->ShowAll();
	if (eng && eng->IsClass(VX_Transformer))
		eng->SetTransform(cam->GetTransform());
}

BEGIN_MESSAGE_MAP(DemoView, View)
	//{{AFX_MSG_MAP(DemoView)
	ON_WM_DROPFILES()
	ON_COMMAND(ID_VIEW_SCENEGRAPH, OnViewScenegraph)
	ON_UPDATE_COMMAND_UI(ID_VIEW_SCENEGRAPH, OnUpdateViewScenegraph)
	ON_COMMAND(ID_VIEW_ZOOMALL, OnViewZoomall)
	ON_COMMAND(ID_VIEW_FRAMERATECOUNTER, OnViewFrameratecounter)
	ON_UPDATE_COMMAND_UI(ID_VIEW_FRAMERATECOUNTER, OnUpdateViewFrameratecounter)
	ON_COMMAND(ID_VIEW_CAMERA, OnCamdialog)
	ON_COMMAND(ID_VIEW_WIREFRAME, OnViewWireframe)
	ON_UPDATE_COMMAND_UI(ID_VIEW_WIREFRAME, OnUpdateViewWireframe)
	ON_COMMAND(ID_VIEW_DISABLELIGHTING, OnDisableLighting)
	ON_UPDATE_COMMAND_UI(ID_VIEW_DISABLELIGHTING, OnUpdateDisableLighting)
	ON_COMMAND(ID_SCPT_OPEN, OnScptOpen)
	ON_COMMAND(ID_SCPT_RECORD, OnScptRecord)
	ON_COMMAND(ID_SCPT_RUN, OnScptPlay)
	ON_COMMAND(ID_SCPT_STOP, OnScptStop)
	ON_UPDATE_COMMAND_UI(ID_SCPT_RECORD, OnUpdateScptRecord)
	ON_COMMAND(ID_SCPT_REPLAY, OnScptReplay)
	ON_UPDATE_COMMAND_UI(ID_SCPT_REPLAY, OnUpdateScptReplay)
	ON_UPDATE_COMMAND_UI(ID_SCPT_STOP, OnUpdateScptStop)
	ON_COMMAND(ID_SCPT_REVERSE, OnScptReverse)
	ON_UPDATE_COMMAND_UI(ID_SCPT_REVERSE, OnUpdateScptReverse)
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_COMMAND(ID_NAV_ARCBALL, OnNavArcball)
	ON_COMMAND(ID_NAV_FLYER, OnNavFlyer)
	ON_COMMAND(ID_NAV_DRIVER, OnNavDriver)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

#ifdef _DEBUG
void DemoView::AssertValid() const
{
	CView::AssertValid();
}

void DemoView::Dump(CDumpContext& dc) const
{
	CView::Dump(dc);
}
#endif //_DEBUG

void DemoView::OnDropFiles(HDROP hDropInfo)
{
	TCHAR buf[256];

	UINT result = DragQueryFile(hDropInfo,
		0,		// index of file to query
		buf,	// buffer for returned filename
		256);	// size of buffer for filename
}

void DemoView::OnViewScenegraph()
{
	if (m_wndTreeDlg.GetSafeHwnd() == NULL)
	{
		if (!m_wndTreeDlg.Create(IDD_TREEVIEW, this))
		{
			TRACE0("Failed to create tree dialog\n");
		}
		m_wndTreeDlg.ShowWindow(SW_HIDE);
	}
	m_wndTreeDlg.RefreshTreeContents(GetMainScene());
	if (m_wndTreeDlg.IsWindowVisible())
		m_wndTreeDlg.ShowWindow(SW_HIDE);
	else
		m_wndTreeDlg.ShowWindow(SW_SHOW);
}

void DemoView::OnUpdateViewScenegraph(CCmdUI* pCmdUI)
{
	if (m_wndTreeDlg.GetSafeHwnd() == NULL)
	{
		pCmdUI->SetCheck(FALSE);
	}
	else
	{
		pCmdUI->SetCheck(m_wndTreeDlg.IsWindowVisible());
	}
}

void DemoView::OnViewZoomall()
{
	ZoomAll();
}

void DemoView::OnViewFrameratecounter()
{
	Demo*	app = Demo::Get();
	FrameCounter* framectr = (FrameCounter*) app->GetStatLog();
	if (!framectr)
		return;
	if (framectr->IsRunning())
		framectr->Stop();
	else
		framectr->Start();
}

void DemoView::OnUpdateViewFrameratecounter(CCmdUI* pCmdUI)
{
	Demo*	app = Demo::Get();
	Engine *pCounter = app->GetStatLog();
	if (pCounter)
		pCmdUI->SetCheck(pCounter->IsRunning());
}

void DemoView::OnCamdialog()
{
	if (m_wndCameraDlg.GetSafeHwnd() == NULL)
	{
		if (!m_wndCameraDlg.Create(IDD_CAMDIALOG, this))
		{
			TRACE0("Failed to create camera dialog\n");
		}
		else
		{
			Camera* cam = GetMainScene()->GetCamera();
			Transformer* xform = (Transformer*) Demo::Get()->GetNavigator();
			m_DefaultLocSaver.ReadStoredLocations(TEXT("default.loc"));
			m_wndCameraDlg.SetLocationSaver(&m_DefaultLocSaver);
			m_wndCameraDlg.SetCamera(cam);
			if (xform && xform->IsClass(VX_Transformer))
				xform->SetTransform(cam->GetTransform());
		}
	}
	m_wndCameraDlg.ShowWindow(SW_SHOW);
}

void DemoView::OnViewWireframe()
{
	ToggleWireframe();
}

void DemoView::OnUpdateViewWireframe(CCmdUI* pCmdUI)
{
	pCmdUI->SetCheck(m_bWireframe);
}

void DemoView::OnDisableLighting()
{
	Appearance::DoLighting = !Appearance::DoLighting;
}

void DemoView::OnUpdateDisableLighting(CCmdUI* pCmdUI)
{
	pCmdUI->SetCheck(!Appearance::DoLighting);
}

void DemoView::OnScptOpen()
{
#ifdef VX_USE_SCRIPTOR
	Demo*			app = Demo::Get();
	const TCHAR*	dir = app->GetMediaDir();
	CFileDialog		openDialog(TRUE, TEXT("*.bvh"), TEXT("test.bvh"));

	openDialog.m_ofn.lpstrFilter = TEXT("BVH Animation Files (*.bvh)\0*.bvh\0Vixen Scripts (*.scp)\0*.scp\0Vixen Files (*.vix)\0*.vix\0All Files (*.*)\0*.*\0\0");
	if (dir)
		openDialog.m_ofn.lpstrInitialDir = dir;
	else
		openDialog.m_ofn.lpstrInitialDir = TEXT("..\\..\\Data");
	if (openDialog.DoModal() == IDOK)
	{
		CString			filename(openDialog.GetPathName());
		Scriptor*		scp = app->GetScriptor();
		const TCHAR*	engname = NULL;

		if (scp)
		{
			Scene*		scene = GetScene();
			Engine*		simroot = scene->GetEngines();
			Skeleton*	skel = app->GetSkeleton();
			SharedObj*	target = NULL;

			app->SetScriptFile(filename);
			if (filename.Right(3).CompareNoCase(TEXT("scp")) == 0)
			{
				scp->LoadScript(filename);
				return;
			}
			if (skel == NULL)
			{
				skel = (Skeleton*) simroot->Find(TEXT("skeleton"), Group::FIND_ACTIVE | Group::FIND_END | Group::FIND_DESCEND);
				app->SetSkeleton(skel);
			}
			target = skel;
			if (skel)
			{
				engname = skel->GetName();
				engname = STRCHR(engname, TEXT('.')) + 1;
			}
			else
				target = scp->GetTarget();
			scp->Load(filename, engname, Animator::AUTO_PLAY, target);
		}
	}
#endif
}

void DemoView::OnScptPlay()
{
	Demo*			app = Demo::Get();
	Scene*			scene = GetScene();
	Engine*			simroot = scene->GetEngines();
	NavRecorder*	nav = GetNavRecorder();
	SharedObj*		targ = NULL;

	if (nav && nav->GetMessenger())
	{
		nav->Stop();
		nav->SetMessenger(NULL);
	}
#ifdef VX_USE_SCRIPTOR
	Scriptor*	scp = app->GetScriptor();
	Skeleton*	skel = app->GetSkeleton();

	if (scp)
	{
		scp->Begin();
		return;
	}
#endif
	else if (simroot)
	{
		simroot = simroot->GetAt(1);
		if (simroot)
			simroot->Start(Engine::CONTROL_CHILDREN);
	}
	m_wndTreeDlg.RefreshTreeContents(scene);
}

void DemoView::PlayAnimation(const TCHAR* filename, SharedObj* target)
{
	Demo*		app = Demo::Get();
	Engine*		simroot = GetMainScene()->GetEngines();
	int32		opts = 0;

	Scriptor*	scp = app->GetScriptor();
	if (filename)
	{
		Animator*	anim = app->GetAnimator();
		app->SetScriptFile(filename);
		if (anim)
			opts = anim->GetOptions();
		anim = scp->Load(filename, NULL, opts | Animator::AUTO_PLAY, target);
		return;
	}
	if (scp)
	{
		scp->Begin();
		return;
	}
	if (simroot)
		simroot = simroot->GetAt(1);
	if (simroot && (simroot = simroot->GetAt(1)))
		simroot->Start(Engine::CONTROL_CHILDREN);
}

NavRecorder* DemoView::GetNavRecorder() const
{
	Navigator*	nav = (Navigator*) Demo::Get()->GetNavigator();
	NavRecorder*	rec = NULL;

	if (nav == NULL)
		return NULL;
	GroupIter<Engine>	iter(nav, Group::CHILDREN);
	while (rec = (NavRecorder*) (Engine*) iter.Next())
		if (rec->IsClass(VX_NavRecorder))
			return rec;
	return NULL;
}

void DemoView::OnScptRecord()
{
	NavRecorder*	rec = GetNavRecorder();
	Messenger*	m = NULL;

	if (rec == NULL)
	{
		rec = new NavRecorder;
		Scene* scene = GetMainScene();
		if (scene)
		{
			scene->Suspend();		// lock around hierarchy changes
			Engine*	nav = Demo::Get()->GetNavigator();
			nav->Append(rec);
			scene->Resume();
		}
		else
			Demo::Get()->GetNavigator()->Append(rec);
	}
	else
		m = rec->GetMessenger();

	if (m == NULL)
	{
		m = new FileMessenger;
		rec->SetMessenger(m);
		m->SetOutStream(new Core::FileStream);
	}
#ifdef VX_USE_SCRIPTOR
	const TCHAR*	filename = Demo::Get()->GetScriptFile();
	if (filename == NULL)
		return;
#else
	const TCHAR*	filename = "demo.dat";
#endif
	m->Open(filename, Messenger::OPEN_WRITE);
	if (!rec->IsRunning())
	{
		rec->SetTarget(GetMainScene()->GetCamera());
		rec->Start();
	}
}

void DemoView::OnUpdateScptRecord(CCmdUI* pCmdUI)
{
	NavRecorder*	nav = GetNavRecorder();
	bool			isrecording = nav && nav->IsRunning();

	pCmdUI->Enable(!isrecording);
}

void DemoView::OnScptStop()
{
	Demo*			app = Demo::Get();
	NavRecorder*	nav = GetNavRecorder();

	if (nav)
	{
		nav->Stop();
		nav->SetMessenger(NULL);
	}
#ifdef VX_USE_SCRIPTOR
	Scriptor*	scp = app->GetScriptor();
	if (scp)
	{
		scp->Stop();
		return;
	}
	else
#endif
	{
		Engine*	simroot = GetMainScene()->GetEngines();
		if (simroot)
			simroot = simroot->GetAt(1);
		if (simroot)
			simroot->Stop(Engine::CONTROL_CHILDREN);
	}
}

void DemoView::OnUpdateScptStop(CCmdUI* pCmdUI)
{
	HMENU		hMenu = AfxGetApp()->m_pMainWnd->GetMenu()->m_hMenu;
	Scene*		scene = GetScene();
	Engine*		simroot = scene->GetEngines();
	NavRecorder*	nav = GetNavRecorder();

	CheckMenuItem(hMenu,ID_SCPT_STOP, MF_UNCHECKED);
#ifdef VX_USE_SCRIPTOR
	Scriptor*	scp = Demo::Get()->GetScriptor();
	if (scp && scp->IsRunning())
	{
		Animator*	anim = scp->FindAnim(NULL, scp->GetTarget());
		if (anim)
		{
			int opts = anim->GetOptions();
			if (anim->IsRunning())
				CheckMenuItem(hMenu, ID_SCPT_STOP, MF_CHECKED);
			return;
		}
	}
#endif
	if (nav && nav->IsRunning())
		CheckMenuItem(hMenu,ID_SCPT_STOP, MF_CHECKED);
}

void DemoView::OnScptReplay()
{
	Scene*		scene = GetScene();
	Engine*		simroot = scene->GetEngines();

#ifdef VX_USE_SCRIPTOR
	Scriptor*	scp = Demo::Get()->GetScriptor();
	if (scp)
	{
		Animator*	anim = scp->FindAnim(NULL, scp->GetTarget());
		if (anim)
		{
			int opts = anim->GetOptions();
			if (anim->GetControl() & Engine::CYCLE)
				anim->Disable(Engine::CYCLE);
			else
				anim->Enable(Engine::CYCLE);
			return;
		}
	}
#endif
	if (simroot)
		simroot = simroot->GetAt(1);
	if (simroot)
	{
		if (simroot->GetControl() & Engine::CYCLE)
			simroot->Disable(Engine::CYCLE, Engine::CONTROL_CHILDREN);
		else
			simroot->Enable(Engine::CYCLE, Engine::CONTROL_CHILDREN);
	}
}

void DemoView::OnUpdateScptReplay(CCmdUI* pCmdUI)
{
	HMENU		hMenu = AfxGetApp()->m_pMainWnd->GetMenu()->m_hMenu;
	Scene*		scene = GetScene();
	Engine*		simroot = scene->GetEngines();

	CheckMenuItem(hMenu,ID_SCPT_REPLAY,MF_UNCHECKED);			return;
#ifdef VX_USE_SCRIPTOR
	Scriptor*	scp = Demo::Get()->GetScriptor();
	if (scp)
	{
		Animator*	anim = scp->FindAnim(NULL, scp->GetTarget());
		if (anim)
		{
			if (anim->GetControl() & Engine::CYCLE)
				CheckMenuItem(hMenu,ID_SCPT_REPLAY, MF_CHECKED);
			return;
		}
	}
#endif
	if (simroot)
		simroot = simroot->GetAt(1);
	if (simroot)
	{
		if (simroot->GetControl() & Engine::CYCLE)
			CheckMenuItem(hMenu,ID_SCPT_REPLAY, MF_CHECKED);
	}
}

void DemoView::OnUpdateScptReverse(CCmdUI* pCmdUI)
{
	HMENU		hMenu = AfxGetApp()->m_pMainWnd->GetMenu()->m_hMenu;
	Scene*		scene = GetScene();
	Engine*		simroot = scene->GetEngines();

	CheckMenuItem(hMenu,ID_SCPT_REVERSE,MF_UNCHECKED);
#ifdef VX_USE_SCRIPTOR
	Scriptor*	scp = Demo::Get()->GetScriptor();
	if (scp)
	{
		Animator*	anim = scp->FindAnim(NULL, scp->GetTarget());
		if (anim)
		{
			if (anim->GetControl() & Engine::REVERSE)
				CheckMenuItem(hMenu, ID_SCPT_REVERSE, MF_CHECKED);
			return;
		}
	}
#endif
	if (simroot)
		simroot = simroot->GetAt(1);
	if (simroot)
	{
		if (simroot->GetControl() & Engine::REVERSE)
			CheckMenuItem(hMenu,ID_SCPT_REVERSE, MF_CHECKED);
	}
}

void DemoView::OnScptReverse()
{
	Scene*		scene = GetScene();
	Engine*		simroot = scene->GetEngines();

#ifdef VX_USE_SCRIPTOR
	Scriptor*	scp = Demo::Get()->GetScriptor();
	if (scp)
	{
		Animator*	anim = scp->FindAnim(NULL, scp->GetTarget());
		if (anim)
		{
			int opts = anim->GetOptions();
			if (anim->GetControl() &  Engine::REVERSE)
				opts &= ~ Engine::REVERSE;
			else
				opts |=  Engine::REVERSE;
			anim->SetOptions(opts);
			return;
		}
	}
#endif
	if (simroot)
		simroot = simroot->GetAt(1);
	if (simroot)
	{
		if (simroot->GetControl() & Engine::REVERSE)
			simroot->Disable(Engine::REVERSE, Engine::CONTROL_CHILDREN);
		else
			simroot->Enable(Engine::REVERSE, Engine::CONTROL_CHILDREN);
	}
}

//
// Refresh tree dialog whenever document (scene graph) is updated
//
void DemoView::OnUpdate( CView* pSender, LPARAM lHint, CObject* pHint )
{
	CView::OnUpdate (pSender, lHint, pHint);
	DemoView::m_wndTreeDlg.RefreshTreeContents(GetMainScene());
}

int DemoView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (View::OnCreate(lpCreateStruct) == -1)
		return -1;
	LoadSceneMenus(Demo::Get()->GetSceneMenus());
	return 0;
}

/*++++
 *
 * Name: DemoView_LoadSceneMenus
 *	bool LoadSceneMenus(char* menunames)
 *
 * Description:
 *	Dynamically loads the 3D scene control menus into
 *	the menu bar of the current application. The menus
 *	are placed before the "Help" menu.
 *
 *	The scene menus are loaded from the IDM_AFMENU menubar
 *	resource in afresource.rc2. To get this functionality,
 *	applications must edit their MFC resource file to
 *	include afresource.rc2.
 *
 *	LoadSceneMenus should only be called once and cannot
 *	be undone. All menus may be loaded or individual menus
 *	from the available set can be selected by name. Menu names
 *	include the & to indicate keyboard acceleration.
 *
 *	Unfortunately, at this time, keyboard accelerators are
 *	NOT loaded and must be explicitly specified by the
 *	application in it's accelerator table.
 *
 *	Args:
 *		<menunames>	String designating the names of the
 *					menus to load. All the names are in a
 *					single null-terminated string and are
 *					delimited by tabs. Blanks are allowed
 *					in menu names. If this string is NULL,
 *					all the menus in the IDM_AFMENU resource
 *					are added to the application menubar.
 *
 * Returns: bool
 *	<true> if menus successfully loaded
 *	<false> if problems finding resource or a particular named menu
 *
 ----*/
bool DemoView::LoadSceneMenus(const TCHAR* menunames)
{
	// Do not load menus at all if -1 is string pointer
	if (menunames == ((const TCHAR*) -1))
		return true;

	// Add menus to the top level frame window
	CFrameWnd* frameWindow = GetTopLevelFrame();
	if (frameWindow == NULL)
		return false;

	// Get frameMenu
	CMenu*	frameMenu = frameWindow->GetMenu();
	if (frameMenu == NULL || frameMenu->GetSafeHmenu() == NULL)
		return false;

	// Create CMenu to retrieve submenus -
	// use new so menu isn't purged from memory upon exit.
	m_sceneMenu = new CMenu();
	m_sceneMenu ->LoadMenu (IDM_AFMENU);
	if (m_sceneMenu ->GetSafeHmenu() == NULL)
		return false;

	// See if last submenu is "Help" and insert before.
	CString	menuname;
	int		mbindex = frameMenu->GetMenuItemCount();
	frameMenu->GetMenuString (mbindex - 1, menuname, MF_BYPOSITION);
	if (menuname == "&Help")
		mbindex--;

	// Copy the menus the user designated, all if menunames is NULL
	CString	wanted(menunames);
	CMenu*	menu = NULL;
	int		menuindex = 0;

	while (menu = m_sceneMenu->GetSubMenu(menuindex))
	{
		m_sceneMenu->GetMenuString(menuindex++, menuname, MF_BYPOSITION);
		if (menunames)
			if (wanted.Find(menuname) < 0)
				continue;
		frameMenu->InsertMenu(mbindex, MF_POPUP | MF_STRING | MF_BYPOSITION, (UINT_PTR) menu->GetSafeHmenu(), menuname);
	}
	return true;
}

void DemoView::OnDestroy()
{
	View::OnDestroy();

	delete m_sceneMenu;
}

//
// Select the arcball for navigation
// Mouse movement causes the scene to rotate
//
void DemoView::OnNavArcball()
{
	Demo*				world = Demo::Get();
	Engine*				navroot = (Engine*) world->GetNavigator();
	Navigator*			naveng;
	Camera*				cam = (Camera*) navroot->GetTarget();
	ArcBall*			arcball;
	GroupIter<Engine>	iter(navroot, Group::CHILDREN);
	Core::String		engname;
	Model*				sceneroot = world->GetUserModels();

	VX_ASSERT(navroot->IsClass(VX_Transformer));
	VX_ASSERT(cam && cam->IsClass(VX_Camera));
	while (naveng = (Navigator*) iter.Next())
	{
		if (naveng->IsClass(VX_Navigator))
		{
			naveng->ClearFlags(SharedObj::DOEVENTS);
			naveng->SetActive(false);
		}
	}
	arcball = (ArcBall*) navroot->Find(TEXT(".arcball"), Group::FIND_END | Group::FIND_CHILD);
	if (arcball)
	{
		arcball->SetActive(true);
		arcball->SetFlags(SharedObj::DOEVENTS);
		return;
	}
	arcball = new ArcBall();
	arcball->SetFlags(SharedObj::DOEVENTS);
	if (sceneroot)
	{
		arcball->SetTarget(sceneroot);
		engname = sceneroot->GetName();
	}
	else
		engname = cam->GetName();
	engname += TEXT(".arcball");
	arcball->SetName(engname);
	GetMessenger()->Observe(arcball, Event::MOUSE, NULL);
	navroot->Append(arcball);
}

void DemoView::OnNavFlyer()
{
	Demo*				world = Demo::Get();
	Engine*				navroot = (Engine*) world->GetNavigator();
	Navigator*			naveng;
	Flyer*				flyer;
	GroupIter<Engine>	iter(navroot, Group::CHILDREN);

	VX_ASSERT(navroot->IsClass(VX_Transformer));
	while(naveng = (Navigator*) iter.Next())
	{
		if (naveng->IsClass(VX_Flyer))
		{
			naveng->SetActive(true);
			naveng->SetFlags(SharedObj::DOEVENTS);
		}
		else if (naveng->IsClass(VX_Navigator) || naveng->IsClass(VX_ArcBall))
		{
			naveng->ClearFlags(SharedObj::DOEVENTS);
			naveng->SetActive(false);
		}
	}
	flyer = (Flyer*) navroot->Find(TEXT(".flyer"), Group::FIND_END | Group::FIND_CHILD);
	VX_ASSERT(flyer);
}

void DemoView::OnNavDriver()
{
	Demo*				world = Demo::Get();
	Transformer*		navroot = (Transformer*) world->GetNavigator();
	Navigator*			naveng;
	Camera*				cam = (Camera*) navroot->GetTarget();
	Navigator*			driver;
	GroupIter<Engine>	iter(navroot, Group::CHILDREN);
	Core::String		engname;

	VX_ASSERT(navroot->IsClass(VX_Transformer));
	VX_ASSERT(cam && cam->IsClass(VX_Camera));
	while(naveng = (Navigator*) iter.Next())
	{
		if (naveng->IsClass(VX_Flyer) || naveng->IsClass(VX_ArcBall))
		{
			naveng->ClearFlags(SharedObj::DOEVENTS);
			naveng->SetActive(false);
		}
	}
	driver = (Navigator*) navroot->Find(TEXT(".driver"), Group::FIND_END | Group::FIND_CHILD);
	if (driver)
	{
		driver->SetActive(true);
		driver->SetFlags(SharedObj::DOEVENTS);
		return;
	}
	driver = new Navigator();
	driver->SetFlags(SharedObj::DOEVENTS);
	driver->SetSpeed(0.2f);
	driver->SetTurnSpeed(0.2f);
	engname = cam->GetName();
	GetMessenger()->Observe(driver, Event::MOUSE, NULL);
	navroot->Append(driver);
	FindTerrain(navroot, engname);
	engname += TEXT(".driver");
	driver->SetName(engname);
}

void DemoView::FindTerrain(Transformer* navroot, const TCHAR* targname)
{
	Demo*				world = Demo::Get();
	const Shape*		mod = (const Shape*) world->Find(TEXT("@terr"));
	TerrainCollider*	tcoll = (TerrainCollider*) navroot->Find(TEXT(".terraincollider"), Group::FIND_CHILD | Group::FIND_END);

	if (tcoll != NULL)
		return;
	VX_ASSERT(navroot->IsClass(VX_Transformer));
	if (mod && mod->IsClass(VX_Shape))
	{
		Core::String name(targname);
		tcoll = new TerrainCollider;
		tcoll->BuildTerrain(mod, 5, 5);
		tcoll->SetHeight(5.0f);
		name += TEXT(".terraincollider");
		tcoll->SetName(name);
		navroot->Append(tcoll);
	}
}

}	// end MFC
}	// end Vixen


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

class Logs_model extends CI_Model {
  public function __construct() {
    parent::__construct();
  }

  /*
  * Modo de usar:
  * $this->logs_model->log('usuarios', 31, 'Efetuou login');
  * @return array @usuario/false
  */
  public function log($area, $area_id, $descricao) {
    $log = array(
      'area' => $area,
      'log_id' => $area_id,
      'descricao' => $descricao
    );

    $this->db->set('data_criado', 'NOW()', FALSE);
    $this->db->insert('logs', $log);

    $log_id = $this->db->insert_id();

    return $log_id;
  }
}


text:
package net.exclaimindustries.geohashdroid;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.MapView;

/**
 * The GraticuleMapView is a simple override of MapView to allow it
 * to know what to do with trackball events. Which is to say, make it handle the
 * trackball BEFORE sending things off to the outline overlay.
 *
 * @author Nicholas Killewald
 */
public class GraticuleMapView extends MapView {
    private GraticuleOutlineOverlay mGoo = null;

    public GraticuleMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setOutlineOverlay(GraticuleOutlineOverlay goo) {
        this.mGoo = goo;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.google.android.maps.MapView#onTrackballEvent(android.view.MotionEvent
     * )
     */
    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        boolean toReturn = super.onTrackballEvent(event);

        // AFTER everything's handled, THEN we let the outline overlay know
        // what's going on.
        if (mGoo != null) {
            mGoo.updateGraticule(this);
        }

        return toReturn;
    }
}


text:
using Hearts.Model;
using System;
using System.Linq;

namespace Hearts.Factories
{
    public class StandardDeckFactory : IFactory<Deck>
    {
        public Deck Create()
        {
            var clubs = Enum.GetValues(typeof(Kind)).Cast<Kind>().Select(k => new Card(k, Suit.Clubs));
            var diamonds = Enum.GetValues(typeof(Kind)).Cast<Kind>().Select(k => new Card(k, Suit.Diamonds));
            var hearts = Enum.GetValues(typeof(Kind)).Cast<Kind>().Select(k => new Card(k, Suit.Hearts));
            var spades = Enum.GetValues(typeof(Kind)).Cast<Kind>().Select(k => new Card(k, Suit.Spades));

            return new Deck(clubs.Union(diamonds).Union(hearts).Union(spades).ToList());
        }
    }
}


text:
package org.jrebirth.af.core.resource.font;

import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;

import org.jrebirth.af.api.resource.builder.VariantResourceBuilder;
import org.jrebirth.af.api.resource.font.FontExtension;
import org.jrebirth.af.api.resource.font.FontItem;
import org.jrebirth.af.api.resource.font.FontName;
import org.jrebirth.af.api.resource.font.FontParams;
import org.jrebirth.af.core.resource.ResourceBuilders;

/**
 * The interface FontItemReal used to provided convenient shortcuts for initializing a {@link Font}.
 *
 * @author Sébastien Bordes
 */
public interface FontItemBase extends FontItem {

    /**
     * {@inheritDoc}
     */
    @Override
    default VariantResourceBuilder<FontItem, FontParams, Font, Double> builder() {
        return ResourceBuilders.FONT_BUILDER;
    }

    /**
     * The interface Real provides shortcuts method used to build and register a {@link RealFont}.
     */
    interface Real extends FontItemBase {

        /**
         * Build and register a {@link RealFont} {@link FontParams}.
         *
         * @param name the name of the font
         * @param size the size of the font
         * @param extension the font extension
         */
        default void real(final FontName name, final double size, final FontExtension extension) {
            set(new RealFont(name, size, extension));
        }

        /**
         * Build and register a {@link RealFont} {@link FontParams}.
         *
         * @param name the name of the font
         * @param size the size of the font
         */
        default void real(final FontName name, final double size) {
            set(new RealFont(name, size));
        }

    }

    /**
     * The interface Family provides shortcuts method used to build and register a {@link FamilyFont}.
     */
    interface Family extends FontItemBase {

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         * @param extension the font extension
         */
        default void family(final String family, final double size, final FontExtension extension) {
            set(new FamilyFont(family, size, extension));
        }

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         * @param weight the font weight {@link FontWeight}
         * @param extension the font extension
         */
        default void family(final String family, final double size, final FontWeight weight, final FontExtension extension) {
            set(new FamilyFont(family, size, extension, weight));
        }

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         * @param extension the font extension
         * @param posture the font posture {@link FontPosture}
         */
        default void family(final String family, final double size, final FontExtension extension, final FontPosture posture) {
            set(new FamilyFont(family, size, extension, posture));
        }

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         * @param extension the font extension
         * @param weight the font weight {@link FontWeight}
         * @param posture the font posture {@link FontPosture}
         */
        default void family(final String family, final double size, final FontExtension extension, final FontWeight weight, final FontPosture posture) {
            set(new FamilyFont(family, size, extension, weight, posture));
        }

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         */
        default void family(final String family, final double size) {
            set(new FamilyFont(family, size));
        }

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         * @param weight the font weight {@link FontWeight}
         */
        default void family(final String family, final double size, final FontWeight weight) {
            set(new FamilyFont(family, size, weight));
        }

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         * @param posture the font posture {@link FontPosture}
         */
        default void family(final String family, final double size, final FontPosture posture) {
            set(new FamilyFont(family, size, posture));
        }

        /**
         * Build and register a {@link FamilyFont} {@link FontParams}.
         *
         * @param family the font family
         * @param size the font size
         * @param weight the font weight {@link FontWeight}
         * @param posture the font posture {@link FontPosture}
         */
        default void family(final String family, final double size, final FontWeight weight, final FontPosture posture) {
            set(new FamilyFont(family, size, weight, posture));
        }

    }
}


text:
package frontend;

public interface LevelSettings {

}


text:
package thredds.inventory.partition;

import thredds.filesystem.MFileOS7;
import thredds.inventory.CollectionAbstract;
import thredds.inventory.MFile;
import ucar.nc2.util.CloseableIterator;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.*;

/**
 * Manage MFiles from one directory.
 * Doesnt know about parents or children.
 * Use getFileIterator() for best performance on large directories
 *
 * @author caron
 * @since 11/16/13
 */
public class DirectoryCollection extends CollectionAbstract {

  /**
   * Create standard name = topCollectionName + last directory
   *
   * @param topCollectionName from config, name of the collection
   * @param dir directory for this
   * @return standard collection name, to name the index file
   */
  public static String makeCollectionName(String topCollectionName, Path dir) {
    int last = dir.getNameCount() - 1;
    Path lastDir = dir.getName(last);
    String lastDirName = lastDir.toString();
    return topCollectionName + "-" + lastDirName;
  }

  /**
   * Create standard name = topCollectionName + last directory
   *
   * @param topCollectionName from config, name of the collection
   * @param dir directory for this
   * @return standard collection name, to name the index file
   */
  public static Path makeCollectionIndexPath(String topCollectionName, Path dir, String suffix) {
    String collectionName = makeCollectionName(topCollectionName, dir);
    return Paths.get(dir.toString(), collectionName + suffix);
  }

  ///////////////////////////////////////////////////////////////////////////////////

  final String topCollection;
  final Path collectionDir; // directory for this collection
  final long olderThanMillis;
  final boolean isTop;

  public DirectoryCollection(String topCollectionName, String topDirS, boolean isTop, String olderThan,
      org.slf4j.Logger logger) {
    this(topCollectionName, Paths.get(topDirS), isTop, olderThan, logger);
  }

  public DirectoryCollection(String topCollectionName, Path collectionDir, boolean isTop, String olderThan,
      org.slf4j.Logger logger) {
    super(null, logger);
    this.topCollection = cleanName(topCollectionName);
    this.collectionDir = collectionDir;
    this.collectionName = isTop ? this.topCollection : makeCollectionName(topCollection, collectionDir);
    this.isTop = isTop;

    this.olderThanMillis = parseOlderThanString(olderThan);
    if (debug)
      System.out.printf("Open DirectoryCollection %s%n", collectionName);
  }

  @Override
  public String getRoot() {
    return collectionDir.toString();
  }

  @Override
  public String getIndexFilename(String suffix) {
    if (isTop)
      return super.getIndexFilename(suffix);
    Path indexPath = DirectoryCollection.makeCollectionIndexPath(topCollection, collectionDir, suffix);
    return indexPath.toString();
  }

  @Override
  public Iterable<MFile> getFilesSorted() throws IOException {
    return makeFileListSorted();
  }

  @Override
  public CloseableIterator<MFile> getFileIterator() throws IOException {
    return new MyFileIterator(collectionDir);
  }

  @Override
  public void close() {
    if (debug)
      System.out.printf("Close DirectoryCollection %s%n", collectionName);
  }

  // returns everything in the current directory, subject to sfilter
  private class MyFileIterator implements CloseableIterator<MFile> {
    int debugNum;
    DirectoryStream<Path> dirStream;
    Iterator<Path> dirStreamIterator;
    MFile nextMFile;
    int count;

    MyFileIterator(Path dir) throws IOException {
      if (debug) {
        debugNum = debugCount++;
        System.out.printf(" MyFileIterator %s (%d)", dir, debugNum);
      }
      try {
        dirStream = Files.newDirectoryStream(dir, new MyStreamFilter());
        dirStreamIterator = dirStream.iterator();
      } catch (IOException ioe) {
        logger.error("Files.newDirectoryStream failed to open directory " + dir.getFileName(), ioe);
        throw ioe;
      }
    }

    public boolean hasNext() {
      while (true) {
        // if (debug && count % 100 == 0) System.out.printf("%d ", count);
        count++;
        if (!dirStreamIterator.hasNext()) {
          nextMFile = null;
          return false;
        }

        long now = System.currentTimeMillis();
        try {
          Path nextPath = dirStreamIterator.next();
          BasicFileAttributes attr = Files.readAttributes(nextPath, BasicFileAttributes.class);
          if (attr.isDirectory())
            continue;
          FileTime last = attr.lastModifiedTime();
          long millisSinceModified = now - last.toMillis();
          if (millisSinceModified < olderThanMillis)
            continue;
          nextMFile = new MFileOS7(nextPath, attr);
          return true;

        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }

    public MFile next() {
      if (nextMFile == null)
        throw new NoSuchElementException();
      return nextMFile;
    }

    public void remove() {
      throw new UnsupportedOperationException();
    }

    // better alternative is for caller to send in callback (Visitor pattern)
    // then we could use the try-with-resource
    public void close() throws IOException {
      if (debug)
        System.out.printf(" closed %d (%d)%n", count, debugNum);
      dirStream.close();
    }
  }

  ////////////////////////////////////////////////////////////////////////////////////////////
  private static final boolean debug = false;
  private static int debugCount;

  // this idiom keeps the iterator from escaping, so that we can use try-with-resource, and ensure DirectoryStream
  // closes. like++
  public void iterateOverMFileCollection(Visitor visit) throws IOException {
    if (debug)
      System.out.printf(" iterateOverMFileCollection %s ", collectionDir);
    int count = 0;
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(collectionDir, new MyStreamFilter())) {
      for (Path p : ds) {
        try {
          BasicFileAttributes attr = Files.readAttributes(p, BasicFileAttributes.class);
          if (!attr.isDirectory())
            visit.consume(new MFileOS7(p));
          if (debug)
            System.out.printf("%d ", count++);
        } catch (IOException ioe) {
          // catch error and skip file
          logger.error("Failed to read attributes from file found in Files.newDirectoryStream ", ioe);
        }
      }
    }
    if (debug)
      System.out.printf("%d%n", count);
  }

  public interface Visitor {
    void consume(MFile mfile);
  }

}


text:
from kivy.core.window import Window
from kivy.graphics.instructions import InstructionGroup
from kivy.graphics import Color, Ellipse, Rectangle, Line
from kivy.graphics import Translate
from kivy.uix.image import Image

class TextureHolder(object):
    def __init__(self, texture):
        self.texture = texture
        self.right = True

class Player(InstructionGroup):
    def __init__(self, init_pos, camera, collision, controller):
        super(Player, self).__init__()

        self.pos = init_pos
        self.y_vel = 0

        self.texture_size = (150, 150)
        self.size = (100, 150)

        self.frame = 0
        texture = Image(source='../../data/kramer_sprites.png').texture
        #texture.mag_filter = 'nearest'
        self.frames = [TextureHolder(texture.get_region(x, 0, 150, 200)) for x in [0, 150, 300, 450]]

        self.sprite = Rectangle(texture=self.frames[0].texture, pos=init_pos, size=self.texture_size)
        self.add(Color(1, 1, 1))
        self.add(self.sprite)

        self.controller = controller
        self.collision = collision
        self.camera = camera

        self.can_jump = True
        self.og_jump_f = 800
        self.jump_f = self.og_jump_f

    def move_absolute(self, pos):
        self.pos = pos

    def move_relative(self, pos):
        x, y = pos
        old_x, old_y = self.pos
        self.pos = (x + old_x, y + old_y)
        self.sprite.pos = self.pos

    def jump(self):
        if self.can_jump > 0:
            self.y_vel = self.jump_f
            self.can_jump -= 1

    def on_update(self, dt):
        terminal_vel = -1000

        x, y = self.pos
        delta_x = 0
        delta_y = self.y_vel * dt

        alpha = 200
        delta = dt * alpha
        key_mappings = {'left':  -delta,
                        'right':  delta}

        for key, value in key_mappings.items():
            if key in self.controller.active_keys and self.controller.active_keys[key]:
                delta_x = value

                #Update sprite
                self.frame += 1
                new_frame = self.frames[self.frame / 5 % len(self.frames)]
                if key == 'left' and new_frame.right == True:
                    new_frame.right = False
                    new_frame.texture.flip_horizontal()
                if key == 'right' and new_frame.right == False:
                    new_frame.right = True
                    new_frame.texture.flip_horizontal()
                self.sprite.texture = new_frame.texture

        new_pos = x + delta_x, y + delta_y
        down_collision = self.collision.check_down_collision(self.pos, new_pos, self.size)

        if self.collision.check_side_collision(self.pos, new_pos, self.size):
            self.can_jump = True
            self.jump_f *= .95
            terminal_vel = -200
        else:
            self.can_jump = False
            self.camera.move_relative((delta_x, 0))
            self.move_relative((delta_x, 0))

        if down_collision:
            self.can_jump = True
            self.y_vel = 0
            self.jump_f = self.og_jump_f
            self.move_relative((0, down_collision - y))
        else:
            self.move_relative((0, delta_y))
            g = -1300
            self.y_vel = max(self.y_vel + g * dt, terminal_vel)


text:
from setuptools import setup, find_packages

def readme():
    with open('README.rst') as f:
        return f.read()

setup(
    name='pysharperratio',
    version='0.01.12',
    description='A moment-free estimator of the Sharpe (signal-to-noise) ratio.',
    long_description=readme(),
    author='Amir Sani',
    url='http://www.amirsani.com',
    author_email='reachme@amirsani.com',
    download_url='https://github.com/amirsani/pySharpeRratio',
    # packages=['pysharperratio'],
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    #
    # Include additional files into the package
    include_package_data=True,
    package_data={'pysharperratio': ['../*.pkl']},
    zip_safe=False
)


text:
using System;

namespace ElmahLogAnalyzer.Core.Common
{
	public static class DateTimeExtensions
	{
		public static bool IsBetween(this DateTime source, DateTime startDate, DateTime endDate)
		{
			return source >= startDate && source <= endDate;
		}

		public static bool IsBetween(this DateTime source, DateInterval interval)
		{
			if (interval == null)
			{
				throw new ArgumentNullException("interval");
			}

			return source.IsBetween(interval.StartDate, interval.EndDate);
		}

		public static string ToTruncatedString(this DateTime date)
		{
			var year = date.Year;
			var month = date.Month.ToString();
			var day = date.Day.ToString();
			var hour = date.Hour.ToString();
			var minute = date.Minute.ToString();

			return string.Format("{0}{1}{2}_{3}{4}", year, month.PadLeft(2, '0'), day.PadLeft(2, '0'), hour.PadLeft(2, '0'), minute).PadLeft(2, '0');
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>sparknlp_jsl.annotator.embeddings.entity_chunk_embeddings — Spark NLP 4.0.0 documentation</title>

  <link href="../../../../static/styles/theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">
<link href="../../../../static/styles/pydata-sphinx-theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">

  <link rel="stylesheet"
    href="../../../../static/vendor/fontawesome/6.1.2/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../../../static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/css/custom.css" />

  <link rel="preload" as="script" href="../../../../static/scripts/pydata-sphinx-theme.js?digest=1e1de1a1873e13ef5536">

    <link rel="shortcut icon" href="../../../../static/fav.ico"/>
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="docsearch:language" content="en">

  <input type="checkbox" class="sidebar-toggle" name="__primary" id="__primary">

  <input type="checkbox" class="sidebar-toggle" name="__secondary" id="__secondary">

<form class="bd-search d-flex align-items-center" action="../../../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
  Ctrl+K
</form>

        Site Navigation

                        Getting Started

                        API Reference

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

        Site Navigation

                        Getting Started

                        API Reference

Source code for sparknlp_jsl.annotator.embeddings.entity_chunk_embeddings

from sparknlp.annotator import BertSentenceEmbeddings
from sparknlp.common import *

[docs]class EntityChunkEmbeddings(BertSentenceEmbeddings, HasEngine):
    """Weighted average embeddings of multiple named entities chunk annotations

    ====================== =======================
    Input Annotation types Output Annotation type
    ====================== =======================
    ``DEPENDENCY, CHUNK``  ``SENTENCE_EMBEDDINGS``
    ====================== =======================

    Parameters
    ----------
    targetEntities
        Target entities and their related entities
    entityWeights
        Relative weights of entities.
    maxSyntacticDistance
        Maximal syntactic distance between related entities. Default value is 2.

    Examples
    --------
    >>> import sparknlp
    >>> from sparknlp.base import *
    >>> from sparknlp.common import *
    >>> from sparknlp.annotator import *
    >>> from sparknlp.training import *
    >>> import sparknlp_jsl
    >>> from sparknlp_jsl.base import *
    >>> from sparknlp_jsl.annotator import *
    >>> from pyspark.ml import Pipeline
    >>> documenter = DocumentAssembler()\
    ...     .setInputCol("text")\
    ...     .setOutputCol("documents")
    >>> sentence_detector = SentenceDetector() \
    ...     .setInputCols("documents") \
    ...     .setOutputCol("sentences")
    >>> tokenizer = Tokenizer() \
    ...     .setInputCols("sentences") \
    ...     .setOutputCol("tokens")
    >>> embeddings = WordEmbeddingsModel() \
    ...     .pretrained("embeddings_clinical", "en", "clinical/models")\
    ...     .setInputCols(["sentences", "tokens"])\
    ...     .setOutputCol("embeddings")
    >>> ner_model = MedicalNerModel()\
    ...     .pretrained("ner_posology_large", "en", "clinical/models")\
    ...     .setInputCols(["sentences", "tokens", "embeddings"])\
    ...     .setOutputCol("ner")
    >>> ner_converter = NerConverterInternal()\
    ...     .setInputCols("sentences", "tokens", "ner")\
    ...     .setOutputCol("ner_chunks")
    >>> pos_tager = PerceptronModel()\
    ...     .pretrained("pos_clinical", "en", "clinical/models")\
    ...     .setInputCols("sentences", "tokens")\
    ...     .setOutputCol("pos_tags")
    >>> dependency_parser = DependencyParserModel()\
    ...     .pretrained("dependency_conllu", "en")\
    ...     .setInputCols(["sentences", "pos_tags", "tokens"])\
    ...     .setOutputCol("dependencies")
    >>> drug_chunk_embeddings = EntityChunkEmbeddings()\
    ...     .pretrained("sbiobert_base_cased_mli","en","clinical/models")\
    ...     .setInputCols(["ner_chunks", "dependencies"])\
    ...     .setOutputCol("drug_chunk_embeddings")\
    ...     .setMaxSyntacticDistance(3)\
    ...     .setTargetEntities({"DRUG": []})
    ...     .setEntityWeights({"DRUG": 0.8, "STRENGTH": 0.2, "DOSAGE": 0.2, "FORM": 0.5})
    >>> sampleData = "The parient was given metformin 125 mg, 250 mg of coumadin and then one pill paracetamol"
    >>> data = SparkContextForTest.spark.createDataFrame([[sampleData]]).toDF("text")
    >>> pipeline = Pipeline().setStages([
    ...     documenter,
    ...     sentence_detector,
    ...     tokenizer,
    ...     embeddings,
    ...     ner_model,
    ...     ner_converter,
    ...     pos_tager,
    ...     dependency_parser,
    ...     drug_chunk_embeddings])
    >>> results = pipeline.fit(data).transform(data)
    >>> results = results \
    ...     .selectExpr("explode(drug_chunk_embeddings) AS drug_chunk") \
    ...     .selectExpr("drug_chunk.result", "slice(drug_chunk.embeddings, 1, 5) AS drug_embedding") \
    ...     .cache()
    >>> results.show(truncate=False)
    +-----------------------------+-----------------------------------------------------------------+
    |                       result|                                                  drug_embedding"|
    +-----------------------------+-----------------------------------------------------------------+
    |metformin 125 mg             |[-0.267413, 0.07614058, -0.5620966, 0.83838946, 0.8911504]       |
    |250 mg coumadin              |[0.22319649, -0.07094894, -0.6885556, 0.79176235, 0.82672405]    |
    |one pill paracetamol         |[-0.10939768, -0.29242, -0.3574444, 0.3981813, 0.79609615]       |
    +-----------------------------+-----------------------------------------------------------------+
    """

[docs]    name = "EntityChunkEmbeddings"

[docs]    entityWeights = Param(Params._dummy(),
                          "entityWeights",
                          "Relative weights of named entities.",
                          typeConverter=TypeConverters.identity)

[docs]    targetEntities = Param(Params._dummy(),
                           "targetEntities",
                           "Target entities and the entities they are related to.",
                           typeConverter=TypeConverters.identity)

[docs]    maxSyntacticDistance = Param(Params._dummy(), "maxSyntacticDistance",
                                 "Maximal syntactic distance between related DRUG and non-DRUG entities",
                                 TypeConverters.toInt)

[docs]    def setEntityWeights(self, weights={}):
        """Sets the relative weights of the embeddings of specific entities. By default the dictionary is empty and
         all entities have equal weights. If non-empty and some entity is not in it, then its weight is set to 0.

        Parameters
        ----------
        weights: : dict[str, float]
            Dictionary with the relative weighs of entities. The notation TARGET_ENTITY:RELATED_ENTITY can be used to
            specify the weight of a entity which is related to specific target entity (e.g. "DRUG:SYMPTOM": 0.3).
            Entity names are case-insensitive.
        """
        self._call_java("setEntityWeights", weights)

[docs]    def setTargetEntities(self, entities={}):
        """Sets the target entities and maps them to their related entities. A target entity with an empty list of
        related entities means all other entities are assumed to be related to it.

        Parameters
        ----------
        entities: dict[str, list[str]]
            Dictionary with target and related entities (TARGET: [RELATED1, RELATED2,...]). If the list of related
            entities is empty, then all non-target entities are considered.
            Entity names are case insensitive.
        """
        self._call_java("setTargetEntities", entities)

[docs]    def setMaxSyntacticDistance(self, distance):
        """Sets the maximal syntactic distance between related entities. Default value is 2.
        Parameters
        ----------
        distance : int
            Maximal syntactic distance
        """
        return self._set(maxSyntacticDistance=distance)

    @keyword_only
    def __init__(self, classname="com.johnsnowlabs.nlp.annotators.embeddings.EntityChunkEmbeddings", java_model=None):
        super(EntityChunkEmbeddings, self).__init__(
            classname=classname,
            java_model=java_model
        )
        self._setDefault(
            dimension=768,
            batchSize=32,
            maxSentenceLength=128,
            caseSensitive=True,
            maxSyntacticDistance=2
        )

    @staticmethod

[docs]    def pretrained(name="sbiobert_base_cased_mli", lang="en", remote_loc="clinical/models"):
        from sparknlp_jsl.pretrained import InternalResourceDownloader
        return InternalResourceDownloader.downloadModel(EntityChunkEmbeddings, name, lang, remote_loc,
                                                        j_dwn='InternalsPythonResourceDownloader')

    © Copyright 2022, John Snow Labs.

Created using Sphinx 5.3.0.


text:
package net.finmath.experiments.concurrency;

import java.util.stream.IntStream;

/**
 * This is a test of Java 8 parallel streams.
 *
 * We are testing nested parallel forEach loops, which appear to
 * have unexpected poor performance in Java 1.8.0u5.
 *
 * We have a nested stream.parallel().forEach():
 *
 * The inner loop is independent (stateless, no interference, etc. - except of the use of a common pool)
 * and consumes 1 second in total in the worst case, namely if processed sequential.
 * Half of the tasks of the outer loop consume 10 seconds prior that loop.
 * Half consume 10 seconds after that loop.
 * We have a boolean which allows to switch the inner loop from parallel() to sequential().
 * Hence every thread consumes 11 seconds (worst case) in total.
 * Now: submitting 24 outer-loop-tasks to a pool of 8 we would expect 24/8 * 11 = 33 seconds at best (on an 8 core or better machine).
 *
 * The result is:
 * - With inner sequential loop:	33 seconds.
 * - With inner parallel loop:		>80 seconds (I had 92 seconds).
 *
 * Now, there is a funny workaround. The method
 * wraps every operation in its own thread. Use this to wrap the inner loop in its
 * own thread via
 * {@code
 * 					wrapInThread( () ->
 * 						IntStream.range(0,numberOfTasksInInnerLoop).parallel().forEach(j -> {
 * 							burnTime(10);
 * 						}));
 * }
 * And the performance issue is gone. Note that this does not introduce any new
 * parallelism and that the inner loop tasks are still submitted to the same
 * common fork-join pool.
 *
 * The reason, why this fix works, is because the inner loop is started form a Thread
 * and not from possible ForkJoinWorkerThread of the outer loop. In the latter case
 * the ForkJoinTask by mistake assumes that the starting thread is a worker of itself
 * and issues a join, effectively joining inner loop tasks with outer loop tasks.
 *
 * @author Christian Fries
 */
public class NestedParallelForEachTest {

	// The program uses 33 sec with this boolean to false and around 80+ with this boolean true:
	private final boolean isInnerStreamParallel		= true;

	// Setup: Inner loop task 0.01 sec in worse case. Outer loop task: 10 sec + inner loop. This setup: (100 * 0.01 sec + 10 sec) * 24/8 = 33 sec.
	private final int		numberOfTasksInOuterLoop = 24;				// In real applications this can be a large number (e.g. > 1000).
	private final int		numberOfTasksInInnerLoop = 100;				// In real applications this can be a large number (e.g. > 1000).
	private final int		concurrentExecutionsLimitForStreams	= 8;	// java.util.concurrent.ForkJoinPool.common.parallelism

	// For those, who do not trust the use of Thread.sleep().
	private final boolean	isCPUTimeBurned = false;					// Set to true, if you like a true loop, and not Thread.sleep()
	private final long	 	cpuTimeBurningCountPerMillis = 800000;		// You might need to calibrate this for your machine

	public static void main(String[] args) {
		(new NestedParallelForEachTest()).testNestedLoops();
	}

	public void testNestedLoops() {

		final long start = System.currentTimeMillis();

		System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism",Integer.toString(concurrentExecutionsLimitForStreams));
		System.out.println("java.util.concurrent.ForkJoinPool.common.parallelism = " + System.getProperty("java.util.concurrent.ForkJoinPool.common.parallelism"));

		// Outer loop
		IntStream.range(0,numberOfTasksInOuterLoop).parallel().forEach(i -> {

			try {
				if(i < 10) {
					burnTime(10 * 1000);
				}

				System.out.println(i + "\t" + Thread.currentThread());

				if(isInnerStreamParallel) {
					// Inner loop as parallel: worst case (sequential) it takes 10 * numberOfTasksInInnerLoop millis
					IntStream.range(0,numberOfTasksInInnerLoop).parallel().forEach(j -> {
						burnTime(10);
					});
				}
				else {
					// Inner loop as sequential
					IntStream.range(0,numberOfTasksInInnerLoop).sequential().forEach(j -> {
						burnTime(10);
					});
				}

				if(i >= 10) {
					burnTime(10 * 1000);
				}
			} catch (final Exception e) { e.printStackTrace(); }

		});

		final long end = System.currentTimeMillis();

		System.out.println("Done in " + (end-start)/1000 + " sec.");
	}

	private double burnTime(long millis) {
		if(isCPUTimeBurned) {
			double x = 0;
			for(long i=0; i<millis*cpuTimeBurningCountPerMillis; i++) {
				x += Math.cos(0.0);
			}
			return x/cpuTimeBurningCountPerMillis;
		}
		else {
			try {
				Thread.sleep(millis);
			} catch (final InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return millis;
		}
	}

	private void wrapInThread(Runnable runnable) {
		final Thread t = new Thread(runnable, "Wrapper Thread");
		try {
			t.start();
			t.join();
		} catch (final InterruptedException e) { }
	}
}


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

<introspection xmlns="http://www.wyona.org/neutron/2.0">
<navigation>  <sitetree href="./" method="PROPFIND"/></navigation>
  <resource name="cruisecontrol.html">
  <edit mime-type="application/xhtml+xml">
    <checkout url="cruisecontrol.html?yanel.resource.viewid=source&yanel.resource.usecase=checkout" method="GET"/>
    <checkin  url="cruisecontrol.html?yanel.resource.usecase=checkin" method="PUT"/>
  </edit>
  </resource>
</introspection>


text:
package com.floreysoft.jmte.message;

import java.util.Map;

import com.floreysoft.jmte.ErrorHandler;
import com.floreysoft.jmte.token.Token;

public class SilentErrorHandler extends AbstractErrorHandler implements ErrorHandler {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void error(String messageKey, Token token, Map<String, Object> parameters) throws ParseException {
		// Silent by design
	}
}


text:
Item::Item(const char* name, const char* description, Entity* parent) : Entity(name, description, parent)
{
	Type = ITEM;
	MinValue = MaxValue = 0;
	ItemType = COMMON;
	Closed = false;
	Openable = false;
}

Item::~Item()
{
}

void Item::Look() const
{
	if (ItemType == CONTAINER && SubEntities.size() > 0)
	{
		if (!Closed)
		{
			cout << Name << " contains: " << endl;
			for (Entity* entity : SubEntities)
			{
				cout << " - " << entity->Name << endl;
			}
			cout << endl;
		}
		else
		{
			cout << Name << "(closed)" << endl << Description << endl << endl;
		}
	}
	else
	{
		Entity::Look();
	}
}

int Item::GetValue() const
{
	return randomize(MinValue, MaxValue);
}


text:
using OfficeDevPnP.Core.Framework.Provisioning.Connectors;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml
{
    /// <summary>
    /// Provider for xml based configurations
    /// </summary>
    public abstract class XMLTemplateProvider : TemplateProviderBase
    {

        #region Constructor
        protected XMLTemplateProvider()
            : base()
        {

        }
        protected XMLTemplateProvider(FileConnectorBase connector)
            : base(connector)
        {
        }
        #endregion

        #region Base class overrides

        public override List<ProvisioningTemplate> GetTemplates()
        {
            var formatter = new XMLPnPSchemaFormatter();
            formatter.Initialize(this);
            return (this.GetTemplates(formatter));
        }

        public override List<ProvisioningTemplate> GetTemplates(ITemplateFormatter formatter)
        {
            List<ProvisioningTemplate> result = new List<ProvisioningTemplate>();

            // Retrieve the list of available template files
            List<String> files = this.Connector.GetFiles();

            // For each file
            foreach (var file in files)
            {
                if (file.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Load it from a File Stream
                    Stream stream = this.Connector.GetFileStream(file);

                    ProvisioningTemplate provisioningTemplate;
                    try
                    {
                        // And convert it into a ProvisioningTemplate
                        provisioningTemplate = formatter.ToProvisioningTemplate(stream);
                    }
                    catch (ApplicationException)
                    {
                        Log.Warning(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_Providers_XML_InvalidFileFormat, file);
                        continue;
                    }

                    if (provisioningTemplate != null)
                    {
                        // Add the template to the result
                        result.Add(provisioningTemplate);
                    }
                }
            }

            return (result);
        }

        public override ProvisioningTemplate GetTemplate(string uri)
        {
            var formatter = new XMLPnPSchemaFormatter();
            formatter.Initialize(this);
            return (this.GetTemplate(uri, null, formatter));
        }

        public override ProvisioningTemplate GetTemplate(string uri, string identifier)
        {
            var formatter = new XMLPnPSchemaFormatter();
            formatter.Initialize(this);
            return (this.GetTemplate(uri, identifier, formatter));
        }

        public override ProvisioningTemplate GetTemplate(string uri, ITemplateFormatter formatter)
        {
            return (this.GetTemplate(uri, null, formatter));
        }

        public override ProvisioningTemplate GetTemplate(string uri, string identifier, ITemplateFormatter formatter)
        {
            Log.Info("OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.XmlTemplateProvider.GetTemplate",
                    "Entered.");

            if (String.IsNullOrEmpty(uri))
            {
                throw new ArgumentException("uri");
            }

            Log.Info("OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.XmlTemplateProvider.GetTemplate",
                    "Processing with uri '{0}' and identifier '{1}'.", uri, identifier);

            // COB - temp hard-coding of path here, since documentation isn't clear on the expected config!
            var filePath = @"D:\home\site\wwwroot\Resources\SiteTemplates\ProvisioningTemplates\" + uri;

            Log.Info("OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.XmlTemplateProvider.GetTemplate",
                    "Attempting to load template file at physical path '{0}'", filePath);

            MemoryStream stream = new MemoryStream();
            using (FileStream fileStream = System.IO.File.OpenRead(filePath))
            {
                stream.SetLength(fileStream.Length);
                fileStream.Read(stream.GetBuffer(), 0, (int)fileStream.Length);
            }

            stream.Position = 0;

            // COB - need to translate URI for Azure Web App filepath..
            //uri = Environment.GetEnvironmentVariable("HOME") + @"\";
            //Log.Info("OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.XmlTemplateProvider.GetTemplate",
            //        "Fetched the following path from config for template file: '{0}'", uri);

            //// COB added - for referencing files in Azure WebJob/WebApp..
            //uri = UrlUtility.ReplaceForwardSlashesWithBackslashes(Environment.GetEnvironmentVariable("HOME"));
            //Log.Info("OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.XmlTemplateProvider.GetTemplate",
            //        "Built unescaped path: '{0}'", uri);

            //// Get the XML document from a File Stream
            //Stream stream = this.Connector.GetFileStream(uri);

            // And convert it into a ProvisioningTemplate
            ProvisioningTemplate provisioningTemplate = formatter.ToProvisioningTemplate(stream, identifier);

            // Store the identifier of this template, is needed for latter save operation
            this.Uri = uri;

            return (provisioningTemplate);
        }

        public override void Save(ProvisioningTemplate template)
        {
            var formatter = new XMLPnPSchemaFormatter();
            this.Save(template, formatter);
        }

        public override void Save(ProvisioningTemplate template, ITemplateFormatter formatter)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            SaveToConnector(template, this.Uri, formatter);
        }

        public override void SaveAs(ProvisioningTemplate template, string uri)
        {
            var formatter = new XMLPnPSchemaFormatter();
            this.SaveAs(template, uri, formatter);
        }

        public override void SaveAs(ProvisioningTemplate template, string uri, ITemplateFormatter formatter)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            if (String.IsNullOrEmpty(uri))
            {
                throw new ArgumentException("uri");
            }

            SaveToConnector(template, uri, formatter);
        }

        public override void Delete(string uri)
        {
            if (String.IsNullOrEmpty(uri))
            {
                throw new ArgumentException("identifier");
            }

            this.Connector.DeleteFile(uri);
        }

        #endregion

        #region Helper methods

        private void SaveToConnector(ProvisioningTemplate template, string uri, ITemplateFormatter formatter)
        {
            if (String.IsNullOrEmpty(template.Id))
            {
                template.Id = Path.GetFileNameWithoutExtension(uri);
            }

            using (var stream = formatter.ToFormattedTemplate(template))
            {
                this.Connector.SaveFileStream(uri, stream);
            }
        }

        #endregion
    }
}


text:
namespace ash::secure_channel {

FakeBleAdvertisementGenerator::FakeBleAdvertisementGenerator() {}

FakeBleAdvertisementGenerator::~FakeBleAdvertisementGenerator() {}

std::unique_ptr<DataWithTimestamp>
FakeBleAdvertisementGenerator::GenerateBleAdvertisementInternal(
    multidevice::RemoteDeviceRef remote_device,
    const std::string& local_device_public_key) {
  return std::move(advertisement_);
}

}  // namespace ash::secure_channel


text:
/*===================================================*\
 * Globals
\*===================================================*/
var UA = require('./SkyDuelUserActions'),
  HashArray = require('hasharray');

/*===================================================*\
 * SkyDuelUserInputProcessor()
\*===================================================*/
var SkyDuelUserInputProcessor = function(game) {
  this.game = game;
};

/*===================================================*\
 * Prototype
\*===================================================*/
SkyDuelUserInputProcessor.prototype = {
  /*===========================*\
   * Methods
  \*===========================*/
  update: function (userInput, elapsed, username) {
    var actions = new HashArray(['id', 'name']);

    if (userInput.left)
      actions.add(UA.BANK_LEFT);
    else if (userInput.right)
      actions.add(UA.BANK_RIGHT);

    if (userInput.up)
      actions.add(UA.ACCELERATE);
    else if (userInput.down)
      actions.add(UA.DECELERATE);

    if (userInput.trigger)
      actions.add(UA.TRIGGER);

    this.game.applyUserAction(actions, elapsed, username);
  }
};

/*===================================================*\
 * Export (nodejs and browser agent)
\*===================================================*/
module.exports = SkyDuelUserInputProcessor;


text:
import React, { FC, ReactNode } from 'react'
import classNames from 'classnames'
import Button from '../button'
import { NativeProps, withNativeProps } from '../../utils/native-props'

export type Action = {
  key: string | number
  text: ReactNode
  disabled?: boolean
  danger?: boolean
  primary?: boolean
  onClick?: () => void | Promise<void>
} & NativeProps

export const ModalActionButton: FC<{
  action: Action
  onAction: () => void | Promise<void>
}> = props => {
  const { action } = props

  return withNativeProps(
    props.action,
    <Button
      key={action.key}
      onClick={props.onAction}
      className={classNames('adm-modal-button', {
        'adm-modal-button-primary': props.action.primary,
      })}
      fill={props.action.primary ? 'solid' : 'none'}
      size={props.action.primary ? 'large' : 'middle'}
      block
      color={action.danger ? 'danger' : 'primary'}
      loading='auto'
      disabled={action.disabled}
    >
      {action.text}
    </Button>
  )
}


text:
{% extends "basic/layout.html" %}

{% block relbar1 %}
{% endblock %}

{% block sidebar1 %}{{ sidebar() }}{% endblock %}
{% block sidebar2 %}{% endblock %}

{% block document %}

Nigel Small

        {{ super() }}

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

{% endblock %}

{% block relbar2 %}
{% endblock %}


text:
@interface MOBProjectionEPSG3910 : MOBProjection

@end


text:
package egovframework.com.ssi.syi.iis.service;

import java.io.Serializable;

public class CntcInstt implements Serializable {

	private static final long serialVersionUID = -4176567860232641639L;

	/*
	 * 기관ID
	 */
	private String insttId        = "";

	/*
	 * 기관명
	 */
	private String insttNm        = "";

	/*
	 * 최초등록자ID
	 */
	private String frstRegisterId = "";

	/*
	 * 최종수정자ID
	 */
	private String lastUpdusrId   = "";

	/**
	 * insttId attribute 를 리턴한다.
	 * @return String
	 */
	public String getInsttId() {
		return insttId;
	}

	/**
	 * insttId attribute 값을 설정한다.
	 * @param insttId String
	 */
	public void setInsttId(String insttId) {
		this.insttId = insttId;
	}

	/**
	 * insttNm attribute 를 리턴한다.
	 * @return String
	 */
	public String getInsttNm() {
		return insttNm;
	}

	/**
	 * insttNm attribute 값을 설정한다.
	 * @param insttNm String
	 */
	public void setInsttNm(String insttNm) {
		this.insttNm = insttNm;
	}

	/**
	 * frstRegisterId attribute 를 리턴한다.
	 * @return String
	 */
	public String getFrstRegisterId() {
		return frstRegisterId;
	}

	/**
	 * frstRegisterId attribute 값을 설정한다.
	 * @param frstRegisterId String
	 */
	public void setFrstRegisterId(String frstRegisterId) {
		this.frstRegisterId = frstRegisterId;
	}

	/**
	 * lastUpdusrId attribute 를 리턴한다.
	 * @return String
	 */
	public String getLastUpdusrId() {
		return lastUpdusrId;
	}

	/**
	 * lastUpdusrId attribute 값을 설정한다.
	 * @param lastUpdusrId String
	 */
	public void setLastUpdusrId(String lastUpdusrId) {
		this.lastUpdusrId = lastUpdusrId;
	}

}


text:
package miguelbcr.ok_adapters.base_adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * OkAdapter for BaseAdapter
 * @param <T> The model data associated with the view.
 * @param <V> The view
 */
public abstract class OkBaseAdapter<T, V extends View & OkBaseAdapter.Binder<T>> extends BaseAdapter {
    private List<T> items = new ArrayList<>();
    private ViewHolder<T, V> holder = null;

    public abstract V inflateView();

    @Override public int getCount() {
        return items.size();
    }

    @Override public T getItem(int position) {
        return items.get(position);
    }

    @Override public long getItemId(int position) {
        return position;
    }

    @Override public View getView(int position, View view, ViewGroup parent) {
        final T item = items.get(position);

        if (view == null) {
            view = inflateView();
            holder = new ViewHolder(view);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        holder.getView().bind(item, position, getCount());

        return view;
    }

    public void add(T item) {
        items.add(item);
        notifyDataSetChanged();
    }

    public void addAll(List<T> data) {
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void setAll(List<T> data) {
        clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public List<T> getAll() {
        return items;
    }

    public void clear() {
        items.clear();
    }

    public static class ViewHolder<T, V extends View & OkBaseAdapter.Binder<T>> {
        private final V view;

        public ViewHolder(V itemView) {
            view = itemView;
        }

        public V getView() {
            return view;
        }
    }

    public interface Binder<T> {
        void bind(T item, int position, int count);
    }

}


text:
var chai = require('chai');

var chaiSubset = require('chai-subset');
chai.use(chaiSubset);

process.on('unhandledRejection', function (error) {
  console.error('Unhandled Promise Rejection:');
  console.error(error && error.stack || error);
});


text:
<?php

namespace App;

use Silex\Api\ControllerProviderInterface;
use Silex\Application as SilexApplication;

class ControllerProvider implements ControllerProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function connect(SilexApplication $app)
    {
        $controllers = $app['controllers_factory'];
        $controllers->post('account/register', 'ctrl.account:create');
        $controllers->post('account/login', 'ctrl.account:login');
        $controllers->patch('account/{uid}', 'ctrl.account:patch');
        $controllers->get('account/{uid}', 'ctrl.account:get');

        return $controllers;
    }
}


text:
/**
 * Module dependencies
 */

var assert = require('assert');
var util = require('util');
var _ = require('lodash');
var async = require('async');
var Sails = require('../../lib').Sails;

describe('req.session', function (){

  var app;

  before(function (done){
    app = Sails();
    app.load({
      globals: false,
      loadHooks: [
        'moduleloader',
        'userconfig',
        'session'
      ],
      session: {
        adapter: 'memory',
        key: 'sails.sid',
        secret: 'af9442683372850a85a87150c47b4a31'
      }
    }, done);
  });

  describe('when responding to a virtual request',function (){

    var doesSessionExist;
    var isSessionAnObject;
    var doesTestPropertyStillExist;

    before(function setupTestRoute(){
      app.post('/sessionTest', function (req, res){
        doesSessionExist = !!req.session;
        isSessionAnObject = _.isObject(req.session);
        req.session.something = 'some string';
        res.send();
      });

      app.get('/sessionTest', function (req, res){
        doesSessionExist = !!req.session;
        isSessionAnObject = _.isObject(req.session);
        doesTestPropertyStillExist = req.session.something === 'some string';
        res.send();
      });

    });

    it('should exist', function (done) {
      app.request({
        url: '/sessionTest',
        method: 'POST',
        params: {},
        headers: {}
      }, function (err, res, body){
        if (err) return done(err);
        if (res.statusCode !== 200) return done(new Error('Expected 200 status code'));
        if (!doesSessionExist) return done(new Error('req.session should exist.'));
        if (!isSessionAnObject) return done(new Error('req.session should be an object.'));
        return done();
      });
    });

    //
    // To test:
    //
    // DEBUG=express-session mocha test/unit/req.session.test.js -b -g 'should persist'
    //

    it('should persist data between requests', function (done){
      app.request({
        url: '/sessionTest',
        method: 'POST',
        params: {},
        headers: {}
      }, function (err, clientRes, body){
        if (err) return done(err);
        if (clientRes.statusCode !== 200) return done(new Error('Expected 200 status code'));
        if (!doesSessionExist) return done(new Error('req.session should exist.'));
        if (!isSessionAnObject) return done(new Error('req.session should be an object.'));

        app.request({
          url: '/sessionTest',
          method: 'GET',
          params: {},
          headers: {
            cookie: clientRes.headers['set-cookie']
          }
        }, function (err, clientRes, body){
          if (err) return done(err);
          if (clientRes.statusCode !== 200) return done(new Error('Expected 200 status code'));
          if (!doesSessionExist) return done(new Error('req.session should exist.'));
          if (!isSessionAnObject) return done(new Error('req.session should be an object.'));
          if (!doesTestPropertyStillExist) return done(new Error('`req.session.something` should still exist for subsequent requests.'));
          return done();
        });
      });
    });

  });

  after(function (done) {
    done();
  });

});