text:
<?php
namespace frontend\controllers;

use common\models\Category;
use common\models\LegalDocuments;
use common\models\Video;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use common\models\Article;
use common\models\Announce;
use common\models\Menu;
use yii\web\NotFoundHttpException;
use sadovojav\gallery\models\GalleryFile;
use sadovojav\gallery\models\Gallery;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public $layout = "main2.php";

    public function actionMainLayout()
    {
        $this->layout = "main2.php";
        return $this->render('index');
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {

        $ann = Announce::find()->all();

        foreach ($ann as $announce) {
            $arr = [];
            $article = Article::findOne(['id' => $announce->article_id]);
            $arr['img'] = strip_tags($article->img);
            $arr['title'] = $article->title;
            $arr['slug'] = $article->slug;
            $this->view->params['ann_articles'][] = $arr;
        }

        $tar = Article::find()->where(['category_id' => 4, 'isFavorite' => 1, 'isActive' => 1])->orderBy('created_at DESC')->all();
        $kiev = Article::find()->where(['category_id' => 6, 'isFavorite' => 1, 'isActive' => 1])->orderBy('created_at DESC')->all();

        return $this->render('index', ['tar' => $tar, 'kiev' => $kiev]);
    }

    public function actionArticle($slug)
    {
        $this->layout = "article_layout.php";

        if (($model = Article::findOne(['slug' => $slug])) !== null) {
            return $this->render('article', ['model' => $model]);
        } else {
//            echo 'The requested page wasn\'t found';
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSearch()
    {
        $this->layout = "article_layout.php";

        $search = \Yii::$app->request->getQueryParam('srch-term');

        if (($query = Article::find()->orWhere(['like', 'title', $search])->orderBy('created_at DESC')) !== null) {
            $countQuery = clone $query;
            $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => 9]);
            $models = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->all();

            return $this->render('search', ['models' => $models, 'pages' => $pages]);
        } else {
//            echo 'The requested page wasn\'t found';
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionArticles($id)
    {
        $this->layout = "article_layout.php";

        if (($query = Article::find()->where(['category_id' => $id])->orderBy('created_at DESC')) !== null) {
            $countQuery = clone $query;
            $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => 9]);
            $models = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->all();

            return $this->render('articles', ['models' => $models, 'pages' => $pages]);
        } else {
            echo 'The requested page wasn\'t found';
        }
    }

    public function actionDocuments()
    {
        $this->layout = "article_layout.php";
        $result = '';
        $matches = [];

        if (Yii::$app->request->isPost) {
            if (isset($_POST['title']) && isset($_POST['type']) && isset($_POST['year']) && isset($_POST['month'])) {
                $model = $this->searchDocuments($_POST['type'], $_POST['year'], $_POST['month']);
                foreach ($model as $docum) {
                    $result .= $docum->title;
                }
                preg_match_all('/.*' . $_POST['title'] . '.*<\/a>/', $result, $matches);
                $session = Yii::$app->session;
                $session->set('title', $_POST['title']);
                $session->set('type', $_POST['type']);
                $session->set('year', $_POST['year']);
                $session->set('month', $_POST['month']);
                $session->set('documents', $matches);

            } else {
                $result = "Введіть текст для пошуку, а також виберіть критерії пошуку";
            }
        } elseif (null !== Yii::$app->session->get('documents') ) {

            $matches = Yii::$app->session->get('documents');

        } else {
            $model = $this->searchDocuments('Всі документи', 0, 0);
            foreach ($model as $docum) {
                $result .= $docum->title;
            }
            preg_match_all('/.*.*<\/a>/', $result, $matches);
        }

        $pages = new Pagination();

        if (isset($matches[0])) {

            $pages->totalCount = count($matches[0]);
            $pages->pageSize = 20;
            $pages->pageSizeParam = false;
            $model = array_slice($matches[0], $pages->offset, $pages->pageSize);
            $result = '';
            $i = 1+$pages->getPage()*$pages->pageSize;
            foreach ($model as $match) {
                $result .= '' . $i++. ')   ' . $match . '

';
            }
        }

        return $this->render('documents', [
            'model' => $result,
            'pages' => $pages,
        ]);
    }

    private function searchDocuments($type, $year, $month)
    {

        $query = LegalDocuments::find();

        if ($year != '0') {
            $query->andFilterWhere(['like', 'year', $year]);
        }

        if ($month != '0') {
            $query->andFilterWhere(['like', 'month', $month]);
        }

        if ($type != 'Всі документи') {
            $query->andFilterWhere(['like', 'type', $type]);
        }

        return $query->all();
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        $this->layout = 'main';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect('/site/index');
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->actionIndex();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->renderAjax('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    public function actionGallery($id)
    {
        $this->layout = "article_layout.php";

        $model = GalleryFile::find()->where(['galleryId' => $id])->orderBy('position')->asArray()->all();
        $title = Gallery::find()->where(['id' => $id])->one();

        return $this->render('gallery', ['model' => $model, 'title' => $title->name]);
    }

    public function actionGalleries()
    {
        $this->layout = "article_layout.php";

        $model = Gallery::find()->where(['status' => 1])->all();
        return $this->render('galleries', ['model' => $model, 'title' => 'Фотогалерея']);
    }

    public function actionVideo()
    {
        $this->layout = "article_layout.php";
        $model = Video::find()->all();
        return $this->render('video', ['model' => $model]);
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $this->layout = 'main';
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */

    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>いいね! カウンター</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

	<link href='//fonts.googleapis.com/css?family=Nixie+One' rel='stylesheet' type='text/css'>
	<link href="/style.css" rel="stylesheet" type="text/css">

みんなのいいね!

0

Myいいね!

0

		<button id="button_like" class="like_button_face" disabled>
			いいね!

		</button>

redpajama_set_name: RedPajamaGithub


text:
import os

import sys

from zeus.config import ConfigManager
from zeus.common import FabricManager
from zeus.common import PasswordManager
from zeus.configmanagement import ConfigEditor
from zeus.ubuntu import RepoManager
from zeus.services import ServiceControl

from fabric.api import parallel, roles, run, env

metadata = ConfigManager(os.environ["CONFIGFILE"])

passwords = PasswordManager(os.environ["PASSWORDCACHE"]).passwords

FabricManager.setup(metadata.roles_ports)

#
# http://docs.openstack.org/mitaka/install-guide-ubuntu/nova-controller-install.html
#
@parallel
@roles('openstack_controller')
def nova_controller():
    run("""
NOVA_PASS="%s"
NOVA_IP="%s"

. admin-openrc

openstack user list | grep nova || openstack user create --domain default --password "${NOVA_PASS}" nova
openstack user list | grep nova && openstack user set --password "${NOVA_PASS}" nova
openstack role add --project service --user nova admin

openstack service list | grep nova || openstack service create --name nova --description "OpenStack Compute" compute

openstack endpoint list | grep compute | grep public   || openstack endpoint create --region RegionOne compute public http://$NOVA_IP:8774/v2.1/%%\(tenant_id\)s
openstack endpoint list | grep compute | grep internal || openstack endpoint create --region RegionOne compute internal http://$NOVA_IP:8774/v2.1/%%\(tenant_id\)s
openstack endpoint list | grep compute | grep admin    || openstack endpoint create --region RegionOne compute admin http://$NOVA_IP:8774/v2.1/%%\(tenant_id\)s

""" % (
        passwords["NOVA_PASS"],
        metadata.servers[metadata.roles['openstack_controller'][0]]['ip']))

    RepoManager.install("nova-api")
    RepoManager.install("nova-conductor")
    RepoManager.install("nova-consoleauth")
    RepoManager.install("nova-novncproxy")
    RepoManager.install("nova-scheduler")

    keystone_server = metadata.roles['openstack_keystone'][0]
    keystone_ip = metadata.servers[keystone_server]['ip']

    controller = env.host_string.split(":")[0]
    controller_ip = metadata.servers[controller]['ip']

    mysql_server = metadata.roles['openstack_mysql'][0]
    mysql_ip = metadata.servers[mysql_server]['ip']

    rabbit_server = metadata.roles['openstack_rabbitmq'][0]
    rabbit_ip = metadata.servers[rabbit_server]['ip']

    glance_server = metadata.roles['openstack_glance'][0]
    glance_ip = metadata.servers[glance_server]['ip']

    neutron_server = metadata.roles['openstack_neutron'][0]
    neutron_ip = metadata.servers[neutron_server]['ip']

    my_ip = metadata.servers[controller]['ip']

    keystone_configs = {
        'auth_uri': 'http://%s:5000' % keystone_ip,
        'auth_url': 'http://%s:35357' % keystone_ip,
        'memcached_servers': '%s:11211' % controller_ip,
        'auth_type': 'password',
        'project_domain_name': 'default',
        'user_domain_name': 'default',
        'project_name': 'service',
        'username': 'nova',
        'password': passwords["NOVA_PASS"]}

    config_file = '/etc/nova/nova.conf'

    ConfigEditor.setKey(
        config_file,
        "database",
        "connection",
        "mysql+pymysql://nova:%s@%s/nova" % (
            passwords["NOVA_DBPASS"],
            mysql_ip))

    ConfigEditor.setKey(
        config_file,
        "api_database",
        "connection",
        "mysql+pymysql://nova_api:%s@%s/nova_api" % (
            passwords["NOVA_API_DBPASS"],
            mysql_ip))

    for key in keystone_configs:
        ConfigEditor.setKey(
            config_file,
            "keystone_authtoken",
            key,
            keystone_configs[key])

    neutron_configs = {
        'url': 'http://%s:9696' % neutron_ip,
        'auth_url': 'http://%s:35357' % keystone_ip,
        'auth_type': 'password',
        'project_domain_name': 'default',
        'user_domain_name': 'default',
        'region_name': 'RegionOne',
        'project_name': 'service',
        'username': 'neutron',
        'password': passwords["NEUTRON_PASS"],
        'service_metadata_proxy': 'True',
        'metadata_proxy_shared_secret': passwords["NEUTRON_METADATA_SHARED_SECRET"]}

    for key in neutron_configs:
        ConfigEditor.setKey(
            config_file,
            "neutron",
            key,
            neutron_configs[key])

    ConfigEditor.setKey(
        config_file,
        "DEFAULT",
        "enabled_apis",
        "osapi_compute,metadata")

    ConfigEditor.setKey(
        config_file,
        "DEFAULT",
        "auth_strategy",
        "keystone")

    ConfigEditor.setKey(
        config_file,
        "DEFAULT",
        "my_ip",
        my_ip)

    ConfigEditor.setKey(
        config_file,
        "DEFAULT",
        "use_neutron",
        "True")

    ConfigEditor.setKey(
        config_file,
        "DEFAULT",
        "firewall_driver",
        "nova.virt.firewall.NoopFirewallDriver")

    ConfigEditor.setKey(
        config_file,
        "vnc",
        "vncserver_listen",
        my_ip)

    ConfigEditor.setKey(
        config_file,
        "vnc",
        "vncserver_proxyclient_address",
        my_ip)

    ConfigEditor.setKey(
        config_file,
        "glance",
        "api_servers",
        "http://%s:9292" % glance_ip)

    ConfigEditor.setKey(
        config_file,
        "oslo_concurrency",
        "lock_path",
        "/var/lib/nova/tmp")

    ConfigEditor.setKey(
        config_file,
        "DEFAULT",
        "rpc_backend",
        "rabbit")

    ConfigEditor.setKey(
        config_file,
        "oslo_messaging_rabbit",
        "rabbit_host",
        rabbit_ip)

    ConfigEditor.setKey(
        config_file,
        "oslo_messaging_rabbit",
        "rabbit_userid",
        "openstack")

    ConfigEditor.setKey(
        config_file,
        "oslo_messaging_rabbit",
        "rabbit_password",
        passwords["RABBIT_PASS"])

    run("""
sed -i 's,logdir,log-dir,g;' /etc/nova/nova.conf

su -s /bin/sh -c "nova-manage api_db sync" nova
su -s /bin/sh -c "nova-manage db sync" nova
""")

    for service in ["api", "consoleauth", "scheduler", "conductor", "novncproxy"]:
        xservice = "nova-{}".format(service)
        ServiceControl.relaunch(xservice)
        ServiceControl.check(xservice)


text:
import { Pass } from './pass.js';

//// SHADER PASS

var ShaderPass = function(shader, textureID) {

  Pass.call(this);

  this.textureID = (textureID !== undefined) ? textureID : "tDiffuse";

  if (shader instanceof THREE.ShaderMaterial) {
    this.uniforms = shader.uniforms;
    this.material = shader;
  } else if (shader) {
    this.uniforms = THREE.UniformsUtils.clone(shader.uniforms);
    this.material = new THREE.ShaderMaterial({
      defines: shader.defines || {},
      uniforms: this.uniforms,
      vertexShader: shader.vertexShader,
      fragmentShader: shader.fragmentShader,
      depthTest: false,
      depthWrite: false
    });
  }

  this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  this.scene = new THREE.Scene();
  this.quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(2,2), null);
  this.scene.add(this.quad);
};

ShaderPass.prototype = Object.assign(Object.create(Pass.prototype), {

  constructor: ShaderPass,

  render: function(renderer, writeBuffer, readBuffer, delta, maskActive) {

    if (this.uniforms[ this.textureID ]) {
      this.uniforms[ this.textureID ].value = readBuffer.texture;
    }

    this.quad.material = this.material;

    if (this.colorMask) {
      renderer.getContext().colorMask(this.colorMask[0], this.colorMask[1], this.colorMask[2], this.colorMask[3]);
    }

    if (this.renderToScreen) {
      renderer.render(this.scene, this.camera);
    } else {
      var oldRenderTarget = renderer.getRenderTarget();
      renderer.setRenderTarget(writeBuffer);
      if (this.clear) renderer.clear();
      renderer.render(this.scene, this.camera);
      renderer.setRenderTarget(oldRenderTarget);
    }

    if (this.colorMask) {
      renderer.getContext().colorMask(true, true, true, true);
    }
  }
});

export { ShaderPass };


text:
PlastiCSS
=========

SASS Framework


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>illacceptanything: IdentityModels.cs Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

illacceptanything
    2.0

Main Page

Namespaces

Data Structures

Files

File List

Globals

IdentityModels.cs

Go to the documentation of this file.

    1 using Microsoft.AspNet.Identity.EntityFramework;

    2

    3 namespace Sharepoint2007.Web.Models

    4 {

    5     // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.

    6     public class ApplicationUser : IdentityUser

    7     {

    8     }

    9

   10     public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

   11     {

   12         public ApplicationDbContext()

   13             : base("DefaultConnection")

   14         {

   15         }

   16     }

   17 }

Sharepoint2007.Web.Models.ApplicationUser

Definition: IdentityModels.cs:6

Sharepoint2007.Web.Models.ApplicationDbContext

Definition: IdentityModels.cs:10

Sharepoint2007

Sharepoint2007.Web.Models.ApplicationDbContext.ApplicationDbContext

ApplicationDbContext()

Definition: IdentityModels.cs:12

Sharepoint2007

Sharepoint2007.Web

Models

IdentityModels.cs

Generated on Fri Apr 10 2015 15:21:50 for illacceptanything by

     1.8.8


text:
Want to contribute? Great! First, read this page.

### Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual)
(CLA), which you can do online.
You (or your employer) retain the copyright to your contribution, this simply
gives us permission to use and redistribute your contributions as part of the
project. Head over to https://cla.developers.google.com/ to see your current
agreements on file or to sign a new one.

You generally only need to submit a CLA once, so if you've already submitted
one (even if it was for a different project), you probably don't need to do it
again.

Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.

### Code reviews

All submissions, including submissions by project members, require a code
review. We use GitHub pull requests for this purpose.

### J2CL code priorities

- Transpiler runs fast (productivity)
- Output is understandable (ease integration and debugging)
- Output optimizes well with Closure compiler (performance)
- Output executes fast in the Browser (performance)

### Shell aliasing and running j2 script

- Alias J2CL's dev script (dev/j2.py). **Do this before anything else**.

```shell

    # alias j2 for ease of use
    alias j2='python3 dev/j2.py'
```

- Running `j2` in the shell will show the available commands for J2CL
development.

**Note:** `j2` script is not ported for open-source development yet. However
you can still test your contributions by running particular integration tests
using `bazel test <target>`. You can also run `./build_test.sh CI` script to
test againt full test suite available in the open-source repo.

### Working with the codebase

- When iterating quickly it's best to run `j2 test`  and `j2 gen` for individual
  targets.
- When starting a review always first run `j2 presubmit`, and of course if you
  see anything unexpected then correct it before beginning the review.
- It's important that you run both `j2 presubmit` after
  syncing. If you don't then the build.log's you've previously created might not
  reflect the current state of the repo. Also if you don't then the baseline
  against which size changes are compared in the size_report.txt won't be the
  right baseline.


text:
int serverport = 8080;
char *videofile = "video.webm";
char *stylefile = "style.css";
char *scriptfile = "script.js";
char *indexfile = "index.html";

#define ERR(...) \
        fprintf(stderr, __VA_ARGS__);

#define LOG(...) \
        printf(__VA_ARGS__);

static void doexit(evutil_socket_t sig, short events, void *ptr) {
	LOG("\nGot Signal!\n");

	struct event_base *base = (struct event_base *) ptr;

        event_base_loopexit(base, NULL);
}

void sendchunkedfile(char *filename, char *type, struct evhttp_request *req, void *arg) {
        int fd = -1, chunked = 1;
        struct evbuffer *buffer = NULL;
        struct stat st;
        struct evhttp_connection *client = NULL;
        char *addr = NULL;
        int port;

        if ((client = evhttp_request_get_connection(req)) != NULL) {
                evhttp_connection_get_peer(client, &addr,(u_short *) &port);

                LOG("%s:%d -> /%s\n", addr, port, filename);
        }

        struct evkeyvalq *headers = evhttp_request_get_output_headers(req);

        if (evhttp_add_header(headers, "Content-Type", type) < 0) {
                ERR("Unable to set header: Content-Type\n");
                return;
        }

	buffer = evbuffer_new();

        if (stat(filename, &st) != -1) {
		if ((fd = open(filename, O_RDONLY)) != -1) {
			if (st.st_size > 0) {
				if (evbuffer_add_file(buffer, fd, 0, st.st_size) < 0) {
					ERR("Unable to read file! (%s)\n", filename);
				}
			} else {
				// File is empty
				close(fd);
				chunked = 0;
			}
		} else {
			ERR("Unable to open file! (%s: %s)\n", filename, strerror(errno));
			chunked = 0;
		}
	} else {
                ERR("Unable to open file! (%s)\n", filename);
		chunked = 0;
        }

	if (chunked > 0) {
		evhttp_send_reply_start(req, HTTP_OK, "OK");
		evhttp_send_reply_chunk(req, buffer);
		evhttp_send_reply_end(req);
	}

	else {
		evhttp_send_reply(req, HTTP_OK, "OK", 0);
	}

        evbuffer_free(buffer);
}

void handleResponseVideo(struct evhttp_request *req, void *arg) {
	sendchunkedfile(videofile, "video/webm", req, arg);
}

void handleResponseStyle(struct evhttp_request *req, void *arg) {
        sendchunkedfile(stylefile, "text/css", req, arg);
}

void handleResponseScript(struct evhttp_request *req, void *arg) {
        sendchunkedfile(scriptfile, "application/javascript", req, arg);
}

void handleResponse(struct evhttp_request *req, void *arg) {
	sendchunkedfile(indexfile, "text/html", req, arg);
}

int main(int argc, char **argv) {
	int c;
	struct event_base *base = NULL;
	struct event *sig = NULL;
	struct evhttp *http = NULL;

	while ((c = getopt(argc, argv, "iscvp:")) != -1) {
		switch (c) {
			case 'i':
				indexfile = argv[optind];
				break;
			case 's':
				stylefile = argv[optind];
				break;
			case 'c':
				scriptfile = argv[optind];
				break;
			case 'v':
				videofile = argv[optind];
				break;
			case 'p':
				serverport = atoi(optarg);
				break;
			default:
				LOG("Usage: %s [-i ./index.html] [-s ./style.css] [-c ./script.js] [-v ./video.webm] [-p 8080]\n", argv[0]);
				return 1;
		}
	}

        signal(SIGPIPE, SIG_IGN);

	base = event_base_new();
	sig = evsignal_new(base, SIGINT, doexit, base);

	if (event_add(sig, NULL) < 0) {
		ERR("Unable to set signal event!\n");
		return 1;
	}

	http = evhttp_new(base);

	evhttp_bind_socket(http, "0.0.0.0", serverport);

        if (evhttp_set_cb(http, "/", handleResponse, base) < 0) {
                ERR("Unable to set request callback!\n");
                return 1;
        }

        if (evhttp_set_cb(http, "/style.css", handleResponseStyle, base) < 0) {
                ERR("Unable to set request callback!\n");
                return 1;
        }

        if (evhttp_set_cb(http, "/script.js", handleResponseScript, base) < 0) {
                ERR("Unable to set request callback!\n");
                return 1;
        }

	if (evhttp_set_cb(http, "/video.webm", handleResponseVideo, base) < 0) {
		ERR("Unable to set request callback!\n");
		return 1;
	}

	LOG("Listening 0.0.0.0:%d\n", serverport);

        event_base_dispatch(base);

        event_free(sig);
        evhttp_free(http);
        event_base_free(base);

        return 0;
}


text:
package batch.sql;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.FIELD })
public @interface Inverse {
	String value();
}


text:
define([
  'attribution',
  'helpers'
], function(attribution, helpers) {
  /**
   * @ngdoc overview
   * @name name
   * @description
   * Name
   */

  var maybe = helpers.maybe; // shorthand

  var exports = {};

  /**********************************/
  /**
   * @ngdoc function
   * @name name.types:constructor.Name
   * @description
   *
   * Name
   *
   * @param {Object|String=} data either a fullText string or an object with optional attributes
   * {type, givenName, surname, prefix, suffix, fullText, preferred, changeMessage}
   **********************************/

  var Name = exports.Name = function(data) {
    if (data) {
      if (helpers.isString(data)) {
        //noinspection JSUnresolvedFunction
        this.$setFullText(data);
      }
      else {
        if (data.type) {
          //noinspection JSUnresolvedFunction
          this.$setType(data.type);
        }
        if (data.givenName) {
          //noinspection JSUnresolvedFunction
          this.$setGivenName(data.givenName);
        }
        if (data.surname) {
          //noinspection JSUnresolvedFunction
          this.$setSurname(data.surname);
        }
        if (data.prefix) {
          //noinspection JSUnresolvedFunction
          this.$setPrefix(data.prefix);
        }
        if (data.suffix) {
          //noinspection JSUnresolvedFunction
          this.$setSuffix(data.suffix);
        }
        if (data.fullText) {
          //noinspection JSUnresolvedFunction
          this.$setFullText(data.fullText);
        }
        //noinspection JSUnresolvedFunction
        this.$setPreferred(!!data.preferred);
        if (data.changeMessage) {
          //noinspection JSUnresolvedFunction
          this.$setChangeMessage(data.changeMessage);
        }
      }
    }
  };

  // return the i'th name form; add it if it doesn't exist
  function ensureNameForm(name, i) {
    var pos = i || 0; // just to be clear
    if (!helpers.isArray(name.nameForms)) {
      name.nameForms = [];
    }
    while (pos >= name.nameForms.length) {
      name.nameForms.push({});
    }
    return name.nameForms[pos];
  }

  exports.Name.prototype = {
    constructor: Name,
    /**
     * @ngdoc property
     * @name name.types:constructor.Name#id
     * @propertyOf name.types:constructor.Name
     * @return {String} Id of the name
     */

    /**
     * @ngdoc property
     * @name name.types:constructor.Name#type
     * @propertyOf name.types:constructor.Name
     * @return {String} http://gedcomx.org/BirthName, etc.
     */

    /**
     * @ngdoc property
     * @name name.types:constructor.Name#preferred
     * @propertyOf name.types:constructor.Name
     * @return {Boolean} true if this name is preferred
     */

    /**
     * @ngdoc property
     * @name name.types:constructor.Name#attribution
     * @propertyOf name.types:constructor.Name
     * @returns {Attribution} {@link attribution.types:constructor.Attribution Attribution} object
     */

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$getNameFormsCount
     * @methodOf name.types:constructor.Name
     * @function
     * @return {Number} get the number of name forms
     */
    $getNameFormsCount: function() { return this.nameForms ? this.nameForms.length : 0; },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$getFullText
     * @methodOf name.types:constructor.Name
     * @function
     * @param {Number=} i name form to read; defaults to 0
     * @return {String} get the full text of the `i`'th name form
     */
    $getFullText: function(i) { return maybe(maybe(this.nameForms)[i || 0]).fullText; },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$getNamePart
     * @methodOf name.types:constructor.Name
     * @function
     * @description you can call $getGivenName, $getSurname, $getPrefix, or $getSuffix instead of this function
     * @param {String} type http://gedcomx.org/Given or http://gedcomx.org/Surname
     * @param {Number=} i name form to read; defaults to 0
     * @return {String} get the specified part of the `i`'th name form
     */
    $getNamePart: function(type, i) {
      return maybe(helpers.find(maybe(maybe(this.nameForms)[i || 0]).parts, {type: type})).value;
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$getGivenName
     * @methodOf name.types:constructor.Name
     * @function
     * @param {Number=} i name form to read; defaults to 0
     * @return {String} get the given part of the `i`'th name form
     */
    $getGivenName: function(i) {
      return this.$getNamePart('http://gedcomx.org/Given', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$getSurname
     * @methodOf name.types:constructor.Name
     * @function
     * @param {Number=} i name form to read; defaults to 0
     * @return {String} get the surname part of the `i`'th name form
     */
    $getSurname: function(i) {
      return this.$getNamePart('http://gedcomx.org/Surname', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$getPrefix
     * @methodOf name.types:constructor.Name
     * @function
     * @param {Number=} i name form to read; defaults to 0
     * @return {String} get the prefix part of the `i`'th name form
     */
    $getPrefix: function(i) {
      return this.$getNamePart('http://gedcomx.org/Prefix', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$getSuffix
     * @methodOf name.types:constructor.Name
     * @function
     * @param {Number=} i name form to read; defaults to 0
     * @return {String} get the suffix part of the `i`'th name form
     */
    $getSuffix: function(i) {
      return this.$getNamePart('http://gedcomx.org/Suffix', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setType
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value
     * @param {String} type e.g., http://gedcomx.org/BirthName
     * @return {Name} this name
     */
    $setType: function(type) {
      this.$changed = true;
      this.type = type;
      //noinspection JSValidateTypes
      return this;
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setPreferred
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value
     *
     * __NOTE__: the preferred name flag can be set only when the person is initially created; after that it is read-only
     * @param {boolean} isPreferred true if preferred
     * @return {Name} this name
     */
    $setPreferred: function(isPreferred) {
      this.$changed = true;
      this.preferred = isPreferred;
      //noinspection JSValidateTypes
      return this;
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setFullText
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value
     * @param {String} fullText value
     * @param {Number=} i name form to set; defaults to 0
     * @return {Name} this name
     */
    $setFullText: function(fullText, i) {
      this.$changed = true;
      var nameForm = ensureNameForm(this, i);
      nameForm.fullText = fullText;
      //noinspection JSValidateTypes
      return this;
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setNamePart
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value;
     * you can call $setGivenName, $setSurname, $setPrefix, and $setSuffix instead of this function
     * @param {String} name value
     * @param {String} type http://gedcomx.org/Given or http://gedcomx.org/Surname
     * @param {Number=} i name form to set; defaults to 0
     * @return {Name} this name
     */
    $setNamePart: function(name, type, i) {
      this.$changed = true;
      var nameForm = ensureNameForm(this, i);
      if (!helpers.isArray(nameForm.parts)) {
        nameForm.parts = [];
      }
      var part = helpers.find(nameForm.parts, {type: type});
      if (!part) {
        part = {type: type};
        nameForm.parts.push(part);
      }
      part.value = name;
      //noinspection JSValidateTypes
      return this;
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setGivenName
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value
     * @param {String} givenName value
     * @param {Number=} i name form to set; defaults to 0
     * @return {Name} this name
     */
    $setGivenName: function(givenName, i) {
      return this.$setNamePart(givenName, 'http://gedcomx.org/Given', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setSurname
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value
     * @param {String} surname value
     * @param {Number=} i name form to set; defaults to 0
     * @return {Name} this name
     */
    $setSurname: function(surname, i) {
      return this.$setNamePart(surname, 'http://gedcomx.org/Surname', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setPrefix
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value
     * @param {String} prefix value
     * @param {Number=} i name form to set; defaults to 0
     * @return {Name} this name
     */
    $setPrefix: function(prefix, i) {
      return this.$setNamePart(prefix, 'http://gedcomx.org/Prefix', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setSuffix
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the $changed flag as well as the value
     * @param {String} suffix value
     * @param {Number=} i name form to set; defaults to 0
     * @return {Name} this name
     */
    $setSuffix: function(suffix, i) {
      return this.$setNamePart(suffix, 'http://gedcomx.org/Suffix', i);
    },

    /**
     * @ngdoc function
     * @name name.types:constructor.Name#$setChangeMessage
     * @methodOf name.types:constructor.Name
     * @function
     * @description sets the changeMessage used to update the name
     * @param {String} changeMessage change message
     * @return {Name} this name
     */
    $setChangeMessage: function(changeMessage) {
      this.attribution = new attribution.Attribution(changeMessage);
      //noinspection JSValidateTypes
      return this;
    }
  };

  return exports;
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

/**
 * Package containing the implementations for AzureDatabricksManagementClient. The Microsoft Azure management APIs allow
 * end users to operate on Azure Databricks Workspace resources.
 */
package com.azure.resourcemanager.databricks.implementation;


text:
package com.amazonaws.services.xray.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.xray.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AvailabilityZoneDetailMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AvailabilityZoneDetailMarshaller {

    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();

    private static final AvailabilityZoneDetailMarshaller instance = new AvailabilityZoneDetailMarshaller();

    public static AvailabilityZoneDetailMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AvailabilityZoneDetail availabilityZoneDetail, ProtocolMarshaller protocolMarshaller) {

        if (availabilityZoneDetail == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(availabilityZoneDetail.getName(), NAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
class GURL;
class ExtensionHost;
class ExtensionDevToolsManager;
class Profile;

namespace content {
class RenderProcessHost;
}

namespace extensions {
class Extension;
}

struct ExtensionEvent;

using extensions::EventFilteringInfo;
using extensions::EventListener;
using extensions::EventListenerMap;

class ExtensionEventRouter : public content::NotificationObserver,
                             public extensions::EventListenerMap::Delegate {
 public:
  // These constants convey the state of our knowledge of whether we're in
  // a user-caused gesture as part of DispatchEvent.
  enum UserGestureState {
    USER_GESTURE_UNKNOWN = 0,
    USER_GESTURE_ENABLED = 1,
    USER_GESTURE_NOT_ENABLED = 2,
  };

  // Sends an event via ipc_sender to the given extension. Can be called on
  // any thread.
  static void DispatchEvent(IPC::Sender* ipc_sender,
                            const std::string& extension_id,
                            const std::string& event_name,
                            const base::Value& event_args,
                            const GURL& event_url,
                            UserGestureState user_gesture,
                            const extensions::EventFilteringInfo& info);

  // This invocation is deprecated. All future consumers of this API should be
  // sending Values as event arguments, using the above version.
  static void DispatchEvent(IPC::Sender* ipc_sender,
                            const std::string& extension_id,
                            const std::string& event_name,
                            const std::string& event_args,
                            const GURL& event_url,
                            UserGestureState user_gesture,
                            const extensions::EventFilteringInfo& info);

  explicit ExtensionEventRouter(Profile* profile);
  virtual ~ExtensionEventRouter();

  // Add or remove the process/extension pair as a listener for |event_name|.
  // Note that multiple extensions can share a process due to process
  // collapsing. Also, a single extension can have 2 processes if it is a split
  // mode extension.
  void AddEventListener(const std::string& event_name,
                        content::RenderProcessHost* process,
                        const std::string& extension_id);
  void RemoveEventListener(const std::string& event_name,
                           content::RenderProcessHost* process,
                           const std::string& extension_id);

  // Add or remove the extension as having a lazy background page that listens
  // to the event. The difference from the above methods is that these will be
  // remembered even after the process goes away. We use this list to decide
  // which extension pages to load when dispatching an event.
  void AddLazyEventListener(const std::string& event_name,
                            const std::string& extension_id);
  void RemoveLazyEventListener(const std::string& event_name,
                               const std::string& extension_id);

  // If |add_lazy_listener| is true also add the lazy version of this listener.
  void AddFilteredEventListener(const std::string& event_name,
                                content::RenderProcessHost* process,
                                const std::string& extension_id,
                                const base::DictionaryValue& filter,
                                bool add_lazy_listener);

  // If |remove_lazy_listener| is true also remove the lazy version of this
  // listener.
  void RemoveFilteredEventListener(const std::string& event_name,
                                   content::RenderProcessHost* process,
                                   const std::string& extension_id,
                                   const base::DictionaryValue& filter,
                                   bool remove_lazy_listener);

  // Returns true if there is at least one listener for the given event.
  bool HasEventListener(const std::string& event_name);

  // Returns true if the extension is listening to the given event.
  bool ExtensionHasEventListener(const std::string& extension_id,
                                 const std::string& event_name);

  // Send an event to every registered extension renderer. If
  // |restrict_to_profile| is non-NULL, then the event will not be sent to other
  // profiles unless the extension has permission (e.g. incognito tab update ->
  // normal profile only works if extension is allowed incognito access). If
  // |event_url| is not empty, the event is only sent to extension with host
  // permissions for this url.
  void DispatchEventToRenderers(
      const std::string& event_name,
      const std::string& event_args,
      Profile* restrict_to_profile,
      const GURL& event_url,
      extensions::EventFilteringInfo info);

  // As above, but defaults |info| to EventFilteringInfo().
  void DispatchEventToRenderers(
      const std::string& event_name,
      const std::string& event_args,
      Profile* restrict_to_profile,
      const GURL& event_url);

  // Same as above, except only send the event to the given extension.
  virtual void DispatchEventToExtension(
      const std::string& extension_id,
      const std::string& event_name,
      const base::Value& event_args,
      Profile* restrict_to_profile,
      const GURL& event_url);

  // This invocation is deprecated. The above variant which uses a Value for
  // event_args is to be used instead.
  virtual void DispatchEventToExtension(
      const std::string& extension_id,
      const std::string& event_name,
      const std::string& event_args,
      Profile* restrict_to_profile,
      const GURL& event_url);

  // Dispatch an event to particular extension. Also include an
  // explicit user gesture indicator.
  virtual void DispatchEventToExtension(
      const std::string& extension_id,
      const std::string& event_name,
      const std::string& event_args,
      Profile* restrict_to_profile,
      const GURL& event_url,
      UserGestureState user_gesture);

  // Send different versions of an event to extensions in different profiles.
  // This is used in the case of sending one event to extensions that have
  // incognito access, and another event to extensions that don't (here),
  // in order to avoid sending 2 events to "spanning" extensions.
  // If |cross_incognito_profile| is non-NULL and different from
  // restrict_to_profile, send the event with cross_incognito_args to the
  // extensions in that profile that can't cross incognito.
  void DispatchEventsToRenderersAcrossIncognito(
      const std::string& event_name,
      const std::string& event_args,
      Profile* restrict_to_profile,
      const std::string& cross_incognito_args,
      const GURL& event_url);

  // Record the Event Ack from the renderer. (One less event in-flight.)
  void OnEventAck(Profile* profile, const std::string& extension_id);

 private:
  // The extension and process that contains the event listener for a given
  // event.
  struct ListenerProcess;

  // A map between an event name and a set of extensions that are listening
  // to that event.
  typedef std::map<std::string, std::set<ListenerProcess> > ListenerMap;

  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  // Returns true if the given listener map contains a event listeners for
  // the given event. If |extension_id| is non-empty, we also check that that
  // extension is one of the listeners.
  bool HasEventListenerImpl(const ListenerMap& listeners,
                            const std::string& extension_id,
                            const std::string& event_name);

  // Shared by DispatchEvent*. If |restrict_to_extension_id| is empty, the
  // event is broadcast.
  // An event that just came off the pending list may not be delayed again.
  void DispatchEventImpl(const std::string& restrict_to_extension_id,
                         const linked_ptr<ExtensionEvent>& event);

  // Ensures that all lazy background pages that are interested in the given
  // event are loaded, and queues the event if the page is not ready yet.
  void DispatchLazyEvent(const std::string& extension_id,
                         const linked_ptr<ExtensionEvent>& event);

  // Dispatches the event to the specified extension running in |process|.
  void DispatchEventToProcess(const std::string& extension_id,
                              content::RenderProcessHost* process,
                              const linked_ptr<ExtensionEvent>& event);

  // Returns false when the event is scoped to a profile and the listening
  // extension does not have access to events from that profile. Also fills
  // |event_args| with the proper arguments to send, which may differ if
  // the event crosses the incognito boundary.
  bool CanDispatchEventToProfile(
      Profile* profile,
      const extensions::Extension* extension,
      const linked_ptr<ExtensionEvent>& event,
      const base::Value** event_args);

  // Possibly loads given extension's background page in preparation to
  // dispatch an event.
  void MaybeLoadLazyBackgroundPageToDispatchEvent(
      Profile* profile,
      const extensions::Extension* extension,
      const linked_ptr<ExtensionEvent>& event);

  // Track of the number of dispatched events that have not yet sent an
  // ACK from the renderer.
  void IncrementInFlightEvents(Profile* profile,
                               const extensions::Extension* extension);

  void DispatchPendingEvent(const linked_ptr<ExtensionEvent>& event,
                            ExtensionHost* host);

  // Implementation of extensions::EventListenerMap::Delegate.
  virtual void OnListenerAdded(const EventListener* listener) OVERRIDE;
  virtual void OnListenerRemoved(const EventListener* listener) OVERRIDE;

  Profile* profile_;

  content::NotificationRegistrar registrar_;

  scoped_refptr<ExtensionDevToolsManager> extension_devtools_manager_;

  EventListenerMap listeners_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionEventRouter);
};

struct ExtensionEvent {
  std::string event_name;
  scoped_ptr<Value> event_args;
  GURL event_url;
  Profile* restrict_to_profile;
  scoped_ptr<Value> cross_incognito_args;
  ExtensionEventRouter::UserGestureState user_gesture;
  extensions::EventFilteringInfo info;

  ExtensionEvent(const std::string& event_name,
                 const Value& event_args,
                 const GURL& event_url,
                 Profile* restrict_to_profile,
                 const Value& cross_incognito_args,
                 ExtensionEventRouter::UserGestureState user_gesture,
                 const extensions::EventFilteringInfo& info);

  // TODO(gdk): This variant should be retired once the callers are switched to
  // providing Values instead of just strings.
  ExtensionEvent(const std::string& event_name,
                 const std::string& event_args,
                 const GURL& event_url,
                 Profile* restrict_to_profile,
                 const std::string& cross_incognito_args,
                 ExtensionEventRouter::UserGestureState user_gesture,
                 const extensions::EventFilteringInfo& info);

  ExtensionEvent(const std::string& event_name,
                 const Value& event_args,
                 const GURL& event_url,
                 Profile* restrict_to_profile,
                 ExtensionEventRouter::UserGestureState user_gesture,
                 const extensions::EventFilteringInfo& info);

  ~ExtensionEvent();
};

#endif  // CHROME_BROWSER_EXTENSIONS_EXTENSION_EVENT_ROUTER_H_


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/******************************************************************************
 * This file is auto-generated from a template file by the GenerateTests.csx  *
 * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make    *
 * changes, please update the corresponding template and run according to the *
 * directions listed in the file.                                             *
 ******************************************************************************/

using System;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;

namespace JIT.HardwareIntrinsics.General
{
    public static partial class Program
    {
        private static void AsVectorByte()
        {
            var test = new VectorAs__AsVectorByte();

            // Validates basic functionality works
            test.RunBasicScenario();

            // Validates calling via reflection works
            test.RunReflectionScenario();

            if (!test.Succeeded)
            {
                throw new Exception("One or more scenarios did not complete as expected.");
            }
        }
    }

    public sealed unsafe class VectorAs__AsVectorByte
    {
        private static readonly int LargestVectorSize = 32;

        private static readonly int VectorElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte);

        private static readonly int NumericsElementCount = Unsafe.SizeOf<Vector<Byte>>() / sizeof(Byte);

        public bool Succeeded { get; set; } = true;

        public void RunBasicScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
            Vector256<Byte> value;

            value = Vector256.Create((byte)TestLibrary.Generator.GetByte());
            Vector<Byte> result = value.AsVector();
            ValidateResult(result, value);

            value = result.AsVector256();
            ValidateResult(value, result);
        }

        public void RunReflectionScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
            Vector256<Byte> value;

            value = Vector256.Create((byte)TestLibrary.Generator.GetByte());
            object Result = typeof(Vector256)
                                .GetMethod(nameof(Vector256.AsVector))
                                .MakeGenericMethod(typeof(Byte))
                                .Invoke(null, new object[] { value });
            ValidateResult((Vector<Byte>)(Result), value);

            value = (Vector256<Byte>)typeof(Vector256)
                                .GetMethods()
                                .Where((methodInfo) => {
                                    if (methodInfo.Name == nameof(Vector256.AsVector256))
                                    {
                                        var parameters = methodInfo.GetParameters();
                                        return (parameters.Length == 1) &&
                                               (parameters[0].ParameterType.IsGenericType) &&
                                               (parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(Vector<>));
                                    }
                                    return false;
                                })
                                .Single()
                                .MakeGenericMethod(typeof(Byte))
                                .Invoke(null, new object[] { Result });
            ValidateResult(value, (Vector<Byte>)(Result));
        }

        private void ValidateResult(Vector<Byte> result, Vector256<Byte> value, [CallerMemberName] string method = "")
        {
            Byte[] resultElements = new Byte[NumericsElementCount];
            Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result);

            Byte[] valueElements = new Byte[VectorElementCount];
            Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref valueElements[0]), value);

            ValidateResult(resultElements, valueElements, method);
        }

        private void ValidateResult(Vector256<Byte> result, Vector<Byte> value, [CallerMemberName] string method = "")
        {
            Byte[] resultElements = new Byte[VectorElementCount];
            Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref resultElements[0]), result);

            Byte[] valueElements = new Byte[NumericsElementCount];
            Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref valueElements[0]), value);

            ValidateResult(resultElements, valueElements, method);
        }

        private void ValidateResult(Byte[] resultElements, Byte[] valueElements, [CallerMemberName] string method = "")
        {
            bool succeeded = true;

            if (resultElements.Length <= valueElements.Length)
            {
                for (var i = 0; i < resultElements.Length; i++)
                {
                    if (resultElements[i] != valueElements[i])
                    {
                        succeeded = false;
                        break;
                    }
                }
            }
            else
            {
                for (var i = 0; i < valueElements.Length; i++)
                {
                    if (resultElements[i] != valueElements[i])
                    {
                        succeeded = false;
                        break;
                    }
                }

                for (var i = valueElements.Length; i < resultElements.Length; i++)
                {
                    if (resultElements[i] != default)
                    {
                        succeeded = false;
                        break;
                    }
                }
            }

            if (!succeeded)
            {
                TestLibrary.TestFramework.LogInformation($"Vector256<Byte>.AsVector: {method} failed:");
                TestLibrary.TestFramework.LogInformation($"   value: ({string.Join(", ", valueElements)})");
                TestLibrary.TestFramework.LogInformation($"  result: ({string.Join(", ", resultElements)})");
                TestLibrary.TestFramework.LogInformation(string.Empty);

                Succeeded = false;
            }
        }
    }
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { RestProvider } from '../providers/rest/rest';
import { FormProvider } from '../providers/form/form';
import { CarrinhoPage } from '../pages/carrinho/carrinho';

@NgModule({
  declarations: [
    MyApp,
    CarrinhoPage,
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    CarrinhoPage,
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    RestProvider,
    FormProvider,
    BarcodeScanner
  ]
})
export class AppModule {}


text:
<?php
namespace Zgh\FEBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Zgh\FEBundle\Transformer\PostTransformer;

class PostType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $option)
    {
        $builder
            ->add("content", "textarea", [
                "required" => false
            ])
            ->add("image_file", "file", array(
                    "required" => false,
                    "attr" => array(
                        "accept" => "image/*"
                    )
                ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
                "data_class" => 'Zgh\FEBundle\Entity\Post',
                "cascade_validation" => true,
            ));
    }

    public function getName()
    {
        return "post";
    }
}


text:
import { sortedIndexOf } from "./index";
export = sortedIndexOf;


text:
package com.github.pockethub.android.ui;

import android.app.Activity;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.StringRes;

import com.afollestad.materialdialogs.MaterialDialog;
import com.github.pockethub.android.ui.roboactivities.RoboSupportFragment;

/**
 * Base fragment capable of receiving dialog callbacks
 */
public abstract class DialogFragment extends RoboSupportFragment implements
        DialogResultListener {

    private MaterialDialog progressDialog;

    /**
     * Is this fragment usable from the UI-thread
     *
     * @return true if usable, false otherwise
     */
    protected boolean isUsable() {
        return getActivity() != null;
    }

    @Override
    public void onDialogResult(int requestCode, int resultCode, Bundle arguments) {
        // Intentionally left blank
    }

    /**
     * Get serializable extra from activity's intent
     *
     * @param name
     * @return extra
     */
    @SuppressWarnings("unchecked")
    protected <V extends Parcelable> V getParcelableExtra(final String name) {
        Activity activity = getActivity();
        if (activity != null) {
            return (V) activity.getIntent().getParcelableExtra(name);
        } else {
            return null;
        }
    }

    /**
     * Get string extra from activity's intent
     *
     * @param name
     * @return extra
     */
    protected String getStringExtra(final String name) {
        Activity activity = getActivity();
        if (activity != null) {
            return activity.getIntent().getStringExtra(name);
        } else {
            return null;
        }
    }

    /**
     * Dismiss and clear progress dialog field
     */
    protected void dismissProgress() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    /**
     * Show indeterminate progress dialog with given message
     *
     * @param message
     */
    protected void showProgressIndeterminate(final CharSequence message) {
        dismissProgress();
        progressDialog = new MaterialDialog.Builder(getActivity())
                .content(message)
                .progress(true, 0)
                .build();
        progressDialog.show();
    }

    /**
     * Show indeterminate progress dialog with given message
     *
     * @param resId
     */
    protected void showProgressIndeterminate(@StringRes final int resId) {
        showProgressIndeterminate(getString(resId));
    }
}


text:
package org.apache.hadoop.hive.druid.serde;

import com.google.common.collect.Iterators;
import com.metamx.common.lifecycle.Lifecycle;
import com.metamx.http.client.HttpClient;
import com.metamx.http.client.HttpClientConfig;
import com.metamx.http.client.HttpClientInit;
import io.druid.query.BaseQuery;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.druid.DruidStorageHandlerUtils;
import org.apache.hadoop.hive.druid.io.HiveDruidSplit;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.joda.time.Period;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * Base record reader for given a Druid query. This class contains the logic to
 * send the query to the broker and retrieve the results. The transformation to
 * emit records needs to be done by the classes that extend the reader.
 *
 * The key for each record will be a NullWritable, while the value will be a
 * DruidWritable containing the timestamp as well as all values resulting from
 * the query.
 */
public abstract class DruidQueryRecordReader<T extends BaseQuery<R>, R extends Comparable<R>>
        extends RecordReader<NullWritable, DruidWritable>
        implements org.apache.hadoop.mapred.RecordReader<NullWritable, DruidWritable> {

  private static final Logger LOG = LoggerFactory.getLogger(DruidQueryRecordReader.class);

  /**
   * Query that Druid executes.
   */
  protected T query;

  /**
   * Query results.
   */
  protected Iterator<R> results = Iterators.emptyIterator();

  @Override
  public void initialize(InputSplit split, TaskAttemptContext context) throws IOException {
    initialize(split, context.getConfiguration());
  }

  public void initialize(InputSplit split, Configuration conf) throws IOException {
    HiveDruidSplit hiveDruidSplit = (HiveDruidSplit) split;

    // Create query
    query = createQuery(hiveDruidSplit.getDruidQuery());

    // Execute query
    if (LOG.isInfoEnabled()) {
      LOG.info("Retrieving from druid using query:\n " + query);
    }

    final Lifecycle lifecycle = new Lifecycle();
    final int numConnection = HiveConf
            .getIntVar(conf, HiveConf.ConfVars.HIVE_DRUID_NUM_HTTP_CONNECTION);
    final Period readTimeout = new Period(
            HiveConf.getVar(conf, HiveConf.ConfVars.HIVE_DRUID_HTTP_READ_TIMEOUT));

    HttpClient client = HttpClientInit.createClient(
            HttpClientConfig.builder().withReadTimeout(readTimeout.toStandardDuration())
                    .withNumConnections(numConnection).build(), lifecycle);
    try {
      lifecycle.start();
    } catch (Exception e) {
      LOG.error("Issues with lifecycle start", e);
    }
    InputStream response;
    try {
      response = DruidStorageHandlerUtils.submitRequest(client,
              DruidStorageHandlerUtils.createRequest(hiveDruidSplit.getLocations()[0], query));
    } catch (Exception e) {
      lifecycle.stop();
      throw new IOException(org.apache.hadoop.util.StringUtils.stringifyException(e));
    }

    // Retrieve results
    List<R> resultsList;
    try {
      resultsList = createResultsList(response);
    } catch (IOException e) {
      response.close();
      throw e;
    } finally {
      lifecycle.stop();
    }
    if (resultsList == null || resultsList.isEmpty()) {
      return;
    }
    results = resultsList.iterator();
  }

  protected abstract T createQuery(String content) throws IOException;

  protected abstract List<R> createResultsList(InputStream content) throws IOException;

  @Override
  public NullWritable createKey() {
    return NullWritable.get();
  }

  @Override
  public DruidWritable createValue() {
    return new DruidWritable();
  }

  @Override
  public abstract boolean next(NullWritable key, DruidWritable value) throws IOException;

  @Override
  public long getPos() {
    return 0;
  }

  @Override
  public abstract boolean nextKeyValue() throws IOException;

  @Override
  public abstract NullWritable getCurrentKey() throws IOException, InterruptedException;

  @Override
  // TODO: we could generate vector row batches so that vectorized execution may get triggered
  public abstract DruidWritable getCurrentValue() throws IOException, InterruptedException;

  @Override
  public abstract float getProgress() throws IOException;

  @Override
  public void close() {
    // Nothing to do
  }

}


text:
title: Potatoes
is_name: false

---

Potatoes


text:
package ecologylab.bigsemantics.generated.library;

import ecologylab.bigsemantics.generated.library.CategoryInterviews;
import ecologylab.bigsemantics.metadata.builtins.MetadataBuiltinsTypesScope;
import ecologylab.bigsemantics.metadata.builtins.RichDocument;
import ecologylab.bigsemantics.metadata.mm_name;
import ecologylab.bigsemantics.metametadata.MetaMetadataCompositeField;
import ecologylab.bigsemantics.namesandnums.SemanticsNames;
import ecologylab.serialization.annotations.simpl_collection;
import ecologylab.serialization.annotations.simpl_inherit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *Video Interviews with personnel from Rwanda Tribunal
 */
@simpl_inherit
public class TribunalVoices extends RichDocument
{
	@simpl_collection("category_interviews")
	@mm_name("categorized_interviews")
	private List<CategoryInterviews> categorizedInterviews;

	public TribunalVoices()
	{ super(); }

	public TribunalVoices(MetaMetadataCompositeField mmd) {
		super(mmd);
	}

	public List<CategoryInterviews> getCategorizedInterviews()
	{
		return categorizedInterviews;
	}

  // lazy evaluation:
  public List<CategoryInterviews> categorizedInterviews()
  {
    if (categorizedInterviews == null)
      categorizedInterviews = new ArrayList<CategoryInterviews>();
    return categorizedInterviews;
  }

  // addTo:
  public void addToCategorizedInterviews(CategoryInterviews element)
  {
    categorizedInterviews().add(element);
  }

  // size:
  public int categorizedInterviewsSize()
  {
    return categorizedInterviews == null ? 0 : categorizedInterviews.size();
  }

	public void setCategorizedInterviews(List<CategoryInterviews> categorizedInterviews)
	{
		this.categorizedInterviews = categorizedInterviews;
	}
}


text:
node-facebook
=============

NodeJS library for facebook


text:
var app = require('app')
var BrowserWindow = require('browser-window')

var mainWindow = null

app.on('ready', function () {
  mainWindow = new BrowserWindow({
    height: 505,
    resizable: false,
    title: '3-servo',
    width: 595
  })

  mainWindow.loadURL('file://' + __dirname + '/app/index.html')

  mainWindow.on('closed', function () {
    mainWindow = null
  })
})


text:
package com.amarjanica.discourse.models

@JsonIgnoreProperties(ignoreUnknown = true)
case class ApiKeyContainer(
  @JsonProperty("api_key")
  apiKey: ApiKey
)
@JsonIgnoreProperties(ignoreUnknown = true)
case class ApiKey(
  id: Int,
  key: String,
  user: Option[BasicUser]
)


text:
package com.azure.identity;

import com.azure.core.credential.TokenRequestContext;
import com.azure.identity.implementation.IdentityClient;
import com.azure.identity.util.TestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.exceptions.misusing.InvalidUseOfMatchersException;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Random;
import java.util.UUID;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.azure.identity.*")
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"})
public class InteractiveBrowserCredentialTest {

    private final String tenantId = "contoso.com";
    private final String clientId = UUID.randomUUID().toString();

    @Test
    public void testValidInteractive() throws Exception {
        Random random = new Random();

        // setup
        String token1 = "token1";
        String token2 = "token2";
        TokenRequestContext request1 = new TokenRequestContext().addScopes("https://management.azure.com");
        TokenRequestContext request2 = new TokenRequestContext().addScopes("https://vault.azure.net");
        OffsetDateTime expiresAt = OffsetDateTime.now(ZoneOffset.UTC).plusHours(1);
        int port = random.nextInt(10000) + 10000;

        // mock
        IdentityClient identityClient = PowerMockito.mock(IdentityClient.class);
        when(identityClient.authenticateWithBrowserInteraction(eq(request1), eq(port))).thenReturn(TestUtils.getMockMsalToken(token1, expiresAt));
        when(identityClient.authenticateWithUserRefreshToken(any(), any()))
            .thenAnswer(invocation -> {
                TokenRequestContext argument = (TokenRequestContext) invocation.getArguments()[0];
                if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request2.getScopes().get(0))) {
                    return TestUtils.getMockMsalToken(token2, expiresAt);
                } else if (argument.getScopes().size() == 1 && argument.getScopes().get(0).equals(request1.getScopes().get(0))) {
                    return Mono.error(new UnsupportedOperationException("nothing cached"));
                } else {
                    throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", (Object) argument));
                }
            });
        PowerMockito.whenNew(IdentityClient.class).withAnyArguments().thenReturn(identityClient);

        // test
        InteractiveBrowserCredential credential =
            new InteractiveBrowserCredentialBuilder().port(port).clientId(clientId).build();
        StepVerifier.create(credential.getToken(request1))
            .expectNextMatches(accessToken -> token1.equals(accessToken.getToken())
                && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
            .verifyComplete();
        StepVerifier.create(credential.getToken(request2))
            .expectNextMatches(accessToken -> token2.equals(accessToken.getToken())
                && expiresAt.getSecond() == accessToken.getExpiresAt().getSecond())
            .verifyComplete();
    }
}


text:
@interface AFN_FXWDemoVC : BaseVC

@end


text:
using System;
namespace Backlog4net
{
    /// <summary>
    /// The interface for Backlog space notification data.
    /// </summary>
    public interface SpaceNotification
    {
        string Content { get; }

        DateTime? Updated { get; }
    }
}


text:
package org.apache.hadoop.hdfs.server.namenode;

import java.util.ArrayList;

import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.server.common.GenerationStamp;
import org.apache.hadoop.hdfs.server.protocol.BlockCommand;

import junit.framework.TestCase;

/**
 * This class tests that methods in DatanodeDescriptor
 */
public class TestDatanodeDescriptor extends TestCase {
  /**
   * Test that getInvalidateBlocks observes the maxlimit.
   */
  public void testGetInvalidateBlocks() throws Exception {
    final int MAX_BLOCKS = 10;
    final int REMAINING_BLOCKS = 2;
    final int MAX_LIMIT = MAX_BLOCKS - REMAINING_BLOCKS;

    DatanodeDescriptor dd = new DatanodeDescriptor();
    ArrayList<Block> blockList = new ArrayList<Block>(MAX_BLOCKS);
    for (int i=0; i<MAX_BLOCKS; i++) {
      blockList.add(new Block(i, 0, GenerationStamp.FIRST_VALID_STAMP));
    }
    dd.addBlocksToBeInvalidated(blockList);
    BlockCommand bc = dd.getInvalidateBlocks(MAX_LIMIT);
    assertEquals(bc.getBlocks().length, MAX_LIMIT);
    bc = dd.getInvalidateBlocks(MAX_LIMIT);
    assertEquals(bc.getBlocks().length, REMAINING_BLOCKS);
  }
}


text:
package org.sterl.gcm.android.backend;

import android.os.Build;

import org.androidannotations.annotations.Bean;
import org.springframework.http.HttpAuthentication;
import org.springframework.http.HttpBasicAuthentication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

public class RestAuthInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpHeaders headers = request.getHeaders();
        // http://stackoverflow.com/questions/13182519/spring-rest-template-usage-causes-eofexception
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            headers.set("Connection", "Close");
        }
        return execution.execute(request, body);
    }
}


text:
/**
\brief GNODE-specific definition of the "bsp_timer" bsp module.

On GNODE, we use timerB0 for the bsp_timer module.

\author Thomas Watteyne <watteyne@eecs.berkeley.edu>, March 2012.
*author Rostislav Spinar <rostislav.spinar@microrisc.com>, April 2015.
*/

#include "board.h"
#include "bsp_timer.h"

//=========================== defines =========================================

//=========================== variables =======================================

typedef struct {
   bsp_timer_cbt    cb;
   PORT_TIMER_WIDTH last_compare_value;
} bsp_timer_vars_t;

bsp_timer_vars_t bsp_timer_vars;

//=========================== prototypes ======================================

//=========================== public ==========================================

/**
\brief Initialize this module.

This functions starts the timer, i.e. the counter increments, but doesn't set
any compare registers, so no interrupt will fire.
*/
void bsp_timer_init() {

   // clear local variables
   memset(&bsp_timer_vars,0,sizeof(bsp_timer_vars_t));

   // source ACLK from 32kHz crystal
   BCSCTL3             |=  LFXT1S_0;

   //set CCRB0 registers
   TBCCTL0              =  0;
   TBCCR0               =  0;

   //start TimerB
   TBCTL                =  MC_2+TBSSEL_1;             // continuous mode, from ACLK
}

/**
\brief Register a callback.

\param cb The function to be called when a compare event happens.
*/
void bsp_timer_set_callback(bsp_timer_cbt cb) {
   bsp_timer_vars.cb   = cb;
}

/**
\brief Reset the timer.

This function does not stop the timer, it rather resets the value of the
counter, and cancels a possible pending compare event.
*/
void bsp_timer_reset() {
   // reset compare
   TBCCR0               =  0;
   TBCCTL0              =  0;
   // reset timer
   TBR                  = 0;
   // record last timer compare value
   bsp_timer_vars.last_compare_value =  0;
}

/**
\brief Schedule the callback to be called in some specified time.

The delay is expressed relative to the last compare event. It doesn't matter
how long it took to call this function after the last compare, the timer will
expire precisely delayTicks after the last one.

The only possible problem is that it took so long to call this function that
the delay specified is shorter than the time already elapsed since the last
compare. In that case, this function triggers the interrupt to fire right away.

This means that the interrupt may fire a bit off, but this inaccuracy does not
propagate to subsequent timers.

\param delayTicks Number of ticks before the timer expired, relative to the
                  last compare event.
*/
void bsp_timer_scheduleIn(PORT_TIMER_WIDTH delayTicks) {
   PORT_TIMER_WIDTH newCompareValue;
   PORT_TIMER_WIDTH temp_last_compare_value;

   temp_last_compare_value = bsp_timer_vars.last_compare_value;

   newCompareValue = bsp_timer_vars.last_compare_value+delayTicks+1;
   bsp_timer_vars.last_compare_value = newCompareValue;

   if (delayTicks<TBR-temp_last_compare_value) {
      // we're already too late, schedule the ISR right now manually

      // setting the interrupt flag triggers an interrupt
      TBCCTL0          |=  CCIFG;
   } else {
      // this is the normal case, have timer expire at newCompareValue
      TBCCR0            =  newCompareValue;
      TBCCTL0          |=  CCIE;
   }
}

/**
\brief Cancel a running compare.
*/
void bsp_timer_cancel_schedule() {
   TBCCR0               =  0;
   TBCCTL0             &= ~CCIE;
}

/**
\brief Return the current value of the timer's counter.

\returns The current value of the timer's counter.
*/
PORT_TIMER_WIDTH bsp_timer_get_currentValue() {
   return TBR;
}

//=========================== private =========================================

//=========================== interrupt handlers ==============================

kick_scheduler_t bsp_timer_isr() {
   // call the callback
   bsp_timer_vars.cb();
   // kick the OS
   return KICK_SCHEDULER;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
WriterOutputStream
</TITLE>

<META NAME="date" CONTENT="2013-09-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.commons.io.output

Class WriterOutputStream

java.lang.Object
  java.io.OutputStream
      org.apache.commons.io.output.WriterOutputStream

All Implemented Interfaces:
java.io.Closeable, java.io.Flushable

public class WriterOutputStream
extends java.io.OutputStream

OutputStream implementation that transforms a byte stream to a
 character stream using a specified charset encoding and writes the resulting
 stream to a Writer. The stream is transformed using a
 CharsetDecoder object, guaranteeing that all charset
 encodings supported by the JRE are handled correctly.

 The output of the CharsetDecoder is buffered using a fixed size buffer.
 This implies that the data is written to the underlying Writer in chunks
 that are no larger than the size of this buffer. By default, the buffer is
 flushed only when it overflows or when flush() or close()
 is called. In general there is therefore no need to wrap the underlying Writer
 in a BufferedWriter. WriterOutputStream can also
 be instructed to flush the buffer after each write operation. In this case, all
 available data is written immediately to the underlying Writer, implying that
 the current position of the Writer is correlated to the current position
 of the WriterOutputStream.

 WriterOutputStream implements the inverse transformation of OutputStreamWriter;
 in the following example, writing to <tt>out2</tt> would have the same result as writing to
 <tt>out</tt> directly (provided that the byte sequence is legal with respect to the
 charset encoding):

 OutputStream out = ...
 Charset cs = ...
 OutputStreamWriter writer = new OutputStreamWriter(out, cs);
 WriterOutputStream out2 = new WriterOutputStream(writer, cs);

 WriterOutputStream implements the same transformation as InputStreamReader,
 except that the control flow is reversed: both classes transform a byte stream
 into a character stream, but InputStreamReader pulls data from the underlying stream,
 while WriterOutputStream pushes it to the underlying stream.

 Note that while there are use cases where there is no alternative to using
 this class, very often the need to use this class is an indication of a flaw
 in the design of the code. This class is typically used in situations where an existing
 API only accepts an OutputStream object, but where the stream is known to represent
 character data that must be decoded for further use.

 Instances of WriterOutputStream are not thread safe.

Since:

2.0

See Also:
ReaderInputStream

Constructor Summary

WriterOutputStream(java.io.Writer writer)

          Constructs a new WriterOutputStream that uses the default character encoding
 and with a default output buffer size of 1024 characters.

WriterOutputStream(java.io.Writer writer,
                   java.nio.charset.Charset charset)

          Constructs a new WriterOutputStream with a default output buffer size of
 1024 characters.

WriterOutputStream(java.io.Writer writer,
                   java.nio.charset.CharsetDecoder decoder)

          Constructs a new WriterOutputStream with a default output buffer size of
 1024 characters.

WriterOutputStream(java.io.Writer writer,
                   java.nio.charset.CharsetDecoder decoder,
                   int bufferSize,
                   boolean writeImmediately)

          Constructs a new WriterOutputStream.

WriterOutputStream(java.io.Writer writer,
                   java.nio.charset.Charset charset,
                   int bufferSize,
                   boolean writeImmediately)

          Constructs a new WriterOutputStream.

WriterOutputStream(java.io.Writer writer,
                   java.lang.String charsetName)

          Constructs a new WriterOutputStream with a default output buffer size of
 1024 characters.

WriterOutputStream(java.io.Writer writer,
                   java.lang.String charsetName,
                   int bufferSize,
                   boolean writeImmediately)

          Constructs a new WriterOutputStream.

Method Summary

 void
close()

          Close the stream.

 void
flush()

          Flush the stream.

 void
write(byte[] b)

          Write bytes from the specified byte array to the stream.

 void
write(byte[] b,
      int off,
      int len)

          Write bytes from the specified byte array to the stream.

 void
write(int b)

          Write a single byte to the stream.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

WriterOutputStream

public WriterOutputStream(java.io.Writer writer,
                          java.nio.charset.CharsetDecoder decoder)

Constructs a new WriterOutputStream with a default output buffer size of
 1024 characters. The output buffer will only be flushed when it overflows or when
 flush() or close() is called.

Parameters:
writer - the target Writer
decoder - the charset decoder
Since:

2.1

WriterOutputStream

public WriterOutputStream(java.io.Writer writer,
                          java.nio.charset.CharsetDecoder decoder,
                          int bufferSize,
                          boolean writeImmediately)

Constructs a new WriterOutputStream.

Parameters:
writer - the target Writer
decoder - the charset decoder
bufferSize - the size of the output buffer in number of characters
writeImmediately - If <tt>true</tt> the output buffer will be flushed after each
                         write operation, i.e. all available data will be written to the
                         underlying Writer immediately. If <tt>false</tt>, the
                         output buffer will only be flushed when it overflows or when
                         flush() or close() is called.
Since:

2.1

WriterOutputStream

public WriterOutputStream(java.io.Writer writer,
                          java.nio.charset.Charset charset,
                          int bufferSize,
                          boolean writeImmediately)

Constructs a new WriterOutputStream.

Parameters:
writer - the target Writer
charset - the charset encoding
bufferSize - the size of the output buffer in number of characters
writeImmediately - If <tt>true</tt> the output buffer will be flushed after each
                         write operation, i.e. all available data will be written to the
                         underlying Writer immediately. If <tt>false</tt>, the
                         output buffer will only be flushed when it overflows or when
                         flush() or close() is called.

WriterOutputStream

public WriterOutputStream(java.io.Writer writer,
                          java.nio.charset.Charset charset)

Constructs a new WriterOutputStream with a default output buffer size of
 1024 characters. The output buffer will only be flushed when it overflows or when
 flush() or close() is called.

Parameters:
writer - the target Writer
charset - the charset encoding

WriterOutputStream

public WriterOutputStream(java.io.Writer writer,
                          java.lang.String charsetName,
                          int bufferSize,
                          boolean writeImmediately)

Constructs a new WriterOutputStream.

Parameters:
writer - the target Writer
charsetName - the name of the charset encoding
bufferSize - the size of the output buffer in number of characters
writeImmediately - If <tt>true</tt> the output buffer will be flushed after each
                         write operation, i.e. all available data will be written to the
                         underlying Writer immediately. If <tt>false</tt>, the
                         output buffer will only be flushed when it overflows or when
                         flush() or close() is called.

WriterOutputStream

public WriterOutputStream(java.io.Writer writer,
                          java.lang.String charsetName)

Constructs a new WriterOutputStream with a default output buffer size of
 1024 characters. The output buffer will only be flushed when it overflows or when
 flush() or close() is called.

Parameters:
writer - the target Writer
charsetName - the name of the charset encoding

WriterOutputStream

public WriterOutputStream(java.io.Writer writer)

Constructs a new WriterOutputStream that uses the default character encoding
 and with a default output buffer size of 1024 characters. The output buffer will only
 be flushed when it overflows or when flush() or close() is called.

Parameters:
writer - the target Writer

Method Detail

write

public void write(byte[] b,
                  int off,
                  int len)
           throws java.io.IOException

Write bytes from the specified byte array to the stream.

Overrides:
write in class java.io.OutputStream

Parameters:
b - the byte array containing the bytes to write
off - the start offset in the byte array
len - the number of bytes to write

Throws:

java.io.IOException - if an I/O error occurs

write

public void write(byte[] b)
           throws java.io.IOException

Write bytes from the specified byte array to the stream.

Overrides:
write in class java.io.OutputStream

Parameters:
b - the byte array containing the bytes to write

Throws:

java.io.IOException - if an I/O error occurs

write

public void write(int b)
           throws java.io.IOException

Write a single byte to the stream.

Specified by:
write in class java.io.OutputStream

Parameters:
b - the byte to write

Throws:

java.io.IOException - if an I/O error occurs

flush

public void flush()
           throws java.io.IOException

Flush the stream. Any remaining content accumulated in the output buffer
 will be written to the underlying Writer. After that
 Writer.flush() will be called.

Specified by:
flush in interface java.io.Flushable
Overrides:
flush in class java.io.OutputStream

Throws:

java.io.IOException - if an I/O error occurs

close

public void close()
           throws java.io.IOException

Close the stream. Any remaining content accumulated in the output buffer
 will be written to the underlying Writer. After that
 Writer.close() will be called.

Specified by:
close in interface java.io.Closeable
Overrides:
close in class java.io.OutputStream

Throws:

java.io.IOException - if an I/O error occurs

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
USE [ANTERO]
GO
/****** Object:  StoredProcedure [dw].[p_lataa_amos_opiskelijavuodet_koko]    Script Date: 24.10.2019 14:12:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dw].[p_lataa_amos_opiskelijavuodet_koko]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dw].[p_lataa_amos_opiskelijavuodet_koko] AS'
END
GO

ALTER PROCEDURE [dw].[p_lataa_amos_opiskelijavuodet_koko] AS

EXEC Koski_SA.[dbo].[p_lataa_opiskelijavuodet_valitaulu]

EXEC Koski_SA.[dbo].[p_lataa_opiskelijavuodet_valitaulu_unpivot]

EXEC [dw].[p_lataa_f_amos_opiskelijavuodet]

EXEC dw.p_lataa_f_amos_opiskelijavuodet_painotetut

GO
/****** Object:  StoredProcedure [dw].[p_lataa_amos_tutkinnot_ja_tutkinnonosat_koko]    Script Date: 24.10.2019 14:12:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dw].[p_lataa_amos_tutkinnot_ja_tutkinnonosat_koko]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dw].[p_lataa_amos_tutkinnot_ja_tutkinnonosat_koko] AS'
END
GO

ALTER PROCEDURE [dw].[p_lataa_amos_tutkinnot_ja_tutkinnonosat_koko] AS

EXEC Koski_SA.dbo.p_lataa_tutkinnot_ja_tutkinnonosat_esivalmistelu

EXEC Koski_SA.dbo.p_lataa_tutkinnot_ja_tutkinnonosat_valitaulu
EXEC Koski_SA.dbo.p_lataa_tutkinnot_ja_tutkinnonosat_valitaulu_organisaatiorajaus

EXEC ANTERO.dw.p_lataa_f_amos_tutkinnot_ja_tutkinnonosat

EXEC ANTERO.sa.p_lataa_sa_amos_tutkinnot_pohjakoulutus_kaikki
EXEC ANTERO.sa.p_lataa_sa_amos_tutkinnot_pohjakoulutus_kaikki_unpivot
EXEC ANTERO.dw.p_lataa_f_amos_tutkinnot_ja_tutkinnonosat_painotetut


text:
using EasyLOB;
using EasyLOB.Mvc;

namespace EasyLOB.Identity.Mvc
{
    public partial class UserItemModel : ItemModel
    {
        #region Properties

        public override bool IsMasterDetail
        {
            get { return false; }
        }

        public UserViewModel User { get; set; }

        #endregion Properties

        #region Methods

        public UserItemModel()
            : base()
        {
            User = new UserViewModel();
        }

        public UserItemModel(ZActivityOperations activityOperations, string controllerAction, UserViewModel user = null)
            : this()
        {
            ActivityOperations = activityOperations;
            ControllerAction = controllerAction;
            User = user ?? User;
        }

        #endregion Methods
    }
}


text:
package client

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"

	"github.com/flynn/flynn/pkg/httpclient"
	"github.com/flynn/flynn/router/types"
)

// ErrNotFound is returned when no route was found.
var ErrNotFound = errors.New("router: route not found")

type client struct {
	*httpclient.Client
}

// New uses the default discoverd client and returns a client.
func New() Client {
	return newRouterClient()
}

// NewWithHTTP does the same thing as New but uses the given *http.Client
func NewWithHTTP(http *http.Client) Client {
	c := newRouterClient()
	http.Transport = c.HTTP.Transport
	c.HTTP = http
	return c
}

func newRouterClient() *client {
	return &client{Client: &httpclient.Client{
		ErrNotFound: ErrNotFound,
		URL:         "http://router-api.discoverd:5000",
		HTTP:        http.DefaultClient,
	}}
}

// NewWithAddr uses addr as the specified API url and returns a client.
func NewWithAddr(addr string) Client {
	c := newRouterClient()
	c.URL = fmt.Sprintf("http://%s", addr)
	return c
}

// Client is a client for the router API.
type Client interface {
	// CreateRoute creates a new route.
	CreateRoute(*router.Route) error
	// UpdateRoute updates an existing route by overwriting all fields on the route
	// except ID and Domain.
	UpdateRoute(*router.Route) error
	// DeleteRoute deletes the route with the specified routeType and id.
	DeleteRoute(routeType, id string) error
	// GetRoute returns a route with the specified routeType and id.
	GetRoute(routeType, id string) (*router.Route, error)
	// ListRoutes returns a list of routes. If parentRef is not empty, routes
	// are filtered by the reference (ex: "controller/apps/myapp").
	ListRoutes(parentRef string) ([]*router.Route, error)
}

func (c *client) CreateRoute(r *router.Route) error {
	return c.Post("/routes", r, r)
}

func (c *client) UpdateRoute(r *router.Route) error {
	return c.Put("/routes/"+r.Type+"/"+r.ID, r, r)
}

func (c *client) DeleteRoute(routeType, id string) error {
	return c.Delete("/routes/" + routeType + "/" + id)
}

func (c *client) GetRoute(routeType, id string) (*router.Route, error) {
	res := &router.Route{}
	err := c.Get(fmt.Sprintf("/routes/%s/%s", routeType, id), res)
	return res, err
}

func (c *client) ListRoutes(parentRef string) ([]*router.Route, error) {
	path := "/routes"
	if parentRef != "" {
		q := make(url.Values)
		q.Set("parent_ref", parentRef)
		path += "?" + q.Encode()
	}
	var res []*router.Route
	err := c.Get(path, &res)
	return res, err
}


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

namespace Mozu.Api.Urls.Commerce.Settings
{
	public partial class CheckoutSettingsUrl
	{

		/// <summary>
        /// Get Resource Url for GetCheckoutSettings
        /// </summary>
        /// <param name="responseFields">Use this field to include those fields which are not included by default.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl GetCheckoutSettingsUrl(string responseFields =  null)
		{
			var url = "/api/commerce/settings/checkout/?responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "responseFields", responseFields);
			return mozuUrl;
		}

	}
}