text:
from typing import Any, Dict, List, Optional

from googleapiclient.discovery import Resource, build
from googleapiclient.http import MediaFileUpload

from airflow.providers.google.common.hooks.base_google import GoogleBaseHook

class GoogleAnalyticsHook(GoogleBaseHook):
    """Hook for Google Analytics 360."""

    def __init__(self, api_version: str = "v3", *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.api_version = api_version
        self._conn = None

    def _paginate(self, resource: Resource, list_args: Optional[Dict[str, Any]] = None) -> List[dict]:
        list_args = list_args or {}
        result: List[dict] = []
        while True:
            # start index has value 1
            request = resource.list(start_index=len(result) + 1, **list_args)
            response = request.execute(num_retries=self.num_retries)
            result.extend(response.get("items", []))
            # result is the number of fetched links from Analytics
            # when all links will be added to the result
            # the loop will break
            if response["totalResults"] <= len(result):
                break
        return result

    def get_conn(self) -> Resource:
        """Retrieves connection to Google Analytics 360."""
        if not self._conn:
            http_authorized = self._authorize()
            self._conn = build(
                "analytics",
                self.api_version,
                http=http_authorized,
                cache_discovery=False,
            )
        return self._conn

    def list_accounts(self) -> List[Dict[str, Any]]:
        """Lists accounts list from Google Analytics 360."""
        self.log.info("Retrieving accounts list...")
        conn = self.get_conn()
        accounts = conn.management().accounts()
        result = self._paginate(accounts)
        return result

    def get_ad_words_link(
        self, account_id: str, web_property_id: str, web_property_ad_words_link_id: str
    ) -> Dict[str, Any]:
        """
        Returns a web property-Google Ads link to which the user has access.

        :param account_id: ID of the account which the given web property belongs to.
        :type account_id: string
        :param web_property_id: Web property-Google Ads link UA-string.
        :type web_property_id: string
        :param web_property_ad_words_link_id: to retrieve the Google Ads link for.
        :type web_property_ad_words_link_id: string

        :returns: web property-Google Ads
        :rtype: Dict
        """
        self.log.info("Retrieving ad words links...")
        ad_words_link = (
            self.get_conn()
            .management()
            .webPropertyAdWordsLinks()
            .get(
                accountId=account_id,
                webPropertyId=web_property_id,
                webPropertyAdWordsLinkId=web_property_ad_words_link_id,
            )
            .execute(num_retries=self.num_retries)
        )
        return ad_words_link

    def list_ad_words_links(self, account_id: str, web_property_id: str) -> List[Dict[str, Any]]:
        """
        Lists webProperty-Google Ads links for a given web property.

        :param account_id: ID of the account which the given web property belongs to.
        :type account_id: str
        :param web_property_id: Web property UA-string to retrieve the Google Ads links for.
        :type web_property_id: str

        :returns: list of entity Google Ads links.
        :rtype: list
        """
        self.log.info("Retrieving ad words list...")
        conn = self.get_conn()
        ads_links = conn.management().webPropertyAdWordsLinks()
        list_args = {"accountId": account_id, "webPropertyId": web_property_id}
        result = self._paginate(ads_links, list_args)
        return result

    def upload_data(
        self,
        file_location: str,
        account_id: str,
        web_property_id: str,
        custom_data_source_id: str,
        resumable_upload: bool = False,
    ) -> None:
        """
        Uploads file to GA via the Data Import API

        :param file_location: The path and name of the file to upload.
        :type file_location: str
        :param account_id: The GA account Id to which the data upload belongs.
        :type account_id: str
        :param web_property_id: UA-string associated with the upload.
        :type web_property_id: str
        :param custom_data_source_id: Custom Data Source Id to which this data import belongs.
        :type custom_data_source_id: str
        :param resumable_upload: flag to upload the file in a resumable fashion, using a
            series of at least two requests.
        :type resumable_upload: bool
        """
        media = MediaFileUpload(
            file_location,
            mimetype="application/octet-stream",
            resumable=resumable_upload,
        )

        self.log.info(
            "Uploading file to GA file for accountId: %s, webPropertyId:%s and customDataSourceId:%s ",
            account_id,
            web_property_id,
            custom_data_source_id,
        )

        self.get_conn().management().uploads().uploadData(
            accountId=account_id,
            webPropertyId=web_property_id,
            customDataSourceId=custom_data_source_id,
            media_body=media,
        ).execute()

    def delete_upload_data(
        self,
        account_id: str,
        web_property_id: str,
        custom_data_source_id: str,
        delete_request_body: Dict[str, Any],
    ) -> None:
        """
        Deletes the uploaded data for a given account/property/dataset

        :param account_id: The GA account Id to which the data upload belongs.
        :type account_id: str
        :param web_property_id: UA-string associated with the upload.
        :type web_property_id: str
        :param custom_data_source_id: Custom Data Source Id to which this data import belongs.
        :type custom_data_source_id: str
        :param delete_request_body: Dict of customDataImportUids to delete.
        :type delete_request_body: dict
        """
        self.log.info(
            "Deleting previous uploads to GA file for accountId:%s, "
            "webPropertyId:%s and customDataSourceId:%s ",
            account_id,
            web_property_id,
            custom_data_source_id,
        )

        self.get_conn().management().uploads().deleteUploadData(
            accountId=account_id,
            webPropertyId=web_property_id,
            customDataSourceId=custom_data_source_id,
            body=delete_request_body,
        ).execute()

    def list_uploads(self, account_id, web_property_id, custom_data_source_id) -> List[Dict[str, Any]]:
        """
        Get list of data upload from GA

        :param account_id: The GA account Id to which the data upload belongs.
        :type account_id: str
        :param web_property_id: UA-string associated with the upload.
        :type web_property_id: str
        :param custom_data_source_id: Custom Data Source Id to which this data import belongs.
        :type custom_data_source_id: str
        """
        self.log.info(
            "Getting list of uploads for accountId:%s, webPropertyId:%s and customDataSourceId:%s ",
            account_id,
            web_property_id,
            custom_data_source_id,
        )

        uploads = self.get_conn().management().uploads()
        list_args = {
            "accountId": account_id,
            "webPropertyId": web_property_id,
            "customDataSourceId": custom_data_source_id,
        }
        result = self._paginate(uploads, list_args)
        return result


text:
            Email Completo (default sem arroba: dextra-sw.com)
            <input type="text" ng-model="credit.user" placeholder="username@dextra-sw.com, ou username@mutant.br">

BZG<input type="number" ng-model="credit.value">

    <input type="button" class="btn-confirm" value="CONFIRMAR" ng-click="new()"/>

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.boot.actuate.cache;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

/**
 * Provide a {@link CacheStatistics} based on a {@link Cache}.
 *
 * @param <C> The {@link Cache} type
 * @author Stephane Nicoll
 * @author Phillip Webb
 * @since 1.3.0
 */
@FunctionalInterface
public interface CacheStatisticsProvider<C extends Cache> {

	/**
	 * Return the current {@link CacheStatistics} snapshot for the specified {@link Cache}
	 * or {@code null} if the given cache could not be handled.
	 * @param cacheManager the {@link CacheManager} handling this cache
	 * @param cache the cache to handle
	 * @return the current cache statistics or {@code null}
	 */
	CacheStatistics getCacheStatistics(CacheManager cacheManager, C cache);

}


text:
package ru.vyukov.bakapa.agent.service.backup;

import ru.vyukov.bakapa.dto.backups.task.BackupTaskDTO;

/**
 * @author Oleg Vyukov
 */
interface BackupScriptFactory {

    BackupScript create(BackupTaskDTO backupTaskDTO, BackupServiceConfig backupServiceConfig, Logger logger);
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.  You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include <cassert>
#include <cstdlib>
#include <vector>
#include <string>

#include <sstream>
#include <iostream>

#include "popen.h"
#include "sp-data.h"
#include "features.h"

#include "simple-api.h"

// externed variables
int debug_level = 0;
bool absolute_counts = true;
bool collect_correct = false;
bool collect_incorrect = false;

RerankerError::RerankerError(const std::string msg) {
    this->description = msg;
}

void setOptions(int debug, bool abs_counts) {
    debug_level = debug;
    absolute_counts = abs_counts;
}

RerankerModel::RerankerModel(const char* feature_class,
        const char* feature_ids_filename,
        const char* feature_weights_filename) {
    fcps = new FeatureClassPtrs(feature_class);

    if (!std::ifstream(feature_ids_filename).good()) {
        throw RerankerError("Can't open feature IDs file.");
    }
    izstream fdin(feature_ids_filename);
    maxid = fcps->read_feature_ids(fdin);

    izstream fwin(feature_weights_filename);
    if (!std::ifstream(feature_weights_filename).good()) {
        throw RerankerError("Can't open feature weights file.");
    }

    weights = new Weights(maxid + 1);
    Id id;
    Float weight;
    while (fwin >> id >> "=" >> weight) {
        assert(id <= maxid);
        assert((*weights)[id] == 0);
        (*weights)[id] = weight;
    }
}

Weights*
RerankerModel::scoreNBestList(const sp_sentence_type& nbest_list) const {
    Id_Floats p_i_v(nbest_list.nparses());
    cforeach (FeatureClassPtrs, it, *fcps)
        (*it)->feature_values(nbest_list, p_i_v);

    Weights* parse_scores = new Weights();

    for (size_type i = 0; i < nbest_list.nparses(); ++i) {
        const Id_Float& i_v = p_i_v[i];

        Float w = 0;
        cforeach (Id_Float, ivit, i_v) {
            assert(ivit->first < weights->size());
            w += ivit->second * (*weights)[ivit->first];
        }
        parse_scores->push_back(w);
    }

    return parse_scores;
}

sp_sentence_type* readNBestList(const std::string nbest_list, bool lowercase) {
    std::stringstream text(nbest_list);
    sp_sentence_type* s = new sp_sentence_type();
    s->read(text, lowercase);

    return s;
}


text:
Custom scripting was introduced to provide a way for users to execute custom logic from within the NetBox UI. Custom scripts enable the user to directly and conveniently manipulate NetBox data in a prescribed fashion. They can be used to accomplish myriad tasks, such as:

* Automatically populate new devices and cables in preparation for a new site deployment
* Create a range of new reserved prefixes or IP addresses
* Fetch data from an external source and import it to NetBox

Custom scripts are Python code and exist outside of the official NetBox code base, so they can be updated and changed without interfering with the core NetBox installation. And because they're completely custom, there is no inherent limitation on what a script can accomplish.

## Writing Custom Scripts

All custom scripts must inherit from the `extras.scripts.Script` base class. This class provides the functionality necessary to generate forms and log activity.

```python
from extras.scripts import Script

class MyScript(Script):
    ...
```

Scripts comprise two core components: a set of variables and a `run()` method. Variables allow your script to accept user input via the NetBox UI, but they are optional: If your script does not require any user input, there is no need to define any variables.

The `run()` method is where your script's execution logic lives. (Note that your script can have as many methods as needed: this is merely the point of invocation for NetBox.)

```python
class MyScript(Script):
    var1 = StringVar(...)
    var2 = IntegerVar(...)
    var3 = ObjectVar(...)

    def run(self, data, commit):
        ...
```

The `run()` method should accept two arguments:

* `data` - A dictionary containing all of the variable data passed via the web form.
* `commit` - A boolean indicating whether database changes will be committed.

!!! note
    The `commit` argument was introduced in NetBox v2.7.8. Backward compatibility is maintained for scripts which accept only the `data` argument, however beginning with v2.10 NetBox will require the `run()` method of every script to accept both arguments. (Either argument may still be ignored within the method.)

Defining script variables is optional: You may create a script with only a `run()` method if no user input is needed.

Any output generated by the script during its execution will be displayed under the "output" tab in the UI.

By default, scripts within a module are ordered alphabetically in the scripts list page. To return scripts in a specific order, you can define the `script_order` variable at the end of your module. The `script_order` variable is a tuple which contains each Script class in the desired order. Any scripts that are omitted from this list will be listed last.

```python
from extras.scripts import Script

class MyCustomScript(Script):
    ...

class AnotherCustomScript(Script):
    ...

script_order = (MyCustomScript, AnotherCustomScript)
```

## Module Attributes

### `name`

You can define `name` within a script module (the Python file which contains one or more scripts) to set the module name. If `name` is not defined, the module's file name will be used.

## Script Attributes

Script attributes are defined under a class named `Meta` within the script. These are optional, but encouraged.

### `name`

This is the human-friendly names of your script. If omitted, the class name will be used.

### `description`

A human-friendly description of what your script does.

### `field_order`

By default, script variables will be ordered in the form as they are defined in the script. `field_order` may be defined as an iterable of field names to determine the order in which variables are rendered. Any fields not included in this iterable be listed last.

### `commit_default`

The checkbox to commit database changes when executing a script is checked by default. Set `commit_default` to False under the script's Meta class to leave this option unchecked by default.

```python
commit_default = False
```

### `job_timeout`

Set the maximum allowed runtime for the script. If not set, `RQ_DEFAULT_TIMEOUT` will be used.

!!! info "This feature was introduced in v3.2.1"

## Accessing Request Data

Details of the current HTTP request (the one being made to execute the script) are available as the instance attribute `self.request`. This can be used to infer, for example, the user executing the script and the client IP address:

```python
username = self.request.user.username
ip_address = self.request.META.get('HTTP_X_FORWARDED_FOR') or \
    self.request.META.get('REMOTE_ADDR')
self.log_info(f"Running as user {username} (IP: {ip_address})...")
```

For a complete list of available request parameters, please see the [Django documentation](https://docs.djangoproject.com/en/stable/ref/request-response/).

## Reading Data from Files

The Script class provides two convenience methods for reading data from files:

* `load_yaml`
* `load_json`

These two methods will load data in YAML or JSON format, respectively, from files within the local path (i.e. `SCRIPTS_ROOT`).

## Logging

The Script object provides a set of convenient functions for recording messages at different severity levels:

* `log_debug`
* `log_success`
* `log_info`
* `log_warning`
* `log_failure`

Log messages are returned to the user upon execution of the script. Markdown rendering is supported for log messages.

## Variable Reference

### Default Options

All custom script variables support the following default options:

* `default` - The field's default value
* `description` - A brief user-friendly description of the field
* `label` - The field name to be displayed in the rendered form
* `required` - Indicates whether the field is mandatory (all fields are required by default)
* `widget` - The class of form widget to use (see the [Django documentation](https://docs.djangoproject.com/en/stable/ref/forms/widgets/))

### StringVar

Stores a string of characters (i.e. text). Options include:

* `min_length` - Minimum number of characters
* `max_length` - Maximum number of characters
* `regex` - A regular expression against which the provided value must match

Note that `min_length` and `max_length` can be set to the same number to effect a fixed-length field.

### TextVar

Arbitrary text of any length. Renders as a multi-line text input field.

### IntegerVar

Stores a numeric integer. Options include:

* `min_value` - Minimum value
* `max_value` - Maximum value

### BooleanVar

A true/false flag. This field has no options beyond the defaults listed above.

### ChoiceVar

A set of choices from which the user can select one.

* `choices` - A list of `(value, label)` tuples representing the available choices. For example:

```python
CHOICES = (
    ('n', 'North'),
    ('s', 'South'),
    ('e', 'East'),
    ('w', 'West')
)

direction = ChoiceVar(choices=CHOICES)
```

In the example above, selecting the choice labeled "North" will submit the value `n`.

### MultiChoiceVar

Similar to `ChoiceVar`, but allows for the selection of multiple choices.

### ObjectVar

A particular object within NetBox. Each ObjectVar must specify a particular model, and allows the user to select one of the available instances. ObjectVar accepts several arguments, listed below.

* `model` - The model class
* `query_params` - A dictionary of query parameters to use when retrieving available options (optional)
* `null_option` - A label representing a "null" or empty choice (optional)

To limit the selections available within the list, additional query parameters can be passed as the `query_params` dictionary. For example, to show only devices with an "active" status:

```python
device = ObjectVar(
    model=Device,
    query_params={
        'status': 'active'
    }
)
```

Multiple values can be specified by assigning a list to the dictionary key. It is also possible to reference the value of other fields in the form by prepending a dollar sign (`$`) to the variable's name.

```python
region = ObjectVar(
    model=Region
)
site = ObjectVar(
    model=Site,
    query_params={
        'region_id': '$region'
    }
)
```

### MultiObjectVar

Similar to `ObjectVar`, but allows for the selection of multiple objects.

### FileVar

An uploaded file. Note that uploaded files are present in memory only for the duration of the script's execution: They will not be automatically saved for future use. The script is responsible for writing file contents to disk where necessary.

### IPAddressVar

An IPv4 or IPv6 address, without a mask. Returns a `netaddr.IPAddress` object.

### IPAddressWithMaskVar

An IPv4 or IPv6 address with a mask. Returns a `netaddr.IPNetwork` object which includes the mask.

### IPNetworkVar

An IPv4 or IPv6 network with a mask. Returns a `netaddr.IPNetwork` object. Two attributes are available to validate the provided mask:

* `min_prefix_length` - Minimum length of the mask
* `max_prefix_length` - Maximum length of the mask

## Running Custom Scripts

!!! note
    To run a custom script, a user must be assigned the `extras.run_script` permission. This is achieved by assigning the user (or group) a permission on the Script object and specifying the `run` action in the admin UI as shown below.

    ![Adding the run action to a permission](../media/admin_ui_run_permission.png)

### Via the Web UI

Custom scripts can be run via the web UI by navigating to the script, completing any required form data, and clicking the "run script" button.

### Via the API

To run a script via the REST API, issue a POST request to the script's endpoint specifying the form data and commitment. For example, to run a script named `example.MyReport`, we would make a request such as the following:

```no-highlight
curl -X POST \
-H "Authorization: Token $TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json; indent=4" \
http://netbox/api/extras/scripts/example.MyReport/ \
--data '{"data": {"foo": "somevalue", "bar": 123}, "commit": true}'
```

### Via the CLI

Scripts can be run on the CLI by invoking the management command:

```
python3 manage.py runscript [--commit] [--loglevel {debug,info,warning,error,critical}] [--data "<data>"] <module>.<script>
```

The required ``<module>.<script>`` argument is the script to run where ``<module>`` is the name of the python file in the ``scripts`` directory without the ``.py`` extension and ``<script>`` is the name of the script class in the ``<module>`` to run.

The optional ``--data "<data>"`` argument is the data to send to the script

The optional ``--loglevel`` argument is the desired logging level to output to the console.

The optional ``--commit`` argument will commit any changes in the script to the database.

## Example

Below is an example script that creates new objects for a planned site. The user is prompted for three variables:

* The name of the new site
* The device model (a filtered list of defined device types)
* The number of access switches to create

These variables are presented as a web form to be completed by the user. Once submitted, the script's `run()` method is called to create the appropriate objects.

```python
from django.utils.text import slugify

from dcim.choices import DeviceStatusChoices, SiteStatusChoices
from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Site
from extras.scripts import *

class NewBranchScript(Script):

    class Meta:
        name = "New Branch"
        description = "Provision a new branch site"
        field_order = ['site_name', 'switch_count', 'switch_model']

    site_name = StringVar(
        description="Name of the new site"
    )
    switch_count = IntegerVar(
        description="Number of access switches to create"
    )
    manufacturer = ObjectVar(
        model=Manufacturer,
        required=False
    )
    switch_model = ObjectVar(
        description="Access switch model",
        model=DeviceType,
        query_params={
            'manufacturer_id': '$manufacturer'
        }
    )

    def run(self, data, commit):

        # Create the new site
        site = Site(
            name=data['site_name'],
            slug=slugify(data['site_name']),
            status=SiteStatusChoices.STATUS_PLANNED
        )
        site.save()
        self.log_success(f"Created new site: {site}")

        # Create access switches
        switch_role = DeviceRole.objects.get(name='Access Switch')
        for i in range(1, data['switch_count'] + 1):
            switch = Device(
                device_type=data['switch_model'],
                name=f'{site.slug}-switch{i}',
                site=site,
                status=DeviceStatusChoices.STATUS_PLANNED,
                device_role=switch_role
            )
            switch.save()
            self.log_success(f"Created new switch: {switch}")

        # Generate a CSV table of new devices
        output = [
            'name,make,model'
        ]
        for switch in Device.objects.filter(site=site):
            attrs = [
                switch.name,
                switch.device_type.manufacturer.name,
                switch.device_type.model
            ]
            output.append(','.join(attrs))

        return '\n'.join(output)
```


text:
layout:     post
title:      Tweets
date:       2018-08-16
summary:    These are the tweets for August 16, 2018.
categories:
---


text:
package edu.asu.ser.jsonrpc.proxy;

import calc.server.Calculator;
import edu.asu.ser.jsonrpc.lite.client.HttpClient;

public class TestGenerator {
	public static void main(String args[])
	{
		SwiftClientProxyGenerator.generateSwiftProxy(Calculator.class,HttpClient.class);

//		SwiftClientProxyGenerator.generateSwiftProxy(Calculator.class, TCPClient.class);

//		JavaClientProxyGenerator.generateJavaProxy(WaypointServer.class, HttpClient.class);
//
//		JavaClientProxyGenerator.generateJavaProxy(WaypointServer.class, TCPClient.class);

	}

}


text:
using System;

namespace EasyNetQ.Management.Client.Model
{
    public class Connection
    {
        public Int64 RecvOct { get; set; }
        public Int64 RecvCnt { get; set; }
        public Int64 SendOct { get; set; }
        public Int64 SendCnt { get; set; }
        public Int64 SendPend { get; set; }
        public string State { get; set; }
        public string LastBlockedBy { get; set; }
        public string LastBlockedAge { get; set; }
        public Int64 Channels { get; set; }
        public string Type { get; set; }
        public string Node { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public int Port { get; set; }
        //PeerAddress is the connected Peer IP Address for RabbitMQ Version <3.0
        public string PeerAddress { get; set; }
        //PeerAddress is the connected Peer IP Address for RabbitMQ Version >3.0
        public string PeerHost { get; set; }
        public Int32 PeerPort { get; set; }
        public bool Ssl { get; set; }
        public string PeerCertSubject { get; set; }
        public string PeerCertIssuer { get; set; }
        public string PeerCertValidity { get; set; }
        public string AuthMechanism { get; set; }
        public string SslProtocol { get; set; }
        public string SslKeyExchange { get; set; }
        public string SslCipher { get; set; }
        public string SslHash { get; set; }
        public string Protocol { get; set; }
        public string User { get; set; }
        public string Vhost { get; set; }
        public Int64 Timeout { get; set; }
        public Int64 FrameMax { get; set; }
        public ClientProperties ClientProperties { get; set; }
    }
}


text:
class SandboxEmailInterceptor
  def self.delivering_email(message)
    message.to = ['sample@example.com']
  end
end


text:
/**
 * creater:pater
 */
(function () {

	/**
	 * @param json
	 * @param {{style:String}} json 加载图形 默认circle
	 */
	function Loaders(config) {
		this.Loaders;
		this.style = (config && config.style ) ? config.style : "circle";
		this.init(config);
	}

	Loaders.prototype = {
		constructor: Loaders,
		init: function (config) {
			let _this = this;
			_this.style = (['circle', 'circle-side', 'arrow-circle', 'ball-scale', 'ball-circle', 'rectangle'
				, 'heart', 'ball-rotate', 'ball-pulse', 'jumping', 'satellite'].filter(function (data) {
				return _this.style.indexOf(data) > -1;
			}).length > 0) ? _this.style : "circle";
		},
		hide: function () {
			$("#screen").fadeOut(100);
			setTimeout(function () {
				$("#screen").remove();
			}, 100);
		},
		show: function () {
			let _this = this;
			$("body").append(`<div  id="screen"><div id="screenLoading" data-loader="${_this.style}"></div></div>`);
		}
	};
	if (typeof exports == "object") {
		module.exports = Loaders;
	} else if (typeof define == "function" && define.amd) {
		define([], function () {
			return Loaders;
		})
	} else {
		window.Loaders = Loaders;
	}
})();


text:
#pragma once
#include <glm/glm.hpp>

#include "../common/json.h"
#include "../gfx/mesh_chunk.h"
#include "../collisionlib/triangle.h"
namespace redc { namespace fps
{
  struct Object
  {
    gfx::Mesh_Chunk mesh;
    glm::mat4 model;
  };

  struct Scene
  {
    glm::vec3 player_pos;

    std::vector<collis::Triangle> collision_triangles;

    // Give just one mesh chunk ownership of the mesh, the rest of the chunks
    // in the vector can point to it since as long as everything is destructed
    // at the same time it shouldn't be a problem.
    std::vector<Object> objects;
  };

  Scene load_scene(std::string fn, std::unique_ptr<IMesh> msh) noexcept;
} }


text:
package uk.co.yottr.repository;

import org.springframework.data.repository.CrudRepository;
import uk.co.yottr.model.User;

public interface UserRepository extends CrudRepository<User, Integer> {
    User findByUsername(String username);
}


text:
<!DOCTYPE html>
<html lang='en'>
    <head>

        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    </head>

    <body>

        <dna-new-state state='home' route='/'></dna-new-state>
        <dna-new-state state='home' route='/home'></dna-new-state>
        <dna-new-state state='contact' route='/contact'></dna-new-state>
        <dna-new-state state='admin' route='/contact/admin/:id/'></dna-new-state>
        <dna-new-state state='notfound' route='/notfound'></dna-new-state>

        <dna-many-view>

                <dna-view
                    state='home'
                    on-auth
                    element='esp-hello'
                    template='comp'
                    else-state='login'></dna-view>
        </dna-many-view>

        <dna-view
            state='contact'
            element='esp-birrr'
            template='comp'
            else-state='login'></dna-view>

        <dna-view
            state='admin'
            element='esp-admin'
            template='comp'
            else-state='login'></dna-view>

        <dna-view
            state='notfound'
            element='esp-not'
            template='comp'
            else-state='login'></dna-view>

    </body>

    <link rel="import" href="bower_components/dna-router/dna.html">
    <link rel="import" href="bower_components/iron-ajax/iron-ajax.html">
<!--     <link rel="import" href="comp/esp.hello.html">
 -->
    <script src="./bower_components/webcomponentsjs/webcomponents-lite.js"></script>

</html>


text:
//
//  Layout-utils.h
//  LayoutTest
//
//  Created by Param Aggarwal on 05/11/14.
//  Copyright (c) 2014 Param Aggarwal. All rights reserved.
//

#ifndef __LayoutTest__Layout_utils__
#define __LayoutTest__Layout_utils__

#include <stdio.h>

#endif /* defined(__LayoutTest__Layout_utils__) */

#include "Layout.h"

css_node_t *new_test_css_node(void);
static void init_test_css_node(css_node_t *node);

static bool is_dirty(void *context);

void init_css_node_children(css_node_t *node, int children_count);
static css_node_t* get_child(void *context, int i);


text:
"""API functions for controlling the Cloudhands DB

This module contains all the API functions available on the Cloudhands RESTful
API. Modifications requests to the database are mediated through functions in
the "server" module.
"""

import json, uuid
import hashlib, base64, random
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.httpexceptions import (HTTPBadRequest, HTTPNotImplemented,
                                    HTTPUnauthorized, HTTPForbidden,
                                    HTTPNotFound, HTTPInternalServerError )
from pyramid.security import Allow, Everyone

from eos_db import server

# Patch for view_config - as we're not calling any of these functions directly it's
# too easy to accidentally give two funtions the same name, and then wonder why
# the result is a 404 error.
# This workaround patches the view_config decorator so that it complains when you
# try to decorate a function that has already been declared.  The behaviour should
# be otherwise unaffected.
# (Note that pyflakes3 is a good way to pick up this issue too.)
# Also, for bonus points, implement the routes=[list] argument.
_view_config = view_config
def view_config(*args, **kwargs):
    def new_decorator(f):
        if f.__name__ in globals():
            raise AttributeError("This module already has a function %s() defined" % f.__name__)
        if 'routes' in kwargs:
            for r in kwargs.pop('routes'):
                f = _view_config(*args, route_name=r, **kwargs)(f)
            return f
        else:
            return _view_config(*args, **kwargs)(f)
    return new_decorator

class PermissionsMap():
    """This is passed to pyramid.config.Configurator in __init__.py,
       and defines the permissions attributed to each group. """

    __acl__ = [(Allow, Everyone,               'login'),
               (Allow, 'group:users',          'use'),
               (Allow, 'group:agents',         'use'),
               (Allow, 'group:agents',         'act'),
               (Allow, 'group:administrators', 'use'),
               (Allow, 'group:administrators', 'act'),
               (Allow, 'group:administrators', 'administer')]
    def __init__(self, request):
        """ No-operations here. """
        pass

@view_config(request_method="GET", route_name='home', renderer='json')
def home_view(request):
    """ Return a list of all valid API calls by way of documentation. """
    call_list = {"Valid API Call List":{
                              "Retrieve User List": "/users",
                              "Get my details": "/user",
                              "Get my touches": "/user/touches",
                              "Set my password": "/user/password",
                              "Get my credit": "/user/credit",
                              "servers": "/servers",  # Return server list
                              "Server details by name": "/servers/{name}",  # Get server details or
                              "Server details by ID": "/servers/by_id/{id}",
                              "Start a server": "/servers/{name}/Starting",
                              "Stop a server": "/servers/{name}/Stopping",
                              "Restart a server": "/servers/{name}/Restarting",
                              "De-Boost a server": "/servers/{name}/pre_deboosting",
                              "server_Pre_Deboosted": "/servers/{name}/Pre_deboosted",
                              "server_Deboost": "/servers/{name}/deboosting",
                              "server_Started": "/servers/{name}/Started",
                              "server_Stopped": "/servers/{name}/Stopped",
                              "Boost a server": "/servers/{name}/preparing",
                              "server_Prepared": "/servers/{name}/prepared",
                              "server_owner": "/servers/{name}/owner",
                              "server_touches": "/servers/{name}/touches",
                              "CPU/RAM Specification": "/servers/{name}/specification",
                              "All states, and count by state": "/states",
                              "Servers is state": "/states/{name}",
                              "Servers needing deboost": "/deboost_jobs",
                              }
                 }
    return call_list

# OPTIONS call result

@view_config(request_method="OPTIONS", routes=['home', 'servers'])
def options(request):
    """ Return the OPTIONS header. """
    # NOTE: This is important for enabling CORS, although under certain
    # circumstances the browser doesn' appear to need it. Might be worth
    # examining why.
    resp = Response(None)
    resp.headers['Allow'] = "HEAD,GET,OPTIONS"
    return resp

@view_config(request_method="OPTIONS", routes=['server', 'server_specification'])
@view_config(request_method="OPTIONS", routes=['server_by_id', 'server_by_id_specification'])
def options2(request):
    resp = Response(None)
    resp.headers['Allow'] = "HEAD,GET,POST,OPTIONS"
    return resp

@view_config(request_method="OPTIONS", routes=["server_" + x for x in server.get_state_list()])
@view_config(request_method="OPTIONS", routes=["server_by_id_" + x for x in server.get_state_list()])
@view_config(request_method="OPTIONS", routes=['server_extend_boost', 'server_by_id_extend_boost'])
def options3(request):
    resp = Response(None)
    resp.headers['Allow'] = "HEAD,POST,OPTIONS"
    return resp

# End of OPTIONS guff

@view_config(request_method="GET", route_name='users', renderer='json', permission="use")
def retrieve_users(request):
    """Return details for all users on the system.  Basically the same as calling /users/x
       for all users, but missing the credit info.
    """
    res = []
    for user_id in server.list_user_ids():
        res.append(server.check_user_details(user_id))

    return res

@view_config(request_method="PUT", route_name='user', renderer='json', permission="administer")
def create_user(request):
    """ Create a user in the database. """
    #FIXME - the UUID for a user should be the e-mail address.  Can we make this explicit?
    newname = server.create_user(request.POST['type'], request.POST['handle'], request.POST['name'], request.matchdict['name'])
    return newname

@view_config(request_method="GET", route_name='user', renderer='json', permission="use")
def retrieve_user(request):
    """Return account details for any user.  Anybody should be able to do this,
       though most users have no need to.

    :param name: The user we are interested in.
    :returns JSON object containing user table data.
    """
    username = request.matchdict['name']
    try:
        actor_id = server.get_user_id_from_name(username)
        details = server.check_user_details(actor_id)
        details.update({'credits' : server.check_credit(actor_id)})
        return details
    except KeyError:
        return HTTPNotFound()

@view_config(request_method="GET", route_name='my_user', renderer='json', permission="use")
def retrieve_my_user(request):
    """Return account details for logged-in user.

    :param name: The user we are interested in.
    :returns JSON object containing user table data.
    """
    username = request.authenticated_userid
    try:
        actor_id = server.get_user_id_from_name(username)
        details = server.check_user_details(actor_id)
        details.update({'credits' : server.check_credit(actor_id)})
        return details
    except KeyError:
        #Should be impossible unless a logged-in user is deleted.
        return HTTPInternalServerError()

@view_config(request_method="PATCH", route_name='user', renderer='json', permission="administer")
def update_user(request):
    # FIXME: Not implemented.
    response = HTTPNotImplemented()
    return response

@view_config(request_method="DELETE", route_name='user', renderer='json', permission="administer")
def delete_user(request):
    # FIXME: Not implemented. Some thought needs to go into this. I think a
    # deletion flag would be appropriate, but this will involve changing quite
    # a number of queries.
    # Tim thinks - makbe just lock the password and remove all machines?
    response = HTTPNotImplemented()
    return response

@view_config(request_method="PUT", route_name='user_password', renderer='json', permission="administer")
def create_user_password(request):
    """ Creates a password for the user given. """
    username = request.matchdict['name']
    actor_id = server.get_user_id_from_name(username)
    newname = server.touch_to_add_password(actor_id, request.POST['password'])
    #FIXME - should we not just return OK?
    return newname

@view_config(request_method="PUT", route_name='my_password', renderer='json', permission="use")
def create_my_password(request):
    """ Creates a password for the user given. """
    username = request.authenticated_userid
    actor_id = server.get_user_id_from_name(username)
    newname = server.touch_to_add_password(actor_id, request.POST['password'])
    #FIXME - should we not just return OK?
    #FIXME2 - also should this not be a POST?
    return newname

@view_config(request_method="GET", route_name='user_touches', renderer='json', permission="use")
def retrieve_user_touches(request):
    # FIXME - Not implemented.
    name = request.matchdict['name']
    return name

@view_config(request_method="POST", route_name='user_credit', renderer='json', permission="administer")
def create_user_credit(request):
    """Adds credit to a user account, negative or positive.  Only an administrator can do this
       directly.  Boost and Deboost actions will do this implicitly.

    Checks if username is valid, otherwise throws HTTP 404.
    Checks if credit is an integer, otherwise throws HTTP 400.

    :param name: User for which we are amending credit.
    :returns: JSON containing actor id, credit change and new balance.
    """
    username, credit = request.matchdict['name'], request.POST['credit']
    try:
        user_id = server.get_user_id_from_name(username)
        server.touch_to_add_credit(user_id, int(credit))
        credits = server.check_credit(user_id)
        return  {'actor_id': int(user_id),
                 'credit_change': int(credit),
                 'credit_balance': int(credits)}
    except ValueError:
        return HTTPBadRequest()
    except KeyError:
        return HTTPNotFound()

# Not sure if Ben was in the process of folding credit balance into user details
# or splitting it out.  I vote for folding it in.
# DELETEME
#
# @view_config(request_method="GET", route_name='my_credit', renderer='json', permission="use")
# def retrieve_my_credit(request):
#     """Return credits outstanding for current user.
#
#     :returns: JSON containing actor_id and current balance.
#     """
#     username = request.authenticated_userid
#     actor_id = server.get_user_id_from_name(username)
#     # actor_id should be valid
#     credits = server.check_credit(actor_id)
#     return  { 'actor_id': actor_id,
#               'credit_balance': int(credits)}

# FIXME - should just return credit to match the POST above.
@view_config(request_method="GET", route_name='user_credit', renderer='json', permission="act")
def retrieve_user_credit(request):
    """Return credits outstanding for any user.

    :param name: User for which we are checking credit.
    :returns: JSON containing actor_id and current balance.
    """
    username = request.matchdict['name']
    try:
        user_id = server.get_user_id_from_name(username)
        credits = server.check_credit(user_id)
        return  {'actor_id': user_id,
                 'credit_balance': int(credits)}
    except KeyError as e:
        return HTTPNotFound(str(e))

@view_config(request_method="GET", route_name='servers', renderer='json', permission="use")
def retrieve_servers(request):
    """
    Lists all artifacts related to the current user.
    """
    user_id = server.get_user_id_from_name(request.authenticated_userid)
    server_list = server.list_artifacts_for_user(user_id)
    return list(server_list)

@view_config(request_method="GET", route_name='states', renderer='json', permission="use")
def retrieve_server_counts_by_state(request):
    """
    List all states and the number of servers in that state.
    """
    #Note that with the current DB schema, having the separate state and states calls is silly
    #because both retrieve the same info from the DB then selectively throw bits away.
    server_table = server.list_servers_by_state()

    all_states = server.get_state_list()

    #Not so good - we'd like to report all valid states...
    #return { k: len(v) for k, v in server_table }

    #Better...
    return { s: len(server_table.get(s, ())) for s in all_states }

@view_config(request_method="GET", route_name='state', renderer='json', permission="use")
def retrieve_servers_in_state(request):
    """
    Lists all servers in a given state.
    """
    server_ids = server.list_servers_by_state().get(request.matchdict['name'],())
    server_uuid = [ server.get_server_uuid_from_id(s_id) for s_id in server_ids ]
    server_name = [ server.get_server_name_from_id(s_id) for s_id in server_ids ]
    return [ { "artifact_id"   : s[0],
               "artifact_uuid" : s[1],
               "artifact_name" : s[2] }
             for s in zip(server_ids, server_uuid, server_name) ]

@view_config(request_method="PUT", route_name='server', renderer='json', permission="administer")
def create_server(request):
    """
    Creates a new artifact record in the database.
    """
    newname = server.create_appliance(request.matchdict['name'], request.POST['uuid'])
    return newname

@view_config(request_method="GET", routes=['server', 'server_by_id'], renderer='json', permission="use")
def retrieve_server(request):
    """
    Gets artifact details from the server, based on the name or the internal ID.
    """
    vm_id, actor_id = _resolve_vm(request)
    server_details = server.return_artifact_details(vm_id)
    return server_details

@view_config(request_method="PATCH", route_name='server', renderer='json', permission="use")
def update_server(request):
    # FIXME: Not implemented. Do we want this to be implemented?
    response = HTTPNotImplemented()
    return response

@view_config(request_method="DELETE", route_name='server', renderer='json', permission="use")
def delete_server(request):
    # FIXME: Not implemented. Again, this needs thought. Probably logical
    # deletion through a "deleted" flag.
    # Or else, add a new server with the same name and blank UUID, as currently for multiple
    # servers with the same name we only see the last.
    response = HTTPNotImplemented()
    return response

@view_config(request_method="PUT", route_name='server_owner', renderer='json', permission="use")
def create_server_owner(request):
    """ Calls touch_to_add_ownership to add an owner to the server. """
    # FIXME: There is the problem of servers being able to have multiple
    # owners in the current system. Again, we may need a logical deletion
    # flag. On reflection, I'd like to suggest that we add a logical deletion
    # flag to the Resource class, as it'll be inherited by all resources,
    # and solves multiple problems in one place.
    newname = server.touch_to_add_ownership(request.matchdict['name'], request.POST['actor_id'])
    return newname

@view_config(request_method="GET", route_name='server_owner', renderer='json', permission="use")
def get_server_owner(request):
    # Not implemented. Check if necessary.  A server can have many owners.
    return HTTPNotImplemented()

def _resolve_vm(request):
    """Function given a request works out the VM we are talking about and whether
       the current user actually has permission to do stuff to it.
       Also returns the internal ID for the user, as well as the VM.
    """

    actor_id = None
    vm_id = None
    try:
        actor_id = server.get_user_id_from_name(request.authenticated_userid)
    except:
        #OK, it must be an agent or an internal call.
        pass
    try:
        vm_id = ( request.matchdict['id']
                  if 'id' in request.matchdict else
                  server.get_server_id_from_name(request.matchdict['name']) )
    except:
        #Presumably because there is no such VM
        raise HTTPNotFound()

    if ( request.has_permission('act') or
         server.check_ownership(vm_id, actor_id) ):
        return vm_id, actor_id
    else:
        raise HTTPUnauthorized()

@view_config(request_method="GET", routes=['server_state', 'server_by_id_state'],
             renderer='json', permission="use")
def server_state(request):
    """Get the status for a server.  Anyone can request this,

    :param name: Name of VApp which we want to stop.
    :returns: The state, by name.
    """
    vm_id, actor_id = _resolve_vm(request)
    return server.check_state(vm_id)

def _set_server_state(request, target_state):
    """Basic function for putting a server into some state, for basic state-change calls."""
    vm_id, actor_id = _resolve_vm(request)
    return {"vm_id": vm_id,
            "touch_id": server.touch_to_state(actor_id, vm_id, target_state)}

#Pyramid is not designed to allow you to add view configurations programatically.
#But in Python all things are possible.  Here is a way to set up view configurations in a loop.
#This will declare the functions "set_server_to_Boosting", etc...
#And bind them to the routes "server_Boosting" and "server_by_id_Boosting"

### Here are the states that can only be set by agents...
for state in ['Stopped', 'Started', 'Prepared', 'Pre_Deboosted',
              'Boosting', 'Deboosting', 'Starting_Boosted' ]:
     funcname = 'set_server_to_' + state
     globals()[funcname] = lambda request, state=state: _set_server_state(request, state)
     globals()[funcname] = view_config( request_method="POST",
                                        routes=['server_' + state, 'server_by_id_' + state],
                                        renderer='json',
                                        permission="act"
                                      )( globals()[funcname] )
     globals()[funcname].__name__ = funcname
     globals()[funcname].__qualname__ = funcname

### States that any user can put their server into...
for state in ['Starting', 'Stopping', 'Restarting', 'Error']:
     funcname = 'set_server_to_' + state
     globals()[funcname] = lambda request, state=state: _set_server_state(request, state)
     globals()[funcname] = view_config( request_method="POST",
                                        routes=['server_' + state, 'server_by_id_' + state],
                                        renderer='json',
                                        permission="use"
                                      )( globals()[funcname] )
     globals()[funcname].__name__ = funcname
     globals()[funcname].__qualname__ = funcname

### Any user can Boost, but it will cost.
@view_config(request_method="POST", routes=['server_Preparing', 'server_by_id_Preparing'],
             renderer='json', permission="use")
def boost_server(request):
    """Boost a server: ie:
        Debit the users account
        Schedule a De-Boost
        Set the CPUs and RAM
        Put the server in a "preparing" status

    :param {vm or name}: ID of VApp which we want to boost.
    :ram: ram wanted
    :cores: cores wanted
    :hours: hours of boost wanted
    :returns: JSON containing VApp ID and job ID for progress calls.
    """
    vm_id, actor_id = _resolve_vm(request)

    hours = int(request.POST['hours'])
    cores = int(request.POST['cores'])
    ram   = int(request.POST['ram'])

    # FIXME: Really the user should boost to a named level, rather than directly
    # specifying RAM and cores.  For now I'm just going to work out the cost based
    # on the cores requested, and assume the RAM level matches it.
    cost = server.check_and_remove_credits(actor_id, ram, cores, hours)

    if not cost:
        #Either we can't afford it or we can't determine the cost.
        return HTTPBadRequest();

    #Schedule a de-boost
    server.touch_to_add_deboost(vm_id, hours)

    # Set spec
    server.touch_to_add_specification(vm_id, cores, ram)

    # Tell the agents to get to work.
    touch_id = server.touch_to_state(actor_id, vm_id, "Preparing")

    return dict(touch_id=touch_id, vm_id=vm_id, cost=cost)

# Likewise any user can deboost.
@view_config(request_method="POST", routes=['server_Pre_Deboosting', 'server_by_id_Pre_Deboosting'],
             renderer='json', permission="use")
def deboost_server(request):
    """Deboost a server: ie:
        Credit the users account
        Cancel any scheduled De-Boost
        Set the CPUs and RAM to the previous state
        Put the server in a "Pre_Deboosting" status

    Note that a user can Deboost at ANY time, but they only get credit if credit is due.
    Deboosting a non-boosted server just amounts to a restart.

    :param {vm or name}: ID of VApp which we want to deboost.
    :returns: ???
    """
    vm_id, actor_id = _resolve_vm(request)

    credit = server.get_time_until_deboost(vm_id)[3]
    server.touch_to_add_credit(actor_id, credit)

    #Scheduled timeouts don't need cancelling as they are ignored on unboosted servers.

    #FIXME - yet more hard-coding for cores/RAM
    prev_cores = 1
    prev_ram = 16
    try:
        prev_cores, prev_ram = server.get_previous_specification(vm_id)
    except:
        #OK, use the defaults.
        pass

    #If we're not careful, with this "go back to previous config" semantics, if a user de-boosts
    #a server twice they will actually end up setting their baseline config to the boosted specs.
    #Therefore do a check.
    current_cores, current_ram = server.get_latest_specification(vm_id)

    if not (prev_ram > current_ram):
        server.touch_to_add_specification(vm_id, prev_cores, prev_ram)

    # Tell the agents to get to work.
    touch_id = server.touch_to_state(actor_id, vm_id, "Pre_Deboosting")

    return dict(touch_id=touch_id, vm_id=vm_id, credit=credit)

@view_config(request_method="POST", routes=['server_extend_boost', 'server_by_id_extend_boost'],
             renderer='json', permission="use")
def extend_boost_on_server(request):
    """Extends the Boost period on a server by adding a new deboost timeout, if
       the user can afford it, and debiting the cost.
    """
    vm_id, actor_id = _resolve_vm(request)
    hours = int(request.POST['hours'])

    #See what level of boost we have just now.  Again, need to FIXME that hard-coding
    cores, ram = server.get_latest_specification(vm_id)

    cost = server.check_and_remove_credits(actor_id, ram, cores, hours)

    if not cost:
        #Either we can't afford it or we can't determine the cost.
        return HTTPBadRequest();

    #Work out when the new de-boost should be.  First get the remaining boost time as
    #hours.  It's unlikely to be a whole number.  If the boost has expired somehow then
    #don't be mean - count from now.
    remaining_time = (server.get_time_until_deboost(vm_id)[1] or 0) / 3600.0
    if remaining_time < 0 : remaining_time = 0

    #Schedule a later de-boost
    server.touch_to_add_deboost(vm_id, hours + remaining_time)

    return dict(vm_id=vm_id, cost=cost)

# Find out what needs de-boosting (agents only)
@view_config(request_method="GET", route_name='deboosts', renderer='json', permission="act")
def deboost_jobs(request):
    """ Calls get_deboost_jobs, which is what the deboost_daemon needs in order to work.
        Defaults to getting all deboosts that expired within the last 60 minutes.
    """
    past = int(request.params.get('past', 60))
    future = int(request.params.get('future', 0))

    return server.get_deboost_jobs(past, future)

@view_config(request_method="GET", route_name='server_touches', renderer='json', permission="use")
def retrieve_server_touches(request):
    """ Retrieve activity log from recent touches. """
    # FIXME - Clearly this hasn't been implemented.
    name = request.matchdict['name']
    return name

@view_config(request_method="POST", renderer='json', permission="act",
             routes=['server_specification', 'server_by_id_specification'])
def set_server_specification(request):
    """ Set number of cores and amount of RAM for a VM. These numbers should
        only match the given specification types listed below.
        Regular users can only do this indirectly via boost/deboost.
    """
    vm_id, actor_id = _resolve_vm(request)

    # FIXME - This really shouldn't be hardcoded.
    cores = request.POST.get('cores')
    ram = request.POST.get('ram')
    if (cores not in ['1', '2', '4', '16']) or (ram not in ['1', '4', '8', '16', '400']):
        return HTTPBadRequest()
    else:
        server.touch_to_add_specification(vm_id, cores, ram)
        return dict(cores=cores, ram=ram, artifact_id=vm_id)

@view_config(request_method="GET", renderer='json', permission="use",
             routes=['server_specification', 'server_by_id_specification'])
def get_server_specification(request):
    """ Get the specification of a machine. Returns RAM in GB and number of
    cores in a JSON object."""
    vm_id, actor_id = _resolve_vm(request)

    cores, ram = server.get_latest_specification(vm_id)
    return dict(cores=cores, ram=ram, artifact_id=vm_id)


text:
<?php
/**
 * @covers \com\github\gooh\InterfaceDistiller\Filters\NoMagicMethodsIterator
 */
namespace com\github\gooh\InterfaceDistiller\Filters;

class NoMagicMethodsIteratorTest extends FilterIteratorTestCase
{
    public function testIteratorWillFilterMagicMethods()
    {
        $this->assertFilterIteratorContains(
            $this->addTraitMethodWhenSupported(
                array(
                    $this->getTestClassMethod('foo'),
                    $this->gettestClassMethod('TestClass'),
                    $this->getTestClassMethod('implementedMethod'),
                    $this->getTestClassMethod('inheritedMethod'),
                    $this->gettestClassMethod('SomeClass')
                )
            )
        );
    }
}


text:
package org.terracotta.management.integration.tests;

import org.junit.Test;
import org.terracotta.management.model.cluster.Server;
import org.terracotta.management.model.stats.ContextualStatistics;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Mathieu Carbou
 */
public class HAStatisticsIT extends AbstractHATest {

  @Test
  public void can_do_remote_management_calls_on_servers() throws Exception {
    try {
      triggerServerStatComputation();

      Set<String> servers = new HashSet<>();

      queryAllRemoteStatsUntil(stats -> {

        for (ContextualStatistics stat : stats) {
          String serverName = stat.getContext().get(Server.NAME_KEY);
          servers.add(serverName);
        }

        // counters are ok, we ensure we got them from both servers
        return servers.size() == 2;
      });
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

  @Test
  public void test_passive_stats() throws Exception {
    try {
      triggerServerStatComputation();

      //System.out.println("put(pet1=Cubitus)");
      put(0, "pets", "pet1", "Cubitus"); // put on both active and passive

      Set<String> servers = new HashSet<>();

      queryAllRemoteStatsUntil(stats -> {

        // do another put
        put(0, "pets", "pet1", "Cubitus"); // put on both active and passive

        for (ContextualStatistics stat : stats) {
          // only consider stats for pet-clinic/pets
          if(stat.getContext().get("alias").equals("pet-clinic/pets")) {
            String serverName = stat.getContext().get(Server.NAME_KEY);
            //System.out.println("server: " + serverName);

            Number counter = stat.getStatistic("Cluster:PutCount");
            //System.out.println("counterHistory: " + counterHistory.getLast().getValue());

            // if the counter history is not yet 1, return false, we continue looping
            if (counter.longValue()< 1L) {
              return false;

            } else {
              // to be sure we receive stats from 2 servers
              servers.add(serverName);
            }
          }
        }

        // counters are ok, we ensure we got them from both servers
        return servers.size() == 2;
      });
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

}


text:
<?php

class Dao_Base_UserFilterCount implements Dao_UserFilterCount {
	protected $_conn;

	/*
	 * constructs a new Dao_Base_UserFilterCount object,
	 * connection object is given
	 */
	public function __construct(dbeng_abs $conn) {
		$this->_conn = $conn;
	} # ctor

	/*
	 * Add a filter count for a specific SHA1 hash
	 * of a filter for this specific user
	 */
	function setCachedFilterCount($userId, $filterHashes) {
		$maxSpotStamp = $this->_conn->singleQuery("SELECT MAX(stamp) AS stamp FROM spots");
		if ($maxSpotStamp == null) {
			$maxSpotStamp = time();
		} # if

		foreach($filterHashes as $filterHash => $filterCount) {
			/* Remove any existing cached filtercount for this user */
			$this->_conn->modify("DELETE FROM filtercounts WHERE (userid = :userid) AND (filterhash = :filterhash)",
                array(
                    ':userid' => array($userId, PDO::PARAM_INT),
                    ':filterhash' => array($filterHash, PDO::PARAM_STR)
                ));

			/* and insert our new filtercount hash */
			$this->_conn->modify("INSERT INTO filtercounts(userid, filterhash, currentspotcount, lastvisitspotcount, lastupdate)
											VALUES(:userid, :filterhash, :currentspotcount, :lastvisitspotcount, :lastupdate)",
                array(
                    ':userid' => array($userId, PDO::PARAM_INT),
                    ':filterhash' => array($filterHash, PDO::PARAM_STR),
                    ':currentspotcount' => array($filterCount['currentspotcount'], PDO::PARAM_INT),
                    ':lastvisitspotcount' => array($filterCount['lastvisitspotcount'], PDO::PARAM_INT),
                    ':lastupdate' => array($maxSpotStamp, PDO::PARAM_INT)
                ));
		} # foreach
	} # setCachedFilterCount

	/*
	 * Add a filter count for a specific SHA1 hash
	 * of a filter for this specific user
	 */
	function getNewCountForFilters($userId) {
		$filterHashes = array();
		$tmp = $this->_conn->arrayQuery("SELECT f.filterhash AS filterhash,
												f.currentspotcount AS currentspotcount,
												f.lastvisitspotcount AS lastvisitspotcount,
												f.lastupdate AS lastupdate,
												t.currentspotcount - f.lastvisitspotcount AS newspotcount
										 FROM filtercounts f
										 INNER JOIN filtercounts t ON (t.filterhash = f.filterhash)
										 WHERE t.userid = -1
										   AND f.userid = :userid",
            array(
                ':userid' => array($userId, PDO::PARAM_INT)
            ));

		foreach($tmp as $cachedItem) {
			$filterHashes[$cachedItem['filterhash']] = array('currentspotcount' => $cachedItem['currentspotcount'],
															 'lastvisitspotcount' => $cachedItem['lastvisitspotcount'],
															 'newspotcount' => $cachedItem['newspotcount'],
															 'lastupdate' => $cachedItem['lastupdate']);
		} # foreach

		return $filterHashes;
	} # getNewCountForFilters

	/*
	 * Makes sure all registered users have at least counts
	 * for all existing filters.
	 */
	function createFilterCountsForEveryone() {
		$userIdList = $this->_conn->arrayQuery('SELECT id FROM users WHERE id <> -1');

		foreach($userIdList as $user) {
			$userId = $user['id'];

			/* Get the list of filters */
			$filterList = $this->_conn->arrayQuery("SELECT id,
														  userid,
														  filtertype,
														  title,
														  icon,
														  torder,
														  tparent,
														  tree,
														  valuelist,
														  sorton,
														  sortorder,
														  enablenotify
													FROM filters
													WHERE userid = :userid
													ORDER BY tparent, torder",
                array(
                    ':userid' => array($userId, PDO::PARAM_INT)
                ));

			/* We can assume userid -1 (baseline) has all the filters which exist */
			$cachedList = $this->getCachedFilterCount($userId);

			/* We add a dummy entry for 'all new spots' */
			$filterList[] = array('id' => 9999, 'userid' => $userId, 'filtertype' => 'dummyfilter',
								'title' => 'NewSpots', 'icon' => '', 'torder' => 0, 'tparent' => 0,
								'tree' => '', 'valuelist' => 'New:0', 'sorton' => '', 'sortorder' => '',
								'enablenotify' => false);

			foreach($filterList as $filter) {
				$filterHash = sha1($filter['tree'] . '|' . urldecode($filter['valuelist']));

				# Do we have a cache entry already for this filter?
				if (!isset($cachedList[$filterHash])) {
					/*
					 * Create the cached count filter
					 */
					$filter['currentspotcount'] = 0;
					$filter['lastvisitspotcount'] = 0;

					$this->setCachedFilterCount($userId, array($filterHash => $filter));
				} # if
			} # foreach
		} # foreach
	} # createFilterCountsForEveryone

	/*
	 * Retrieves the filtercount for a specific userid
	 */
	function getCachedFilterCount($userId) {
		$filterHashes = array();
		$tmp = $this->_conn->arrayQuery("SELECT filterhash,
		                                        currentspotcount,
		                                        lastvisitspotcount,
		                                        lastupdate
		                                   FROM filtercounts
		                                  WHERE userid = :userid",
            array(
                ':userid' => array($userId, PDO::PARAM_INT)
            ));

		foreach($tmp as $cachedItem) {
			$filterHashes[$cachedItem['filterhash']] = array('currentspotcount' => $cachedItem['currentspotcount'],
															 'lastvisitspotcount' => $cachedItem['lastvisitspotcount'],
															 'lastupdate' => $cachedItem['lastupdate']);
		} # foreach

		return $filterHashes;
	} # getCachedFilterCount

	/*
	 * Resets the unread count for a specific user
	 */
	function resetFilterCountForUser($userId) {
		$filterList = $this->_conn->arrayQuery("SELECT currentspotcount, filterhash FROM filtercounts WHERE userid = -1", array());
		foreach($filterList as $filter) {
			$this->_conn->modify("UPDATE filtercounts
										SET lastvisitspotcount = currentspotcount,
											currentspotcount = :currentspotcount
										WHERE (filterhash = :filterhash)
										  AND (userid = :userid)",
                array(
                    ':currentspotcount' => array($filter['currentspotcount'], PDO::PARAM_INT),
                    ':filterhash' => array($filter['filterhash'], PDO::PARAM_STR),
                    ':userid' => array($userId, PDO::PARAM_INT)
                ));
		} # foreach
	} # resetFilterCountForUser

	/*
	 * Updates the last filtercounts for sessions which are active at the moment
	 */
	function updateCurrentFilterCounts() {
		/*
		 * Update the current filter counts if the session
		 * is still active
		 */
		$filterList = $this->_conn->arrayQuery("SELECT currentspotcount,
		                                               lastupdate,
		                                               filterhash
		                                          FROM filtercounts
		                                          WHERE userid = -1");
		foreach($filterList as $filter) {
			$this->_conn->modify("UPDATE filtercounts
										SET currentspotcount = :currentspotcount,
											lastupdate = :lastupdate
										WHERE (filterhash = :filterhash)
										  AND (userid IN (SELECT userid FROM sessions WHERE lasthit > lastupdate GROUP BY userid ))",
                array(
                    ':currentspotcount' => array($filter['currentspotcount'], PDO::PARAM_INT),
                    ':lastupdate' => array($filter['lastupdate'], PDO::PARAM_INT),
                    ':filterhash' => array($filter['filterhash'], PDO::PARAM_INT)
                ));
		} # foreach
	} # updateCurrentFilterCounts

	/*
	 * Mark all filters as read
	 */
	function markFilterCountAsSeen($userId) {
		throw new NotImplementedException();
	} # markFilterCountAsSeen

} # Dao_Base_UserFilterCount


text:
import React from 'react'

import './Chat.scss'
import ChatList from './ChatList'
import ChatInput from './ChatInput'
export default class Chat extends React.Component {
  render() {
    return <div className="chat">
        <ChatInput></ChatInput>
        <ChatList></ChatList>
    </div>
  }
}


text:
(function() {
  'use strict';

  var services = angular.module('app.yuidoc.services');
  services.service('yuidocDataService', function($resource, querifySync, yuidocDataPath) {
    function YuidocDataService() {
      this.dataset_ = null;
      this.loaded = false;
    }

    YuidocDataService.prototype = {
      load: function() {
        var paramDefaults = {};
        var actions = {
          cache: true
        };
        var this_ = this;
        return $resource(yuidocDataPath, paramDefaults, actions)
          .get()
          .$promise
          .then(function(dataset) {
            this_.loaded = true;
            this_.dataset_ = dataset;
          });
      },
      get dataset() {
        if (this.dataset_ === null) {
          throw Error('YuidocDataService: dataset is not loaded.');
        }
        return this.dataset_;
      },
      getProject: function() {
        return this.dataset.project;
      },
      getModules: function() {
        return this.dataset.modules;
      },
      getClasses: function() {
        return this.dataset.classes;
      },
      getClassItems: function() {
        return this.dataset.classitems;
      },
      getGlobalClasses: function() {
        var query = {
          $not: {
            $has: 'module'
          }
        };
        return querifySync.extract(this.dataset.classes, query);
      },
      getClassesByModuleName: function(moduleName) {
        var query = {
          module: moduleName
        };
        return querifySync.extract(this.dataset.classes, query);
      },
      getClassItemsByModuleAndClassName: function(moduleName, className) {
        var query = {
          module: moduleName,
          class: className
        };
        return querifySync.filter(this.dataset.classitems, query);
      }
    };

    return new YuidocDataService();
  });
}());


text:
(function(){

	var $loader = $("#loader-container");
	var $logo = $("#isologo");
	var $descargarExcel = $("#descargarExcel");

	function mostrarLoader() {
		$logo.hide('fade');
		$logo.delay(10000);
		$logo.show('fade');
	}

	function mostrarLogo() {
		$logo.show('fade');
	}
	$( function() {
		mostrarLogo();
	} );

	//$( window ).on("load", mostrarLoader);
	$( window ).on("unload",mostrarLoader);
	$descargarExcel.on("click",mostrarLoader);

	mostrarLogo();

})();


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>MARTIN THEO | Còdi n Camp - Promo 1</title>
    <link rel="stylesheet" href="stylesheet.css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

      Còdi n camp

Promo #1

Biographie

Objectif

Projets

Loisirs

A propos de moi

        NOM : Martin

        PRENOM : Théo

        VILLE : Saint Etienne (42)

        AGE : 22 ans

Biographie

Théo Martin plus connu sous le pseudonyme d'Exohyb est un super-héros née en 1994, ancien ouvrier à Stark Industrie et très vite repérer par Tony Stark pour devenir son successeur.
        Lors de la bataille à New York contre les extraterrestre, son nom ne fut pas citer mais il était présent.

        Citation favorite : Génie Milliardaire Playboy Philanthrope. Tony Stark ;-)

Objectif après Còdi n Camp

J'ai beaucoup d'idées qui me trotte dans la tête, mon objectif principal étant de devenir indépendant en créant ma société.

Projets

Réalisée

Création de serveur de jeux vidéos

Divers sites HTML/CSS & PHP

En cours

Pleins d'idées

Loisirs

Coder

Cinémas

Musiques

Plongé sous-marine

Automobile

  Copyright © - Còdi n Camp - 2015


text:
package com.google.idea.blaze.aspect.scala.scalatest;

import static com.google.common.truth.Truth.assertThat;

import com.google.devtools.intellij.IntellijAspectTestFixtureOuterClass.IntellijAspectTestFixture;
import com.google.devtools.intellij.ideinfo.IntellijIdeInfo.TargetIdeInfo;
import com.google.idea.blaze.BazelIntellijAspectTest;
import com.google.idea.blaze.aspect.IntellijAspectTest;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests scala_test */
@RunWith(JUnit4.class)
public class ScalaTestTest extends BazelIntellijAspectTest {

  @Test
  public void testScalaTest() throws Exception {
    IntellijAspectTestFixture testFixture = loadTestFixture(":footest_fixture");
    TargetIdeInfo testInfo = findTarget(testFixture, ":FooTest");
    assertThat(testInfo.getKindString()).isEqualTo("scala_test");
    assertThat(relativePathsForArtifacts(testInfo.getJavaIdeInfo().getSourcesList()))
        .containsExactly(testRelative("FooTest.scala"));
    assertThat(
            testInfo
                .getJavaIdeInfo()
                .getJarsList()
                .stream()
                .map(IntellijAspectTest::libraryArtifactToString)
                .collect(Collectors.toList()))
        .containsExactly(jarString(testRelative("FooTest.jar"), null, null));

    assertThat(getOutputGroupFiles(testFixture, "intellij-info-java"))
        .contains(testRelative("FooTest.intellij-info.txt"));
    assertThat(getOutputGroupFiles(testFixture, "intellij-resolve-java"))
        .contains(testRelative("FooTest.jar"));
    assertThat(getOutputGroupFiles(testFixture, "intellij-compile-java"))
        .contains(testRelative("FooTest.jar"));
    assertThat(getOutputGroupFiles(testFixture, "intellij-info-generic")).isEmpty();

    assertThat(testInfo.getTestInfo().getSize()).isEqualTo("large");
  }
}


text:
[![Laravel Version](https://shield.with.social/cc/github/Taronyuu/Teamspeak3-server-manager/master.svg?style=flat-square)](https://packagist.org/packages/laravel/framework)

### What is it?
TeamSpeak 3 Server Manager is a simple web application built on Laravel to let users manage their own TeamSpeak servers.
It's been re-written in Laravel 5.5 LTS and still needs a lot of work done but the basics are there.

### What does it do?
Right now it lets you create, delete and edit servers. You can start, stop and restart them. Edit their configuration.
Create and delete tokens. And check how many people are online.

### Requirements
It's built on Laravel 5.5 LTS so check the requirements from their site [https://laravel.com/docs/5.5#server-requirements](https://laravel.com/docs/5.5#server-requirements), plus;
1. TeamSpeak 3 server
2. Web server (nginx, Apache, or similar)

### Installation
1. Clone or download this repo
    `git clone https://github.com/Taronyuu/Teamspeak3-server-manager.git`
2. Setup your environment vars using `.env` or similar (Apache vars, php-fpm vars). You can copy the `.env.example` file.
3. Run composer install
    `composer install`
4. Make sure `DB_CONNECTION` is set to sqlite!
5. Create an empty file named `database.sqlite` in the database folder. `database/database.sqlite`.
6. Run `php artisan migrate` to migrate the database
7. Install or make sure your TeamSpeak 3 server is running. Doing this is outside the scope of this readme file.
8. Run `php artisan teamspeak:sync` to sync the virtual servers and settings into the system.
9. Go to the URL you have setup and you should be able to register your new account.
10. Enjoy

### TeamSpeak Commands
We provide a small number of commands which you can use to complete your panel.

Command: `php artisan teamspeak:reset`
Description: **DANGEROUS** command, this will remove **all** your TeamSpeak server from the TeamSpeak 3 instance and database.

Command: `php artisan teamspeak:sync`
Description: This command will synchronize all the servers with your database and the TeamSpeak 3 instance itself.

### Can you add....?
Of course! Please open an issue. we'll be more than happy to add/discuss features. :)

### Screens:
#### Log in:
![Log in](https://snapr.pw/i/59df643509.png "Log in")
#### Dashboard:
![Dashboard](https://snapr.pw/i/9054ea0fa0.png "Dashboard")
#### Servers list:
![Servers list](https://snapr.pw/i/d0c971ccf1.png "Servers list")
#### Server overview:
![Server overview v1](https://snapr.pw/i/14920dcb75.png "Server overview v1")
![Server overview v2](https://snapr.pw/i/b9db69baf5.png "Server overview v2")
#### Create server:
![Create server](https://snapr.pw/i/527944c590.png "Create server")


text:
				<form class="form-horizontal" id="formRiwayatPKM" method="post">

						Nama PKM

							<input name="nama_pkm" class="form-control" id="inputNamaPKM" required="" type="text" placeholder="Nama PKM" value="" autocomplete="off">

						Nama Penyelenggara

							<input name="nama_penyelenggara_pkm" class="form-control" id="inputNamaPeyelenggara" required="" type="text" placeholder="Nama Penyelenggara" value="" autocomplete="off">

						Tahun PKM

							<input name="tahun_pkm" class="form-control" id="inputPKM" required="" type="text" placeholder="Tahun PKM" value="" autocomplete="off" pattern="[0-9]{4,4}" title="Format Tahun : YYYY, contoh : 2016">

						PKM Kemahasiswaan

									<input name="pkm_kemahasiswaan" required="" type="radio" value=1>
									Ya

									<input name="pkm_kemahasiswaan" required="" type="radio" value=0>
									Tidak

							<?php echo form_submit('', 'Submit', array('class' => 'btn btn-primary')); ?>

				</form>


text:
package com.sequenceiq.it.cloudbreak.cloud.v4.gcp;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform;
import com.sequenceiq.it.cloudbreak.cloud.v4.AbstractCloudProviderAssertion;

@Component
public class GcpCloudProviderAssertion extends AbstractCloudProviderAssertion {

    @Override
    public CloudPlatform getCloudPlatform() {
        return CloudPlatform.GCP;
    }

}


text:
import scala.reflect.runtime.universe._

class PlaceboParameterZoo {
  class C[@placebo T](@placebo val x: Int)
  object С
  def m[@placebo T, @placebo U](@placebo x: Int)(@placebo y: Int) = ???
  type T[@placebo U] = U
}

class PlaceboParameters {
  def assertEquals(a: Any, b: Any): Unit = { assert(a == b, s"$a != $b") }

  // @Test
  def combo: Unit = {
    assertEquals(typeOf[PlaceboParameterZoo].decls.sorted.map(_.toString).mkString("\n"), """
      |constructor PlaceboParameterZoo
      |class C
      |object С
      |method m
      |type T
    """.trim.stripMargin)
  }
}


text:
namespace System.Data.ProviderBase
{
    sealed internal partial class DbConnectionPoolIdentity
    {
        public static readonly DbConnectionPoolIdentity NoIdentity = new DbConnectionPoolIdentity(string.Empty, false, true);

        private readonly string _sidString;
        private readonly bool _isRestricted;
        private readonly bool _isNetwork;
        private readonly int _hashCode;

        private DbConnectionPoolIdentity(string sidString, bool isRestricted, bool isNetwork)
        {
            _sidString = sidString;
            _isRestricted = isRestricted;
            _isNetwork = isNetwork;
            _hashCode = sidString == null ? 0 : sidString.GetHashCode();
        }

        internal bool IsRestricted
        {
            get { return _isRestricted; }
        }

        override public bool Equals(object value)
        {
            bool result = ((this == NoIdentity) || (this == value));
            if (!result && (null != value))
            {
                DbConnectionPoolIdentity that = ((DbConnectionPoolIdentity)value);
                result = ((_sidString == that._sidString) && (_isRestricted == that._isRestricted) && (_isNetwork == that._isNetwork));
            }
            return result;
        }

        override public int GetHashCode()
        {
            return _hashCode;
        }

        internal static DbConnectionPoolIdentity GetCurrentManaged()
        {
            string sidString = (!string.IsNullOrWhiteSpace(System.Environment.UserDomainName) ? System.Environment.UserDomainName + "\\" : "")
                                + System.Environment.UserName;
            bool isNetwork = false;
            bool isRestricted = false;
            return new DbConnectionPoolIdentity(sidString, isRestricted, isNetwork);
        }
    }
}


text:
package com.hcl.bigchaindbDriver;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * Utility to use the Kalium library to produce key pairs and wrap them in adaptors for Java KeyPair, PublicKey and
 * PrivateKey
 *

 * Created by Mark Grand on 2/21/2017.
 */
class KaliumKeyPairUtil {

    static KeyPair generateKeyPair() {
        final org.abstractj.kalium.keys.KeyPair kaliumKeyPair = new org.abstractj.kalium.keys.KeyPair();
        return new KeyPair(new KaliumPublicKey(kaliumKeyPair.getPublicKey()),
                                  new KaliumPrivateKey(kaliumKeyPair.getPrivateKey()));
    }

    private static class KaliumPublicKey implements PublicKey {
        private final org.abstractj.kalium.keys.PublicKey kaliumPublicKey;

        KaliumPublicKey(org.abstractj.kalium.keys.PublicKey kaliumPublicKey) {
            this.kaliumPublicKey = kaliumPublicKey;
        }

        /**
         * Returns the standard algorithm name for this key. For
         * example, "DSA" would indicate that this key is a DSA key.
         * See Appendix A in the
         * Java Cryptography Architecture API Specification & Reference
         * for information about standard algorithm names.
         *
         * @return the name of the algorithm associated with this key.
         */
        @Override
        public String getAlgorithm() {
            return "EdDSA";
        }

        /**
         * Returns the name of the primary encoding format of this key,
         * or null if this key does not support encoding.
         * The primary encoding format is
         * named in terms of the appropriate ASN.1 data format, if an
         * ASN.1 specification for this key exists.
         * For example, the name of the ASN.1 data format for public
         * keys is SubjectPublicKeyInfo, as
         * defined by the X.509 standard; in this case, the returned format is
         * {@code "X.509"}. Similarly,
         * the name of the ASN.1 data format for private keys is
         * PrivateKeyInfo,
         * as defined by the PKCS #8 standard; in this case, the returned format is
         * {@code "PKCS#8"}.
         *
         * @return the primary encoding format of the key.
         */
        @Override
        public String getFormat() {
            return "X.509";
        }

        /**
         * Returns the key in its primary encoding format, or null
         * if this key does not support encoding.
         *
         * @return the encoded key, or null if the key does not support encoding.
         */
        @Override
        public byte[] getEncoded() {
            return kaliumPublicKey.toBytes();
        }
    }

    private static class KaliumPrivateKey implements PrivateKey {
        private final org.abstractj.kalium.keys.PrivateKey kaliumPrivateKey;

        KaliumPrivateKey(org.abstractj.kalium.keys.PrivateKey kaliumPrivateKey) {
            this.kaliumPrivateKey = kaliumPrivateKey;
        }

        /**
         * Returns the standard algorithm name for this key. For
         * example, "DSA" would indicate that this key is a DSA key.
         * See Appendix A in the
         * Java Cryptography Architecture API Specification & Reference
         * for information about standard algorithm names.
         *
         * @return the name of the algorithm associated with this key.
         */
        @Override
        public String getAlgorithm() {
            return "EdDSA";
        }

        /**
         * Returns the name of the primary encoding format of this key,
         * or null if this key does not support encoding.
         * The primary encoding format is
         * named in terms of the appropriate ASN.1 data format, if an
         * ASN.1 specification for this key exists.
         * For example, the name of the ASN.1 data format for public
         * keys is SubjectPublicKeyInfo, as
         * defined by the X.509 standard; in this case, the returned format is
         * {@code "X.509"}. Similarly,
         * the name of the ASN.1 data format for private keys is
         * PrivateKeyInfo,
         * as defined by the PKCS #8 standard; in this case, the returned format is
         * {@code "PKCS#8"}.
         *
         * @return the primary encoding format of the key.
         */
        @Override
        public String getFormat() {
            return "PKCS#8";
        }

        /**
         * Returns the key in its primary encoding format, or null
         * if this key does not support encoding.
         *
         * @return the encoded key, or null if the key does not support encoding.
         */
        @Override
        public byte[] getEncoded() {
            return kaliumPrivateKey.toBytes();
        }
    }
}


text:
package com.taskadapter.redmineapi.internal;

import com.taskadapter.redmineapi.RedmineException;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public final class DirectObjectsSearcher {

    public static <T> ResultsWrapper<T> getObjectsListNoPaging(Transport transport, Map<String, String> map, Class<T> classRef) throws RedmineException {
        final Set<NameValuePair> set = map.entrySet()
                .stream()
                .map(param -> new BasicNameValuePair(param.getKey(), param.getValue()))
                .collect(Collectors.toSet());

        return transport.getObjectsListNoPaging(classRef, set);
    }
}


text:
natural language processing, actually in the browser

    by
    Spencer Kelly and

      many contributors

```javascript
var nlp = require('compromise')

nlp('Wee-ooh, I look just like buddy holly.').sentences().toPastTense()
// 'Wee-ooh, I looked just like buddy holly.'

nlp('..then consider me Miles Davis!').people().out('freq')
// [{ text:'Miles Davis', count:1 }]
```

            210k

                   one javascript file

              86%

                on the Penn treebank

        🙏

              npm install compromise

        IE9+

                  caniuse, youbetcha

  with deliberate, rule-based nlp,

  compromise makes working with text easy

  no jargon,   |   no config,   |   no training

  🙌 you can do it!

  API doc

  Demos

  QuickStart

  Tutorials

                      Part-of-Speech tagging

            nouns! verbs! adjectives!

                            Named-entities

            people, places, organizations

                          Number parsing

            seven hundred and fifty == 750

                    Template-matches

            like a regex for a sentence

                      Verb conjugation

            all your base are belong

                      Transformations

            contractions, style, mood..

#### ⚡ Client-side!
```html
<script src="https://unpkg.com/compromise@latest/builds/compromise.min.js"></script>
<script>
  var doc = nlp('dinosaur')

  var str = doc.nouns().toPlural().out('text')
  console.log(str)
  // 'dinosaurs'
</script>
```

#### 🌋 Server-side!
```javascript
var nlp = require('compromise')

var doc = nlp('London is calling')
doc.sentences().toNegative()
// 'London is not calling'
```

## Toss in text,
even if it's just one word:

Grab a part:

  use built-in methods like .nouns(), or .people() - or query any pattern with .match():

```js
doc = nlp('Ludwig van Beethoven wrote to Josephine Brunsvik')

doc.people().out('list')
// ['ludwig van beethoven', 'josephine brunsvik']

doc.match('#TitleCase van #LastName').out()
// 'Ludwig van Beethoven'

doc.match('#PastTense to').hyphenate().out()
// 'wrote-to'
```

Throw stuff around:

* Plural/singular: - grab the noun-phrases, make em plural:
```javascript
doc = nlp('a bottle of beer on the wall.')
doc.nouns().first().toPlural()
doc.out('text')
//'The bottles of beer on the wall.'
```

* Number parsing: - parse written-out numbers, and change their form:
```javascript
doc = nlp('ninety five thousand and fifty two')
doc.values().toNumber().out('text')
// '95052'

doc = nlp('the 23rd of December')
doc.values().add(2).toText()
doc.out('text')
// 'the twenty fifth of December'
```

* Normalization: - handle the craziness:
```javascript
doc = nlp("the guest-singer's björk   at seven thirty.").normalize().out('text')
// 'The guest singer is Bjork at 7:30.'
```

* Tense: - switch between conjugations of any verb
```javascript
let doc = nlp('she sells seashells by the seashore.')
doc.sentences().toFutureTense().out('text')
//'she will sell seashells...'

doc.verbs().conjugate()
// [{ PastTense: 'sold',
//    Infinitive: 'sell',
//    Gerund: 'selling', ...
// }]
```

*  Named-entities: - get the people, places, organizations:
```javascript
doc = nlp('that opera about richard nixon visiting china')
doc.topics().data()
// [
//   { text: 'richard nixon' },
//   { text: 'china' }
// ]
```

* Error correction: - make it say what you'd like:
```javascript
var lexicon={
  'boston': 'MusicalGroup'
}
doc = nlp('i heard Boston\'s set in Chicago', lexicon)
doc.match('#MusicalGroup').length
// 1

//alternatively, fix it all 'in-post':
doc.match('heard #Possessive set').terms(1).tag('MusicalGroup')
doc.match('#MusicalGroup').length
// 1
```

*  Handy outputs: - get sensible data:
```javascript
doc = nlp('We like Roy! We like Roy!').sentences().out('array')
// ['We like Roy!', 'We like Roy!']

doc = nlp('Tony Hawk').out('html')
/*
<span>
  <span class="nl-Person nl-FirstName">Tony</span>
  <span> </span>
  <span class="nl-Person nl-LastName">Hawk</span>
</span>
*/
```

  and yes, ofcourse, there's a lot more stuff.

  Join in -
  we're fun, using semver, and moving fast.
  get involved

        Twitter

      Slack group

      Mailing-list

        Projects

      Pull-requests

      🌎 Other Languages?

        okay! we've got work-in-progress forks for German and French, in the same philosophy.

        Get involved!

      ☂ Isn't javascript too...

        yeah..

        it wasn't built to compete with the stanford tagger, and may not fit every project.

        all string stuff is synchronous too, and parallelizing is weird.

        See here for information about speed & performance.

      💃 Can it run on my arduino-watch?

        Only if it's water-proof!

        See quickStart for all sorts of funny environments.

      ✨ Partial builds?

        compromise can't really be tree-shaken, because it's one function.

 .. and the tagging methods are competitive, so it's not recommended to pull things out.

        It's best to load the library fully, given it's smaller than this gif.

        A plug-in scheme is in the works.

### Don't forget about:
*   **[naturalNode](https://github.com/NaturalNode/natural)** - decidedly fancier, statistical nlp in javascript
*   **[superScript](http://superscriptjs.com/)** - clever conversation engine in js
*   **[nodeBox Linguistics](https://www.nodebox.net/code/index.php/Linguistics)** - conjugation, inflection in javascript
*   **[reText](https://github.com/wooorm/retext)** - very impressive [text utilities](https://github.com/wooorm/retext/blob/master/doc/plugins.md) in javascript
*   **[jsPos](https://code.google.com/archive/p/jspos/)** - javascript build of the time-tested Brill-tagger
*   **[spaCy](https://spacy.io/)** - speedy, multilingual tagger in C/python

For the former promise-library, see [jnewman/compromise](https://github.com/jnewman/compromise)
(Thanks [Joshua](https://github.com/jnewman)!)

(also don't forget 🙇
NLTK,
GATE,
Stanford,
and
Illinois toolkit
)


text:
package com.itbuzzpress.ejb;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

@Singleton
@Startup
public class UserRegistry {

    @Resource
	TimerService timerService;

	public ArrayList<String> listUsers;
	@PostConstruct
	public void init() {
		listUsers = new ArrayList<String>();
		listUsers.add("administrator");

		timerService.createSingleActionTimer(5000, new TimerConfig());

	}
	public void addUser(String username) {
		listUsers.add(username);
	}
	public void removeUser(String username) {
		listUsers.remove(username);
	}

	public ArrayList<String> getListUsers() {
		return listUsers;
	}
    @Timeout
	public void createReports(javax.ejb.Timer timer){
	   System.out.println("It is time to create a Report!");
	}

    @Schedule(hour = "*", minute = "*", second = "*/60", info ="Every minute timer",persistent=true)
    public void printDate() {

        System.out.println("Schedule invoked at " + new java.util.Date().toString());

    }

}


text:
module.exports.safe = true;

/*
 Purpose:
 Executes a single nested action, reversing the failure expectation
 if the nested action fails, then the error is swallowed and processing continues as successful
 if the nested action does not fail, however, an error is specifically thrown

 Example:
 not:
 {action}
 */

var _ = require("lodash");
var verror = require("verror");

module.exports.normalize = function (action, normalize_action) {
	if (_.has(action, "not")) {
		action.not = normalize_action(action.not, "not");
		return action;
	}
};

module.exports.process = function (context) {
	return context.processAction(this.not).then(() => {
		throw new verror.VError({
			name: "NotConditionFailed"
		}, "not: nested action should not have succeeded");
	}, () => context);
};


text:
<!doctype html>
<meta charset=utf-8>
<title>Textarea rows</title>
<link rel=match href=textarea-ref.html>
<textarea rows=0></textarea>