text:
package org.elasticsearch.action.fieldcaps;

import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.test.AbstractSerializingTestCase;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import static org.hamcrest.Matchers.equalTo;

public class FieldCapabilitiesTests extends AbstractSerializingTestCase<FieldCapabilities> {
    private static final String FIELD_NAME = "field";

    @Override
    protected FieldCapabilities doParseInstance(XContentParser parser) throws IOException {
        return FieldCapabilities.fromXContent(FIELD_NAME, parser);
    }

    @Override
    protected FieldCapabilities createTestInstance() {
        return randomFieldCaps(FIELD_NAME);
    }

    @Override
    protected Writeable.Reader<FieldCapabilities> instanceReader() {
        return FieldCapabilities::new;
    }

    public void testBuilder() {
        FieldCapabilities.Builder builder = new FieldCapabilities.Builder("field", "type");
        builder.add("index1", false, true, false, Collections.emptyMap());
        builder.add("index2", false, true, false, Collections.emptyMap());
        builder.add("index3", false, true, false, Collections.emptyMap());

        {
            FieldCapabilities cap1 = builder.build(false);
            assertThat(cap1.isSearchable(), equalTo(true));
            assertThat(cap1.isAggregatable(), equalTo(false));
            assertNull(cap1.indices());
            assertNull(cap1.nonSearchableIndices());
            assertNull(cap1.nonAggregatableIndices());
            assertEquals(Collections.emptyMap(), cap1.meta());

            FieldCapabilities cap2 = builder.build(true);
            assertThat(cap2.isSearchable(), equalTo(true));
            assertThat(cap2.isAggregatable(), equalTo(false));
            assertThat(cap2.indices().length, equalTo(3));
            assertThat(cap2.indices(), equalTo(new String[]{"index1", "index2", "index3"}));
            assertNull(cap2.nonSearchableIndices());
            assertNull(cap2.nonAggregatableIndices());
            assertEquals(Collections.emptyMap(), cap2.meta());
        }

        builder = new FieldCapabilities.Builder("field", "type");
        builder.add("index1", false, false, true, Collections.emptyMap());
        builder.add("index2", false, true, false, Collections.emptyMap());
        builder.add("index3", false, false, false, Collections.emptyMap());
        {
            FieldCapabilities cap1 = builder.build(false);
            assertThat(cap1.isSearchable(), equalTo(false));
            assertThat(cap1.isAggregatable(), equalTo(false));
            assertNull(cap1.indices());
            assertThat(cap1.nonSearchableIndices(), equalTo(new String[]{"index1", "index3"}));
            assertThat(cap1.nonAggregatableIndices(), equalTo(new String[]{"index2", "index3"}));
            assertEquals(Collections.emptyMap(), cap1.meta());

            FieldCapabilities cap2 = builder.build(true);
            assertThat(cap2.isSearchable(), equalTo(false));
            assertThat(cap2.isAggregatable(), equalTo(false));
            assertThat(cap2.indices().length, equalTo(3));
            assertThat(cap2.indices(), equalTo(new String[]{"index1", "index2", "index3"}));
            assertThat(cap2.nonSearchableIndices(), equalTo(new String[]{"index1", "index3"}));
            assertThat(cap2.nonAggregatableIndices(), equalTo(new String[]{"index2", "index3"}));
            assertEquals(Collections.emptyMap(), cap2.meta());
        }

        builder = new FieldCapabilities.Builder("field", "type");
        builder.add("index1", false, true, true, Collections.emptyMap());
        builder.add("index2", false, true, true, Map.of("foo", "bar"));
        builder.add("index3", false, true, true, Map.of("foo", "quux"));
        {
            FieldCapabilities cap1 = builder.build(false);
            assertThat(cap1.isSearchable(), equalTo(true));
            assertThat(cap1.isAggregatable(), equalTo(true));
            assertNull(cap1.indices());
            assertNull(cap1.nonSearchableIndices());
            assertNull(cap1.nonAggregatableIndices());
            assertEquals(Map.of("foo", Set.of("bar", "quux")), cap1.meta());

            FieldCapabilities cap2 = builder.build(true);
            assertThat(cap2.isSearchable(), equalTo(true));
            assertThat(cap2.isAggregatable(), equalTo(true));
            assertThat(cap2.indices().length, equalTo(3));
            assertThat(cap2.indices(), equalTo(new String[]{"index1", "index2", "index3"}));
            assertNull(cap2.nonSearchableIndices());
            assertNull(cap2.nonAggregatableIndices());
            assertEquals(Map.of("foo", Set.of("bar", "quux")), cap2.meta());
        }
    }

    static FieldCapabilities randomFieldCaps(String fieldName) {
        String[] indices = null;
        if (randomBoolean()) {
            indices = new String[randomIntBetween(1, 5)];
            for (int i = 0; i < indices.length; i++) {
                indices[i] = randomAlphaOfLengthBetween(5, 20);
            }
        }
        String[] nonSearchableIndices = null;
        if (randomBoolean()) {
            nonSearchableIndices = new String[randomIntBetween(0, 5)];
            for (int i = 0; i < nonSearchableIndices.length; i++) {
                nonSearchableIndices[i] = randomAlphaOfLengthBetween(5, 20);
            }
        }
        String[] nonAggregatableIndices = null;
        if (randomBoolean()) {
            nonAggregatableIndices = new String[randomIntBetween(0, 5)];
            for (int i = 0; i < nonAggregatableIndices.length; i++) {
                nonAggregatableIndices[i] = randomAlphaOfLengthBetween(5, 20);
            }
        }

        Map<String, Set<String>> meta;
        switch (randomInt(2)) {
        case 0:
            meta = Collections.emptyMap();
            break;
        case 1:
            meta = Map.of("foo", Set.of("bar"));
            break;
        default:
            meta = Map.of("foo", Set.of("bar", "baz"));
            break;
        }

        return new FieldCapabilities(fieldName,
            randomAlphaOfLengthBetween(5, 20), randomBoolean(), randomBoolean(), randomBoolean(),
            indices, nonSearchableIndices, nonAggregatableIndices, meta);
    }

    @Override
    protected FieldCapabilities mutateInstance(FieldCapabilities instance) {
        String name = instance.getName();
        String type = instance.getType();
        boolean isMetadataField = instance.isMetadataField();
        boolean isSearchable = instance.isSearchable();
        boolean isAggregatable = instance.isAggregatable();
        String[] indices = instance.indices();
        String[] nonSearchableIndices = instance.nonSearchableIndices();
        String[] nonAggregatableIndices = instance.nonAggregatableIndices();
        Map<String, Set<String>> meta = instance.meta();
        switch (between(0, 8)) {
        case 0:
            name += randomAlphaOfLengthBetween(1, 10);
            break;
        case 1:
            type += randomAlphaOfLengthBetween(1, 10);
            break;
        case 2:
            isSearchable = isSearchable == false;
            break;
        case 3:
            isAggregatable = isAggregatable == false;
            break;
        case 4:
            String[] newIndices;
            int startIndicesPos = 0;
            if (indices == null) {
                newIndices = new String[between(1, 10)];
            } else {
                newIndices = Arrays.copyOf(indices, indices.length + between(1, 10));
                startIndicesPos = indices.length;
            }
            for (int i = startIndicesPos; i < newIndices.length; i++) {
                newIndices[i] = randomAlphaOfLengthBetween(5, 20);
            }
            indices = newIndices;
            break;
        case 5:
            String[] newNonSearchableIndices;
            int startNonSearchablePos = 0;
            if (nonSearchableIndices == null) {
                newNonSearchableIndices = new String[between(1, 10)];
            } else {
                newNonSearchableIndices = Arrays.copyOf(nonSearchableIndices, nonSearchableIndices.length + between(1, 10));
                startNonSearchablePos = nonSearchableIndices.length;
            }
            for (int i = startNonSearchablePos; i < newNonSearchableIndices.length; i++) {
                newNonSearchableIndices[i] = randomAlphaOfLengthBetween(5, 20);
            }
            nonSearchableIndices = newNonSearchableIndices;
            break;
        case 6:
            String[] newNonAggregatableIndices;
            int startNonAggregatablePos = 0;
            if (nonAggregatableIndices == null) {
                newNonAggregatableIndices = new String[between(1, 10)];
            } else {
                newNonAggregatableIndices = Arrays.copyOf(nonAggregatableIndices, nonAggregatableIndices.length + between(1, 10));
                startNonAggregatablePos = nonAggregatableIndices.length;
            }
            for (int i = startNonAggregatablePos; i < newNonAggregatableIndices.length; i++) {
                newNonAggregatableIndices[i] = randomAlphaOfLengthBetween(5, 20);
            }
            nonAggregatableIndices = newNonAggregatableIndices;
            break;
        case 7:
            Map<String, Set<String>> newMeta;
            if (meta.isEmpty()) {
                newMeta = Map.of("foo", Set.of("bar"));
            } else {
                newMeta = Collections.emptyMap();
            }
            meta = newMeta;
            break;
        case 8:
            isMetadataField = isMetadataField == false;
            break;
        default:
            throw new AssertionError();
        }
        return new FieldCapabilities(name, type, isMetadataField, isSearchable, isAggregatable,
            indices, nonSearchableIndices, nonAggregatableIndices, meta);
    }
}


text:
<?php

class Plugins{

    var $basepath = null;

    function __construct(){
        global $basepath;
        $this->basepath = $basepath;
    }

    public function getFrontendMenu($activeplugins){
        $path = $this->basepath."/plugins";

        $dir_handle = @opendir($path);

        $menus = array();

        if (@$dir_handle){
            while ($file = readdir($dir_handle)) {

				if($file == "." || $file == ".."){
					continue;
				} else {
					if (file_exists($this->basepath."/plugins/".$file."/descriptor.xml") && isset($activeplugins[$file])){
						$content = file_get_contents($this->basepath."/plugins/".$file."/descriptor.xml");
						$dom = new DOMDocument();
						@$dom->loadXML($content);

						$plugin_name = $file;

						$paths = $dom->getElementsByTagName('paths');
						if ($paths->length){
							$backend = $paths->item(0)->getElementsByTagName('frontEnd');
							if ($backend->length){
								$paths = $backend->item(0)->getElementsByTagName('path');
								if ($paths->length){
									for($i=0; $i<$paths->length; $i++){
										$main_menu_url = $paths->item($i)->getElementsByTagName('mainMenuUrl');
										if ($main_menu_url->length){
											$main_menu_url = $main_menu_url->item(0)->nodeValue;

											$main_menu_title = $paths->item($i)->getElementsByTagName('mainMenuTitle');
											if ($main_menu_title->length){
												$main_menu_title = $main_menu_title->item(0)->nodeValue;
											} else {
												$main_menu_title = false;
											}

											$main_menu_icon = $paths->item($i)->getElementsByTagName('mainMenuIcon');
											if ($main_menu_icon->length){
												$main_menu_icon = $main_menu_icon->item(0)->nodeValue;
											} else {
												$main_menu_icon = "icon-magnet";
											}

											$sub_menu_title = $paths->item($i)->getElementsByTagName('subMenuTitle');
											if ($sub_menu_title->length){
												$sub_menu_title = $sub_menu_title->item(0)->nodeValue;
											} else {
												$sub_menu_title = false;
											}

											$sub_menu_url = $paths->item($i)->getElementsByTagName('subMenuUrl');
											if ($sub_menu_url->length){
												$sub_menu_url = $sub_menu_url->item(0)->nodeValue;
											} else {
												$sub_menu_url = false;
											}

											if (!isset($menus[$main_menu_url])){
												$menus[$main_menu_url] = array();
											}

											$full_url = false;
											if (isset($sub_menu_url[0]) && $sub_menu_url[0] == "/"){
												$full_url = $sub_menu_url;
											} else {
												$full_url = "/plugin/".$plugin_name."/".$sub_menu_url;
											}

											$menus[$main_menu_url][] = array("main_menu_title" => $main_menu_title, "sub_menu_title" => $sub_menu_title, "sub_menu_url" => $sub_menu_url, "plugin" => $plugin_name, "icon" => $main_menu_icon, "full_url" => $full_url);
										}
									}
								}
							}
						}

					}
				}
			}
			closedir($dir_handle);
		}
		return $menus;
	}

	public function getBackendMenu(){
		$path = $this->basepath."/plugins";

		$dir_handle = @opendir($path);

		$menus = array();

		if (@$dir_handle){
			while ($file = readdir($dir_handle)) {
                if($file == "." || $file == ".."){
                    continue;
                } else {
                    if (file_exists($this->basepath."/plugins/".$file."/descriptor.xml")){
                        $content = file_get_contents($this->basepath."/plugins/".$file."/descriptor.xml");
                        $dom = new DOMDocument();
                        @$dom->loadXML($content);

                        $plugin_name = $file;

                        $paths = $dom->getElementsByTagName('paths');
                        if ($paths->length){
                            $backend = $paths->item(0)->getElementsByTagName('backEnd');
                            if ($backend->length){
                                $paths = $backend->item(0)->getElementsByTagName('path');
                                if ($paths->length){
                                    for($i=0; $i<$paths->length; $i++){
                                        $main_menu_url = $paths->item($i)->getElementsByTagName('mainMenuUrl');
                                        if ($main_menu_url->length){
                                            $main_menu_url = $main_menu_url->item(0)->nodeValue;

                                            $main_menu_title = $paths->item($i)->getElementsByTagName('mainMenuTitle');
                                            if ($main_menu_title->length){
                                                $main_menu_title = $main_menu_title->item(0)->nodeValue;
                                            } else {
                                                $main_menu_title = false;
                                            }

                                            $main_menu_icon = $paths->item($i)->getElementsByTagName('mainMenuIcon');
                                            if ($main_menu_icon->length){
                                                $main_menu_icon = $main_menu_icon->item(0)->nodeValue;
                                            } else {
                                                $main_menu_icon = "icon-magnet";
                                            }

                                            $sub_menu_title = $paths->item($i)->getElementsByTagName('subMenuTitle');
                                            if ($sub_menu_title->length){
                                                $sub_menu_title = $sub_menu_title->item(0)->nodeValue;
                                            } else {
                                                $sub_menu_title = false;
                                            }

                                            $sub_menu_url = $paths->item($i)->getElementsByTagName('subMenuUrl');
                                            if ($sub_menu_url->length){
                                                $sub_menu_url = $sub_menu_url->item(0)->nodeValue;
                                            } else {
                                                $sub_menu_url = false;
                                            }

                                            if (!isset($menus[$main_menu_url])){
                                                $menus[$main_menu_url] = array();
                                            }

                                            $menus[$main_menu_url][] = array("main_menu_title" => $main_menu_title, "sub_menu_title" => $sub_menu_title, "sub_menu_url" => $sub_menu_url, "plugin" => $plugin_name, "icon" => $main_menu_icon);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }
            closedir($dir_handle);
        }
        return $menus;
    }

    public function getAllPlugins(){
        // clearing the cache
        $path = $this->basepath."/plugins";
        $dir_handle = @opendir($path);

        $plugs = array();
        $cntr = 0;

        if (@$dir_handle){
            while ($file = readdir($dir_handle)) {

                if($file == "." || $file == ".."){
                    continue;
                } else {
                    if (file_exists($this->basepath."/plugins/".$file."/descriptor.xml")){
                        $content = file_get_contents($this->basepath."/plugins/".$file."/descriptor.xml");
                        $dom = new DOMDocument();
                        @$dom->loadXML($content);

                        $names = $dom->getElementsByTagName('name');
                        if ($names->length){
                            $name = $names->item(0)->nodeValue;
                        } else {
                            $name = '';
                        }

                        $descriptions = $dom->getElementsByTagName('description');
                        if ($descriptions->length){
                            $description = $descriptions->item(0)->nodeValue;
                        } else {
                            $description = '';
                        }

                        $installUrls = $dom->getElementsByTagName('installUrl');
                        if ($installUrls->length){
                            $installUrl = $installUrls->item(0)->nodeValue;
                        } else {
                            $installUrl = '';
                        }

                        $uninstallUrls = $dom->getElementsByTagName('uninstallUrl');
                        if ($uninstallUrls->length){
                            $uninstallUrl = $uninstallUrls->item(0)->nodeValue;
                        } else {
                            $uninstallUrl = '';
                        }

                        $startUrls = $dom->getElementsByTagName('startUrl');
                        if ($startUrls->length){
                            $startUrl = $startUrls->item(0)->nodeValue;
                        } else {
                            $startUrl = '';
                        }

                        $authors = $dom->getElementsByTagName('author');
                        if ($authors->length){
                            $author = $authors->item(0)->nodeValue;
                        } else {
                            $author = '';
                        }

                        $authorUrls = $dom->getElementsByTagName('authorUrl');
                        if ($authorUrls->length){
                            $authorUrl = $authorUrls->item(0)->nodeValue;
                        } else {
                            $authorUrl = '';
                        }

                        if ($name){
                            $plugs[$cntr]=array();
                            $plugs[$cntr]['dirname']=$file;
                            $plugs[$cntr]['name']=$name;
                            $plugs[$cntr]['description']=$description;
                            $plugs[$cntr]['install_url']=$installUrl;
                            $plugs[$cntr]['uninstall_url']=$uninstallUrl;
                            $plugs[$cntr]['start_url']=$startUrl;
                            $plugs[$cntr]['author']=$author;
                            $plugs[$cntr]['author_url']=$authorUrl;
                            $cntr++;
                        }
                    }
                }
            }
            closedir($dir_handle);
        }

        return $plugs;
    }

    public function getInstalledPlugins(){
        $e = mysql_query("SELECT * FROM plugins") or die(mysql_error());
        $plugs = array();
        if (mysql_num_rows($e)){
            while($s=mysql_fetch_assoc($e)){
                $plugs[$s['dirname']]=$s;
            }
        }
        return $plugs;

    }

    public function deletePlugin($plug){
        $plug['dirname'] = mysql_real_escape_string($plug['dirname']);
        $e = mysql_query("DELETE FROM plugins WHERE dirname='{$plug['dirname']}'") or die(mysql_error());
    }

    public function activatePlugin($plug){
        $plug['dirname']=mysql_real_escape_string($plug['dirname']);
        $plug['name']=mysql_real_escape_string($plug['name']);
        $plug['description']=mysql_real_escape_string($plug['description']);
        $plug['author']=mysql_real_escape_string($plug['author']);
        $plug['install_url']=mysql_real_escape_string($plug['install_url']);
        $plug['start_url']=mysql_real_escape_string($plug['start_url']);
        $plug['author_url']=mysql_real_escape_string($plug['author_url']);

        $e = mysql_query("INSERT INTO plugins(dirname,name,description,author,install_url,start_url,author_url)
                                 VALUES ('{$plug['dirname']}','{$plug['name']}','{$plug['description']}','{$plug['author']}','{$plug['install_url']}','{$plug['start_url']}','{$plug['author_url']}')") or die(mysql_error());
    }

}

?>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

Inicio de Sesión

                <form data-lift="form.ajax?class=form-horizontal" class="form-horizontal" role="form">

                        Usuario:

                            <input type="email" class="form-control" id="inputUser" placeholder="usuario">

                        Contraseña:

                            <input type="password" class="form-control" id="inputPass" placeholder="contraseña">

                            <button type="submit" class="btn btn-default">Iniciar Sesión</button>

                </form>


text:
from twitter_ads.client import Client
from twitter_ads.creative import TweetPreview
from twitter_ads.enum import TWEET_TYPE

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_TOKEN_SECRET = ''
ACCOUNT_ID = ''

# initialize the client
client = Client(
    CONSUMER_KEY,
    CONSUMER_SECRET,
    ACCESS_TOKEN,
    ACCESS_TOKEN_SECRET)

# load the advertiser account instance
account = client.accounts(ACCOUNT_ID)

# fetch preview data
tweets = TweetPreview.load(
    account,
    tweet_ids=['1130942781109596160', '1101254234031370240'],
    tweet_type=TWEET_TYPE.PUBLISHED)

# iterate for each tweet
for k in tweets:
    print(k.tweet_id)
    print(k.preview)


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

    define(
        [
            'util/container',
            'services/searchService',
            'services/detailService',
            'services/cachingService',
            'ui/overlay'
        ],
        function (container, searchService, detailService, cachingService, overlay) {
            var simpleApiBaseUrl, options;

            simpleApiBaseUrl = 'https://collections-api.histwest.org.au/service.php/simple';
            options = {
                noCache: true,
                logErrors: true,
                limit: 500,
                ajaxOptions: {
                    xhrFields: {
                        withCredentials: true
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('research-frontend:NotReallySecret'));
                    }
                }
            };

            return function () {
                container.register('options.service', options);
                container.register('options.shop', {
                    baseUrl: 'https://staging-shop.histwest.org.au/index.php/',
                    path: {
                        search: 'catalogsearch/result/',
                        digitalPhotographs: 'photographs/digital-photograph.html'
                    }
                });
                container.register('options.providence', {
                    baseUrl: 'https://staging-collections.histwest.org.au/index.php/',
                    path: {
                        objects: 'editor/objects/ObjectEditor/Summary/'
                    }
                });

                container.register('search.all', cachingService(searchService(simpleApiBaseUrl + '/all_search', options)));
                container.register('search.library', cachingService(searchService(simpleApiBaseUrl + '/library_search', options)));
                container.register('search.photographs', cachingService(searchService(simpleApiBaseUrl + '/photographs_search', options)));
                container.register('search.museum', cachingService(searchService(simpleApiBaseUrl + '/museum_search', options)));
                container.register('search.memorials', cachingService(searchService(simpleApiBaseUrl + '/memorials_search', options)));

                container.register('detail.library', cachingService(detailService(simpleApiBaseUrl + '/library_detail', options)));
                container.register('detail.photographs', cachingService(detailService(simpleApiBaseUrl + '/photographs_detail', options)));
                container.register('detail.museum', cachingService(detailService(simpleApiBaseUrl + '/museum_detail', options)));
                container.register('detail.memorials', cachingService(detailService(simpleApiBaseUrl + '/memorials_detail', options)));

                container.register('ui.overlay', overlay(true));
            };
        }
    );
}());


text:
<?php
namespace Admin\Form;
use Zend\Ldap\Attribute;

use Zend\Form\Form;
use Zend\Form\Element as El;
use Zend\Filter as Filter;
use Zend\InputFilter;
use Zend\Validator as Validator;

class Article extends Form
{
    public function __construct()
    {
        parent::__construct();

        $this->setName('comment');

        $this->add(new El\Text('name', array(
            'label' => 'Name',
        )));

        $this->add($text = new El\Textarea('text', array(
            'label' => 'Text',
        )));
        $text->setAttributes(
        	array(
        		'cols' => 80,
		    	'rows' => 20,
        	));

        $submit = new El\Submit('submit');
        $submit->setLabel('Send');
        $submit->setValue('Save');
        $this->add($submit);

        $inputFilter = new \Zend\InputFilter\InputFilter();

        $name = new \Zend\InputFilter\Input('name');
        $filterChain = new Filter\FilterChain();
        $filterChain->attachByName('StripTags');
        $name->setFilterChain($filterChain);
        $inputFilter->add($name);

        $email = new \Zend\InputFilter\Input('text');
        $inputFilter->add($email);
        $this->setInputFilter($inputFilter);
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
var _ = require('lodash'),
  fs = require('fs'),
  path = require('path'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  mongoose = require('mongoose'),
  multer = require('multer'),
  config = require(path.resolve('./config/config')),
  User = mongoose.model('User'),
  validator = require('validator');

var whitelistedFields = ['firstName', 'lastName', 'email', 'username'];

/**
 * Update user details
 */
exports.update = function (req, res) {
  // Init Variables
  var user = req.user;

  if (user) {
    // Update whitelisted fields only
    user = _.extend(user, _.pick(req.body, whitelistedFields));

    user.updated = Date.now();
    user.displayName = user.firstName + ' ' + user.lastName;

    user.save(function (err) {
      if (err) {
        return res.status(422).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        req.login(user, function (err) {
          if (err) {
            res.status(400).send(err);
          } else {
            res.json(user);
          }
        });
      }
    });
  } else {
    res.status(401).send({
      message: 'User is not signed in'
    });
  }
};

/**
 * Update profile picture
 */
exports.changeProfilePicture = function (req, res) {
  var user = req.user;
  var upload = multer(config.uploads.profileUpload).single('newProfilePicture');
  var profileUploadFileFilter = require(path.resolve('./config/lib/multer')).extensionFilter;
  var existingImageUrl;

  // Filtering to upload only images
  upload.fileFilter = profileUploadFileFilter;

  if (user) {
    existingImageUrl = user.profileImageURL;
    uploadImage()
      .then(updateUser)
      .then(deleteOldImage)
      .then(login)
      .then(function () {
        res.json(user);
      })
      .catch(function (err) {
        res.status(422).send(err);
      });
  } else {
    res.status(401).send({
      message: 'User is not signed in'
    });
  }

  function uploadImage () {
    return new Promise(function (resolve, reject) {
      upload(req, res, function (uploadError) {
        if (uploadError) {
          reject(errorHandler.getErrorMessage(uploadError));
        } else {
          resolve();
        }
      });
    });
  }

  function updateUser () {
    return new Promise(function (resolve, reject) {
      user.profileImageURL = config.uploads.profileUpload.dest + req.file.filename;
      user.save(function (err, theuser) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }

  function deleteOldImage () {
    return new Promise(function (resolve, reject) {
      if (existingImageUrl !== User.schema.path('profileImageURL').defaultValue) {
        fs.unlink(existingImageUrl, function (unlinkError) {
          if (unlinkError) {
            console.log(unlinkError);
            reject({
              message: 'Error occurred while deleting old profile picture'
            });
          } else {
            resolve();
          }
        });
      } else {
        resolve();
      }
    });
  }

  function login () {
    return new Promise(function (resolve, reject) {
      req.login(user, function (err) {
        if (err) {
          res.status(400).send(err);
        } else {
          resolve();
        }
      });
    });
  }
};

/**
 * Send User
 */
exports.me = function (req, res) {
  // Sanitize the user - short term solution. Copied from core.server.controller.js
  // TODO create proper passport mock: See https://gist.github.com/mweibel/5219403
  var safeUserObject = null;
  if (req.user) {
    safeUserObject = {
      displayName: validator.escape(req.user.displayName),
      provider: validator.escape(req.user.provider),
      username: validator.escape(req.user.username),
      created: req.user.created.toString(),
      roles: req.user.roles,
      profileImageURL: req.user.profileImageURL,
      email: validator.escape(req.user.email),
      lastName: validator.escape(req.user.lastName),
      firstName: validator.escape(req.user.firstName),
      additionalProvidersData: req.user.additionalProvidersData
    };
  }

  res.json(safeUserObject || null);
};


text:
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/index',
                    // add_url: 'order/add',
                    // edit_url: 'order/edit',
                    // del_url: 'order/del',
                    // multi_url: 'order/multi',
                    table: 'order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: true,
                sortName: 'id',
                sortOrder: 'desc',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),visible: false,operate: false},
                        {field: 'amazon_order_id', title: __('Amazon_order_id'), style: 'width:228px'},
                        {field: 'package_number', title: __('Package_number')},
                        {field: 'skus', title: __('Skus'),formatter: Controller.api.formatter.skus, operate: false},
                        {field: 'ship_by', title: __('Ship_by'), formatter: Controller.api.formatter.shipBy},
                        // {field: 'has_items', title: __('Has_items'),visible: false},
                        {
                            field: 'order_status',
                            title: __('Order_status'),
                            formatter: Controller.api.formatter.orderStatus,
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索,*表示任意字符',
                        },
                        {
                            field: 'deliver_status',
                            title: __('Deliver_status'),
                            formatter: Controller.api.formatter.packageStatus,
                            operate: 'LIKE %...%',
                            placeholder: '模糊搜索,*表示任意字符',
                            visible: false
                        },
                        {
                            field: 'has_send_mail',
                            title: __('Has_send_mail'),
                            formatter: Controller.api.formatter.mailStatus,
                            searchList: ['0', '1'],
                            events: Controller.api.events.mail,
                            style:'width:159px'
                        },

                        {field: 'buyer_name', title: __('Buyer_name'), operate:true},
                        {
                            field: 'buyer_email',
                            title: __('Buyer_email'),
                            formatter: Controller.api.formatter.email
                            // visible: false,
                            // operate: false
                        },
                        {
                            field: 'update_time',
                            title: __('Update_time'),
                            formatter: Table.api.formatter.datetime,
                            sortable: true,
                            operate: 'BETWEEN', type: 'datetime', addclass: 'datetimepicker', data: 'data-date-format="YYYY-MM-DD HH:mm:ss"'
                        },
                        {field: 'sales_channel', title: __('Sales_channel'), visible: false, operate: false},
                        {field: 'last_update_date', title: __('Last_update_date'), visible: false, operate: false},
                        {field: 'order_type', title: __('Order_type'), visible: false, operate: false},
                        {field: 'purchase_date', title: __('Purchase_date'), operate: false},
                        {field: 'is_business_order', title: __('Is_business_order'), visible: false, operate: false},
                        {field: 'ship_service_level', title: __('Ship_service_level'), visible: false, operate: false},
                        {
                            field: 'number_of_items_shipped',
                            title: __('Number_of_items_shipped'),
                            visible: false,
                            operate: false
                        },
                        {
                            field: 'fulfillment_channel',
                            title: __('Fulfillment_channel'),
                            visible: false,
                            operate: false
                        },
                        {
                            field: 'create_time',
                            title: __('Create_time'),
                            formatter: Table.api.formatter.datetime,
                            visible: false,
                            operate: false
                        },
                        // {field: 'latest_ship_date', title: __('Latest_ship_date'),visible: false},
                        {
                            field: 'number_of_items_unshipped',
                            title: __('Number_of_items_unshipped'),
                            visible: false,
                            operate: false
                        },
                        // {field: 'is_replacement_order', title: __('Is_replacement_order'),visible: false},
                        // {field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 快递按钮事件
            $(document).on("click", ".btn-track", function (e) {
                e.preventDefault();
                var ids = Table.api.selectedids(table);
                //循环弹出多个编辑框
                $.each(ids, function (i, id) {
                    Fast.api.open('order/tracker' + "?id=" + id, "快递信息列表");
                });
            });

            // 商品按钮事件
            $(document).on("click", ".btn-order-item", function (e) {
                e.preventDefault();
                var ids = Table.api.selectedids(table);
                //循环弹出多个编辑框
                $.each(ids, function (i, id) {
                    Fast.api.open('order/items' + "?id=" + id, "商品列表");
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
                orderStatus: function (value, row, index) {
                    var colorArr = {
                        Shipped: 'success', Pending: 'warning', Canceled: 'danger', Unshipped: 'info',  // order status
                    };
                    value = value === null ? "无状态" : value;
                    var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                    return '' + __(value) + '';
                },
                skus: function (value, row, index) {
                    // var skus = value.split(',');
                    // var skuArr = [];
                    // $.each(skus, function (i, value) {
                    //     arr = value.split('-');
                    //     if(arr.length===2){
                    //         skuArr.push(arr[1]);
                    //     }
                    // });
                    // value = skuArr.join(',');
                    value = value.replace(/HOLSEM[-| ]/g,'');
                    return value;
                },
                shipBy: function (value, row, index) {
                    value = value===null?'':value.toString();
                    return '' + value + '';
                },
                packageStatus: function (value, row, index) {
                    var colorArr = {
                        delivered: 'success', in_transit: 'warning', unknown: 'danger',  // package status
                    };
                    var html = [];
                    value = (value===null || value==='') ? "未爬取" : value;
                    var arr = value.split("_");
                    $.each(arr, function (i, value) {
                        var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                        html.push('' + __(value) + '');
                    });
                    return html.join(' ');
                },
                mailStatus: function (value, row, index) {
                    var colorArr = {
                        '1': 'success', '0': 'danger',  // package status
                    };
                    value = value === null ? "0" : value.toString();
                    var val = value === '0' ? '未发送' : '已发送';
                    var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                    // return '' + __(val) + '';
                    return '' + __(val) + '';
                },
                email: function (value, row, index) {
                    value = value === null ? '无邮箱' : value;
                    return '
<input type="text" class="form-control input-sm" value="' + value + '">
';
                },

            },
            events: {//绑定事件的方法
                mail: {
                    //格式为:方法名+空格+DOM元素
                    'click .btn-mail': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        $("form.form-commonsearch [name='has_send_mail']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        // Toastr.info("执行了自定义搜索操作");
                    }
                },
            }
        },

    };
    return Controller;
});


text:
================
django-livefield
================

.. image:: https://travis-ci.org/hearsaycorp/django-livefield.svg
    :alt: Build Status
    :target: https://travis-ci.org/hearsaycorp/django-livefield

=====
About
=====
A Django field that enables convenient soft-deletion. For Python 2.7/3.3+ and Django 1.8+

============
Installation
============
Simple: ``pip install django-livefield``.

=============
Example Usage
=============
.. code:: python

    >>> from django.db import models
    >>> from livefield import LiveField, LiveManager
    >>>
    >>>
    >>> class Person(models.Model):
    ...    name = models.CharField()
    ...    live = LiveField()
    ...
    ...    objects = LiveManager()
    ...    all_objects = LiveManager(include_soft_deleted=True)
    ...
    ...    class Meta:
    ...        unique_together = ('name', 'live')
    ...
    ...    def delete(self, using=None):
    ...        self.live = False
    ...        self.save(using=using)
    ...
    >>> john = Person.objects.create(name='John Cleese')
    >>> doppelganger = Person(name='John Cleese')
    >>> doppelganger.save()  # Raises an IntegrityError
    >>> john.delete()
    >>> doppelganger.save()  # Succeeds!

=======
License
=======
MIT. See LICENSE.txt for details.

============
Contributing
============
Pull requests welcome! To save everyone some hassle, please open an
issue first so we can discuss your proposed change.

In your PR, be sure to add your name to AUTHORS.txt and include some
tests for your spiffy new functionality. Travis CI will green-light your
build once it passes the unit tests (``./setup.py test``) and our
linters (``./lint.sh``).


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "Array#initialize" do
  it "is private" do
    [].private_methods.should include("initialize")
  end

  it "replaces self with the other array" do
    o = [2]
    def o.special() size end
    a = [1, o, 3]
    ary = Array.new a
    ary[1].special.should == 1

    b = [1, [2], 3]
    ary.send :initialize, b

    b.==(ary).should == true
    lambda { b[1].special }.should raise_error(NoMethodError)
    lambda { ary[1].special }.should raise_error(NoMethodError)
  end

  it "is called on subclasses" do
    a = ArraySpecs::SubArray.new 10
    a.special.should == 10
    a.should == []

    b = ArraySpecs::SubArray.new [1,2,3]
    b.special.should == [1,2,3]
    b.should == []
  end

  it "does nothing when passed self" do
    ary = [1, 2, 3]
    ary.instance_eval { initialize(ary) }
    ary.should == [1, 2, 3]
  end

  it "sets the array to size and fills with the object when passed size, object" do
    a = []
    a.instance_eval { initialize(2, [3]) }
    a.should == [[3], [3]]
    a[0].__id__.should == a[1].__id__
    [].instance_eval { initialize(1) }.should == [nil]
  end

  it "raises an ArgumentError if size is negative" do
    lambda { [].instance_eval { initialize(-1, :a) } }.should raise_error(ArgumentError)
    lambda { [1, 2, 3].instance_eval { initialize(-1) } }.should raise_error(ArgumentError)
  end

  it "tries to convert the passed size argument to an Integer using #to_int" do
    obj = mock('1')
    obj.should_receive(:to_int).and_return(1)
    [1, 2].send(:initialize, obj, :a).should == [:a]
  end

  it "checks whether the passed size argument responds to #to_int" do
    obj = mock('1')
    obj.should_receive(:respond_to?).with(:to_int).any_number_of_times.and_return(true)
    obj.should_receive(:method_missing).with(:to_int).and_return(1)
    [1, 2].send(:initialize, obj, :a).should == [:a]
  end

  compliant_on :ruby, :jruby do
    it "raises a TypeError on frozen arrays even if the array would not be 'modified'" do
      # This is true at least 1.8.6p111 onwards
      lambda { ArraySpecs.frozen_array.instance_eval { initialize } }.should raise_error(TypeError)

      lambda { ArraySpecs.frozen_array.instance_eval { initialize(1) } }.should raise_error(TypeError)
      lambda { ArraySpecs.frozen_array.instance_eval { initialize([1, 2, 3]) } }.should raise_error(TypeError)
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Microporellus inusitatus var. inusitatus

### Remarks
null


text:
module WicketSDK
  class Error < StandardError; end

  # Custom error class for rescuing from all Wicket API errors
  class ApiError < Error

    # Returns the appropriate WicketSDK::Error subclass based
    # on status and response message
    #
    # @param [Hash] response HTTP response
    # @return [WicketSDK::Error]
    def self.from_response(response)
      status  = response[:status].to_i
      body    = response[:body].to_s
      headers = response[:response_headers]

      if klass =  case status
                  when 400      then WicketSDK::BadRequest
                  when 401      then WicketSDK::Unauthorized
                  when 403      then error_for_403(body)
                  when 404      then WicketSDK::NotFound
                  when 409      then WicketSDK::Conflict
                  when 415      then WicketSDK::UnsupportedMediaType
                  when 422      then WicketSDK::UnprocessableEntity
                  when 400..499 then WicketSDK::ClientError
                  when 500      then WicketSDK::InternalServerError
                  when 501      then WicketSDK::NotImplemented
                  when 502      then WicketSDK::BadGateway
                  when 503      then WicketSDK::ServiceUnavailable
                  when 500..599 then WicketSDK::ServerError
                  end
        klass.new(response)
      end
    end

    def initialize(response=nil)
      @response = response
      super(build_error_message)
    end

    # Returns most appropriate error for 403 HTTP status code
    # @private
    def self.error_for_403(body)
      # TODO: Look at returning more specific error class for some 403 errors.
      WicketSDK::Forbidden
    end

    # Array of validation errors
    # @return [Array<Hash>] Error info
    def errors
      []
    end

    # Status code returned by the Wicket API server.
    #
    # @return [Integer]
    def response_status
      @response[:status]
    end

    private

    def data
      nil
    end

    def response_message
      case data
      when Hash
        data[:message]
      when String
        data
      end
    end

    def response_error
      "Error: #{data[:error]}" if data.is_a?(Hash) && data[:error]
    end

    def response_error_summary
      return nil unless data.is_a?(Hash) && !Array(data[:errors]).empty?

      summary = "\nError summary:\n"
      summary << data[:errors].map do |hash|
        hash.map { |k,v| "  #{k}: #{v}" }
      end.join("\n")

      summary
    end

    def build_error_message
      return nil if @response.nil?

      message =  "#{@response[:method].to_s.upcase} "
      message << redact_url(@response[:url].to_s) + ": "
      message << "#{@response[:status]} - "
      message << "#{response_message}" unless response_message.nil?
      message << "#{response_error}" unless response_error.nil?
      message << "#{response_error_summary}" unless response_error_summary.nil?
      message
    end

    def redact_url(url_string)
      %w{client_secret access_token}.each do |token|
        url_string.gsub!(/#{token}=\S+/, "#{token}=(redacted)") if url_string.include? token
      end
      url_string
    end
  end

  # Raised when a connection could not be established with the Wicket API.
  class ConnectionError < Error; end

  # Raied when a JSON api document could not be parsed
  class InvalidDocument < Error; end

  # Raised on errors in the 400-499 range
  class ClientError < ApiError; end

  # Raised when Wicket API returns a 400 HTTP status code
  class BadRequest < ClientError; end

  # Raised when Wicket API returns a 401 HTTP status code
  class Unauthorized < ClientError; end

  # Raised when Wicket API returns a 403 HTTP status code
  class Forbidden < ClientError; end

  # Raised when Wicket API returns a 404 HTTP status code
  class NotFound < ClientError; end

  # Raised when Wicket API returns a 405 HTTP status code
  class MethodNotAllowed < ClientError; end

  # Raised when Wicket API returns a 409 HTTP status code
  class Conflict < ClientError; end

  # Raised when Wicket API returns a 414 HTTP status code
  class UnsupportedMediaType < ClientError; end

  # Raised when Wicket API returns a 422 HTTP status code
  class UnprocessableEntity < ClientError; end

  # Raised on errors in the 500-599 range
  class ServerError < ApiError; end

  # Raised when Wicket API returns a 500 HTTP status code
  class InternalServerError < ServerError; end

  # Raised when Wicket API returns a 501 HTTP status code
  class NotImplemented < ServerError; end

  # Raised when Wicket API returns a 502 HTTP status code
  class BadGateway < ServerError; end

  # Raised when Wicket API returns a 503 HTTP status code
  class ServiceUnavailable < ServerError; end

end


text:
/* User */
export const userModelSelector = state => state.user.model;
export const isLoggedInSelector = state => !!state.user.model;
export const userModelLocaleSelector = state =>
  (state.user.model || {}).locale || 'en';
export const isUserEditModalOpenSelector = state => state.user.isEditModalOpen;
export const isInitializedSelector = state => state.user.isInitialized;
export const userUidSelector = state => (state.user.model || {}).uid;
export const userFormSelector = state => state.user.form;
export const userLocaleSelector = state => state.user.locale;

/* Entity */
export const entitySelector = state => state.entity.models;
export const sectorSelector = state => state.entity.models.sector;
export const currentSectorSelector = state => state.entity.currentSector;
export const currentEntityTypeSelector = state =>
  state.entity.currentEntityType;
export const currentEntitySelector = state => state.entity.currentEntity;
export const lastOverviewEntitySelector = state =>
  state.entity.lastOverviewEntity;
export const savedSectorSelector = state => state.entity.saved;
export const shareSectorSelector = state => state.entity.share;
export const isSharedSectorSelector = state => !!state.entity.share;

/* Sector */
export const configurationSelector = state => state.sector.configuration;
export const holdKeySelector = state => state.sector.holdKey;
export const hoverKeySelector = state => state.sector.hoverKey;
export const renderSectorSelector = state => state.sector.renderSector;
export const topLevelKeySelector = state => state.sector.topLevelKey;
export const syncLockSelector = state => state.sector.syncLock;
export const exportTypeSelector = state => state.sector.exportType;
export const isExportOpenSelector = state => state.sector.isExportOpen;
export const isSectorExpansionOpenSelector = state =>
  state.sector.isSectorExpansionOpen;
export const isPrintingSelector = state => state.sector.isPrinting;
export const fetchedSectorSelector = state => state.sector.fetched;
export const playerViewSelector = state => state.sector.playerView;

/* Sidebar Edit */
export const sidebarEditSelector = state => state.sidebar;
export const isSidebarEditActiveSelector = state =>
  state.sidebar.isSidebarEditActive;
export const sidebarEditEntitySelector = state => state.sidebar.entity;
export const sidebarEditChildrenSelector = state => state.sidebar.children;

/* Router */
export const routerLocationSelector = state => state.router.location;

/* Navigation */
export const navigationRoutesSelector = state => state.navigation.routes;
export const navigationSettingsSelector = state => state.navigation.settings;
export const navigationSettingsRouteSelector = state =>
  state.navigation.settings.route;
export const isHelpOpenSelector = state => state.navigation.isHelpOpen;
export const navigationSyncLockSelector = state => state.navigation.syncLock;
export const routeLocatorSelector = state => state.navigation.routeLocator;

/* Layer */
export const layersSelector = state => state.layer.models;
export const layerFormSelector = state => state.layer.form;
export const layerIsEditingSelector = state => state.layer.isEditing;
export const layerRegionFormSelector = state => state.layer.regionForm;
export const layerColorPickerSelector = state => state.layer.colorPicker;
export const layerRegionPaintSelector = state => state.layer.regionPaint;

/* Faction */
export const factionsSelector = state => state.faction.models;
export const factionFormSelector = state => state.faction.form;
export const factionIsCreatingSelector = state => state.faction.isCreating;

/* Settings */
export const settingsSelector = state => state.settings;
export const settingsShowNumberOfChildren = state =>
  state.settings.showNumberOfChildren;
export const settingsShowEntityName = state => state.settings.showEntityName;
export const settingsShowCoordinates = state => state.settings.showCoordinates;

/* Tag */
export const customTagSelector = state => state.tag.models;
export const isCustomTagModalOpenSelector = state => state.tag.isOpen;


text:
package hpl.values;

import hpl.sys.HPLException;
import hpl.sys.PainterFrame;
import hpl.sys.Screen;
import javax.imageio.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;

public class PrimitivePainter extends Painter {

    protected BufferedImage image;

    /** Create a new Painter object that draws a blank screen.*/
    public PrimitivePainter() {
	image = new BufferedImage (Screen.DEFAULT_WIDTH,
				   Screen.DEFAULT_HEIGHT,
				   BufferedImage.TYPE_INT_ARGB);
    }

    /** Create a new painter from the image stored in the given file
     * @param imageFile The image file to be loaded and prepared as a painter.
     * @throws hpl.sys.HPLException if there was a problem reading the specified
     * file
     */
    public PrimitivePainter(String imageFile) throws HPLException {
	BufferedImage src;
	try {
	    src =ImageIO.read(new File(imageFile));
	} catch (IllegalArgumentException iae) {
	    throw new HPLException("File " + imageFile +
				   " not found");
	} catch (IOException ioe) {
	    throw new HPLException("Unable to read " + imageFile);
	}
	// now we need to invert the src image.
	/* define a transformation to reflect through y=0, then translate by
	   height.  xform = [ 1  0  0]
	                    [ 0 -1  height]
			    [ 0  0  1]
	 */
	int height = src.getHeight();
	AffineTransform xform = new AffineTransform(1, 0, 0, -1, 0, height);
	AffineTransformOp xformOp = new AffineTransformOp(xform, null);

	//image = xformOp.createCompatibleDestImage(src, src.getColorModel());
	image = xformOp.filter(src, null);
    }

    @Override
    public void render(Screen screen, PainterFrame frame) {
	/* draw the image represented by this painter in the given
	   rectangle on the screen. */
	screen.draw(image, frame);
    }
}


text:
package uo.ri.business;

import java.util.List;
import java.util.Map;

import uo.ri.business.dto.BreakdownDto;
import uo.ri.business.dto.InvoiceDto;
import uo.ri.business.dto.PaymentMeanDto;
import uo.ri.util.exception.BusinessException;

public interface CashService {

	InvoiceDto createInvoiceFor( List<Long> idsAveria ) throws BusinessException;

	InvoiceDto findInvoice( Long numeroFactura ) throws BusinessException;

	List<PaymentMeanDto> findPayMethodsForInvoice( Long idFactura ) throws BusinessException;

	void settleInvoice( Long idFactura, Map<Long, Double> cargos ) throws BusinessException;

	List<BreakdownDto> findRepairsByClient( String dni ) throws BusinessException;

	// resto de métodos que faltan...

}


text:
/**
 * @file ecl_pitch_controller.h
 * Definition of a simple orthogonal pitch PID controller.
 *
 * @author Lorenz Meier <lm@inf.ethz.ch>
 * @author Thomas Gubler <thomasgubler@gmail.com>
 *
 * Acknowledgements:
 *
 *   The control design is based on a design
 *   by Paul Riseborough and Andrew Tridgell, 2013,
 *   which in turn is based on initial work of
 *   Jonathan Challinger, 2012.
 */

#ifndef ECL_PITCH_CONTROLLER_H
#define ECL_PITCH_CONTROLLER_H

#include <stdbool.h>
#include <stdint.h>

#include "ecl_controller.h"

class __EXPORT ECL_PitchController :
	public ECL_Controller
{
public:
	ECL_PitchController();

	~ECL_PitchController();

	float control_attitude(const struct ECL_ControlData &ctl_data);
	float control_bodyrate(const struct ECL_ControlData &ctl_data);

	/* Additional Setters */
	void set_max_rate_pos(float max_rate_pos) {
		_max_rate = max_rate_pos;
	}

	void set_max_rate_neg(float max_rate_neg) {
		_max_rate_neg = max_rate_neg;
	}

	void set_roll_ff(float roll_ff) {
		_roll_ff = roll_ff;
	}

protected:
	float _max_rate_neg;
	float _roll_ff;
};

#endif // ECL_PITCH_CONTROLLER_H


text:
<?php
namespace org\bovigo\vfs\examples\part03;
use org\bovigo\vfs\vfsStream;
use PHPUnit\Framework\TestCase;

class FileSystemCacheFailureTest extends TestCase
{
    private $root;

    public function setUp(): void {
        $this->root = vfsStream::setup();
    }

    /**
     * @test
     */
    public function returnsTrueWhenNoFailureOccurs() {
        $cache = new FileSystemCache($this->root->url() . '/cache');
        $this->assertTrue($cache->store('example', ['bar' => 303]));
    }

    /**
     * @test
     */
    public function returnsFalseWhenFailureOccurs() {
        vfsStream::newFile('example', 0000)
                 ->withContent('notoverwritten')
                 ->at($this->root);
        $cache = new FileSystemCache($this->root->url());
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage("failed to open stream");
        $cache->store('example', ['bar' => 303]);
    }

    /**
     * @test
     */
    public function returnsFalseWhenFailureOccursAlternative() {
        vfsStream::setQuota(10);
        $cache = new FileSystemCache($this->root->url());
        $this->expectException(\Exception::class);
        $this->expectExceptionMessage("possibly out of free disk space");
        $cache->store('example', ['bar' => 303]);
    }
}


text:
Integration for [Microsoft Application Insights]( http://azure.microsoft.com/services/application-insights/ ) tracking in your Kirby site.

## Installation

1. Create a directory `application-insights` in your site's `/site/plugins` directory.
2. Copy all files into this directory.

### Advanced Installation

If you use Git for your site you can also install in a single step by using a [Git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules). From the root of your site execute this:

```
git submodule add https://github.com/bowstreet/application-insights-kirby.git site/plugins/application-insights
```

## Config Variables

Configure the corresponding values in your site config.

**Tip:** Make use of Kirby's simple [multi-environment options]( http://getkirby.com/docs/advanced/options ) feature to set up tracking only for your production site.

- applicationinsights.active: true / false (Default: true)
- applicationinsights.instrumentationkey: (Use your Application Insights Instrumentation Key)

## Example usage

### Config

```php
c::set('applicationinsights.active', true);
c::set('applicationinsights.instrumentationkey', 'your-instrumentation-key');
```

### Snippets

You can either add the following to your site's `<head>` element or as the last element right before the closing `</body>` tag.

```php
<?php echo application_insights(); ?>
```

## Author

Matthias Wenz, bowstreet
<https://bowstreet.de>


text:
tranny.service package
======================

Submodules
----------

tranny.service.rating module
----------------------------

.. automodule:: tranny.service.rating
    :members:
    :undoc-members:
    :show-inheritance:

tranny.service.tmdb module
--------------------------

.. automodule:: tranny.service.tmdb
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: tranny.service
    :members:
    :undoc-members:
    :show-inheritance:


text:
<?php

namespace gossamer\core\http;

use gossamer\libraries\utils\YAMLConfiguration;
use Monolog\Logger;
use gossamer\core\http\HTTPRequest;
use gossamer\core\http\HTTPResponse;

class ResponseFormatter
{

    /**
     * if true, the system will throw an error if a URI is not specified for exposing elements.
     * if false, the system will output ALL values in the registry if the URI is not located in the XML config file.
     */
    const PARANOID_MODE = FALSE;

    /**
     * format - prune the registry based on xml config
     *
     * @param string    XMLpath
     * @param Registry  registry
     *
     * @return array
     */
    public static function format(YAMLConfiguration $params, HTTPRequest $request, HTTPResponse &$response, Logger $logger) {

        $attributes = $request->getAttributes();

        $output = array();

        if (count($params) < 1) {
            if (self::PARANOID_MODE) {
                $logger->addError('XML is missing CherryPicker configs for ' . $uri);
                throw new XMLNodeNotConfiguredException('need to customize error for YAML configs for ' . $uri);
            }

            //not paranoid? ok - dump the whole registry to the user
            foreach($attributes as $key => $value) {
                $output[self::trimNamespacing($key)] = $attributes[$key];
            }
            return $output;
        }
        $configs = array_filter($params->getConfigs());

        foreach($configs as $key => $outputSet) {
         // pr($outputSet);
          //  exit;
           foreach($outputSet as $className => $columns) {
               if(is_array($outputSet)) {
                    self::formatArray($className, $columns, $output, $attributes, $logger);
               }
           }
        }

      $response = new HTTPResponse($output);

    }

    /**
     * formatArray - takes the value located in the yml file, pulls it from the registry
     * and adds it to the output array.
     *
     * @param string    className - element name we are parsing
     * @param array     columns - the array of exposable values
     * @param array     output - the return value
     * @param array     attributes - the list to parse
     * @param Logger    logger - the logging object
     */

    private static function formatArray($className, array $columns, &$output = array(), array $attributes, Logger $logger) {

        if(!array_key_exists($className, $attributes)) {
            return;
        }
        $list = $attributes[$className];

        $columns = array_flip($columns);
       if(is_array(current($list))){
            foreach($list as $row) {
                $newRow = array_intersect_key($row, $columns);
                $output[self::trimNamespacing($className)][] = $newRow;
             }
        } else {

            $newRow = array_intersect_key($list, $columns);
                $output[self::trimNamespacing($className)][] = $newRow;
        }

    }

    private static function trimNamespacing($key) {
        $chunks = explode('\\', $key);
        return array_pop($chunks);
    }

}


text:
package functional.programming;

/**
 A function is a higher order function if at least one of the following conditions are met:

    The function takes one or more functions as parameters.
    The function returns another function as result.

 * @author SAtul
 *
 */
public class HigherOrderFunction1 {

	public static void main(String[] args) {
		HigherOrderFunction1 main = new HigherOrderFunction1();
		IFactory<String> func = main.createFactory(() -> "Producer", (c) -> System.out.println("Configuring " + c));
		func.create();
	}

	public <T> IFactory<T> createFactory(IProducer<T> producer, IConfigurator<T> configurator) {
		return () -> {
			T instance = producer.produce();
			configurator.configure(instance);
			return instance;
		};
	}

}

interface IFactory<T> {
	T create();
}

interface IProducer<T> {
	T produce();
}

interface IConfigurator<T> {
	void configure(T t);
}


text:
Whale::Whale(Graphics& graphics, int x, int y) : WaterObject(x, y, 0.25f) {
  // 90 frames makes the whale only appear 10% of the time
  sprite = std::shared_ptr<Sprite>(new AnimatedSprite(graphics, "boats", 32, 32, 16, 16, 90));
}

void Whale::update(std::shared_ptr<Map> map, int elapsed) {
  WaterObject::update(map, elapsed);

  if (is_moving()) return;

  Direction d = static_cast<Direction>(rand() % 4);
  switch (d) {
    case UP:
      if (map->is_water(x, y - 1)) start_moving(UP);
      break;

    case DOWN:
      if (map->is_water(x, y + 1)) start_moving(DOWN);
      break;

    case LEFT:
      if (map->is_water(x - 1, y)) start_moving(LEFT);
      break;

    case RIGHT:
      if (map->is_water(x + 1, y)) start_moving(RIGHT);
      break;
  }
}

void Whale::draw(Graphics& graphics) {
  int dx = x * 16;
  int dy = y * 16;

  if (is_moving()) {
    switch (facing) {
      case LEFT: dx -= progress * 16; break;
      case RIGHT: dx += progress * 16; break;
      case UP: dy -= progress * 16; break;
      case DOWN: dy += progress * 16; break;
    }
  }

  sprite->draw(graphics, dx, dy);
}


text:
#define LOG_TAG "wayland.Touch"
#include "wheatley.h"

#include <stdlib.h>
#include <string.h>
#include <errno.h>

JNIEXPORT jlong JNICALL
Java_net_jlekstrand_wheatley_wayland_Touch_createNative(JNIEnv *env,
        jclass cls, jlong seatHandle)
{
    struct wlb_seat *seat = (struct wlb_seat *)(intptr_t)seatHandle;
    struct wlb_touch *touch;

    touch = wlb_touch_create(seat);
    if (touch == NULL) {
        ALOGD("wlb_touch_create failed: %s\n", strerror(errno));
        jni_util_throw_by_name(env, "java/lang/RuntimeException",
                "Failed to create Touch");
    }

    return (jlong)(intptr_t)touch;
}

JNIEXPORT void JNICALL
Java_net_jlekstrand_wheatley_wayland_Touch_destroyNative(JNIEnv *env,
        jclass cls, jlong nativeHandle)
{
    struct wlb_touch *touch = (struct wlb_touch *)(intptr_t)nativeHandle;

    wlb_touch_destroy(touch);
}

JNIEXPORT void JNICALL
Java_net_jlekstrand_wheatley_wayland_Touch_downOnOutputNative(JNIEnv *env,
        jclass cls, jlong nativeHandle, jint time, jint id,
        jlong outputHandle, jfloat x, jfloat y)
{
    struct wlb_touch *touch = (struct wlb_touch *)(intptr_t)nativeHandle;
    struct wlb_output *output = (struct wlb_output *)(intptr_t)outputHandle;

    wlb_touch_down_on_output(touch, time, id, output,
            wl_fixed_from_double(x), wl_fixed_from_double(y));
}

JNIEXPORT void JNICALL
Java_net_jlekstrand_wheatley_wayland_Touch_moveOnOutputNative(JNIEnv *env,
        jclass cls, jlong nativeHandle, jint id,
        jlong outputHandle, jfloat x, jfloat y)
{
    struct wlb_touch *touch = (struct wlb_touch *)(intptr_t)nativeHandle;
    struct wlb_output *output = (struct wlb_output *)(intptr_t)outputHandle;

    wlb_touch_move_on_output(touch, id, output,
            wl_fixed_from_double(x), wl_fixed_from_double(y));
}

JNIEXPORT void JNICALL
Java_net_jlekstrand_wheatley_wayland_Touch_finishFrameNative(JNIEnv *env,
        jclass cls, jlong nativeHandle, jint time)
{
    struct wlb_touch *touch = (struct wlb_touch *)(intptr_t)nativeHandle;

    wlb_touch_finish_frame(touch, time);
}

JNIEXPORT void JNICALL
Java_net_jlekstrand_wheatley_wayland_Touch_upNative(JNIEnv *env,
        jclass cls, jlong nativeHandle, jint time, jint id)
{
    struct wlb_touch *touch = (struct wlb_touch *)(intptr_t)nativeHandle;

    wlb_touch_up(touch, time, id);
}

JNIEXPORT void JNICALL
Java_net_jlekstrand_wheatley_wayland_Touch_cancelNative(JNIEnv *env,
        jclass cls, jlong nativeHandle)
{
    struct wlb_touch *touch = (struct wlb_touch *)(intptr_t)nativeHandle;

    wlb_touch_cancel(touch);
}

/* vim: set ts=4 sw=4 sts=4 expandtab: */


text:
<?php

namespace Api\Transformer;

use Api\Traits\TransformerAwareTrait;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Utility\Inflector;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;
use League\Fractal\TransformerAbstract as FractalTransformerAbstract;

abstract class TransformerAbstract extends FractalTransformerAbstract
{
    use TransformerAwareTrait;

    /**
     * Getter for the resourceKey.
     *
     * @return string
     */
    abstract public function resourceKey();

    /**
     * Transforms the give item.
     *
     * @param mixed $item
     * @param string|Transformer $transformer
     * @param null|string $resourceKey
     * @return Item
     */
    public function item($item, $transformer, $resourceKey = null)
    {
        if(!$transformer instanceof TransformerAbstract) {
            $transformer = $this->getTransformer($transformer);
        }

        $resourceKey = $transformer->resourceKey();
        return parent::item($item, $transformer, $resourceKey);
    }

    /**
     * Transforms the given collection.
     *
     * @param mixed $collection
     * @param string|Transformer $transformer
     * @param null|string $resourceKey
     * @return Collection
     */
    public function collection($collection, $transformer, $resourceKey = null)
    {
        if(!$transformer instanceof TransformerAbstract) {
            $transformer = $this->getTransformer($transformer);
        }

        $resourceKey = $transformer->resourceKey();
        return parent::collection($collection, $transformer, $resourceKey);
    }

    /**
     * Gets the repository for this entity
     *
     * @param EntityInterface $entity
     * @return Table
     */
    protected function _repository($entity)
    {
        $source = $entity->source();
        if ($source === null) {
            list(, $class) = namespaceSplit(get_class($entity));
            $source = Inflector::pluralize($class);
        }
        return TableRegistry::get($source);
    }
}


text:
package com.amazonaws.services.devicefarm.model;

import javax.annotation.Generated;

/**
 * <p>
 * An entity with the same name already exists.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class IdempotencyException extends com.amazonaws.services.devicefarm.model.AWSDeviceFarmException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new IdempotencyException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public IdempotencyException(String message) {
        super(message);
    }

}


text:
""" An illustration of using the NSGA-II multi-objective optimization algorithm
on Constrained Multi-Objective Optimization benchmark function. """

__author__ = 'Jean Pierre Queau, jeanpierre.queau@sbmoffshore.com'

from pybrain.optimization import ConstMultiObjectiveGA
from pybrain.rl.environments.functions.multiobjective import ConstDeb,ConstSrn, \
     ConstOsy,ConstTnk,ConstBnh
import pylab
from scipy import zeros, array

# The Deb function
#f = ConstDeb()
# The Srinivas & Deb function
#f = ConstSrn()
# The Osyczka & Kundu function
#f = ConstOsy()
# The Tanaka function
#f = ConstTnk()
# The Binh & Korn function
f = ConstBnh()
# start at the origin
x0 = zeros(f.indim)

x0 = array([min_ for min_, max_ in f.xbound])

# the optimization for a maximum of 25 generations
n = ConstMultiObjectiveGA(f, x0, storeAllEvaluations = True, populationSize = 100, eliteProportion = 1.0,
    topProportion = 1.0, mutationProb = 1.0, mutationStdDev = 0.3, storeAllPopulations = True, allowEquality = False)
print 'Start Learning'
n.learn(50)
print 'End Learning'
# plotting the results (blue = all evaluated points, red = resulting pareto front)
print 'Plotting the Results'
print 'All Evaluations.... take some time'
for x in n._allEvaluations:
    if x[1]:
        pylab.plot([x[0][0]], [x[0][1]], 'b.')
    else:
        pylab.plot([x[0][0]], [x[0][1]], 'r.')
for x in n.bestEvaluation: pylab.plot([x[0][0]], [x[0][1]], 'go')
pylab.show()
print 'Pareto Front'
for x in n.bestEvaluation: pylab.plot([x[0][0]], [x[0][1]], 'go')
pylab.show()

print '==========='
print '= Results ='
print '==========='
'''
i=0
for gen in n._allGenerations:
    print 'Generation: ',i
    for j in range(len(gen[1])):
        print gen[1].keys()[j],gen[1].values()[j]
    i+=1
'''
print 'Population size ',n.populationSize
print 'Elitism Proportion ',n.eliteProportion
print 'Mutation Probability ',n.mutationProb
print 'Mutation Std Deviation ',n.mutationStdDev
print 'Objective Evaluation number ',n.numEvaluations
print 'last generation Length of bestEvaluation ',len(n.bestEvaluation)
print 'Best Evaluable : Best Evaluation'
for i in range(len(n.bestEvaluation)):
    assert len(n.bestEvaluation) == len(n.bestEvaluable)
    print n.bestEvaluable[i],':',n.bestEvaluation[i]


text:
package org.mockitousage;

import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;

import java.util.Date;
import java.util.GregorianCalendar;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.mockitoutil.TestBase;

@SuppressWarnings("unchecked")
public class PlaygroundWithDemoOfUnclonedParametersProblemTest extends TestBase {

    ImportManager importManager;
    ImportLogDao importLogDao;
    IImportHandler importHandler;

    @Before
    public void setUp() throws Exception {
        importLogDao = Mockito.mock(ImportLogDao.class);
        importHandler = Mockito.mock(IImportHandler.class);
        importManager = new ImportManager(importLogDao);
    }

    @Test
    public void shouldIncludeInitialLog() {
        //given
        int importType = 0;
        Date currentDate = new GregorianCalendar(2009, 10, 12).getTime();

        ImportLogBean initialLog = new ImportLogBean(currentDate, importType);
        initialLog.setStatus(1);

        given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate)).willReturn(false);
        willAnswer(byCheckingLogEquals(initialLog)).given(importLogDao).include(any(ImportLogBean.class));

        //when
        importManager.startImportProcess(importType, currentDate);

        //then
        verify(importLogDao).include(any(ImportLogBean.class));
    }

    @Test
    public void shouldAlterFinalLog() {
        //given
        int importType = 0;
        Date currentDate = new GregorianCalendar(2009, 10, 12).getTime();

        ImportLogBean finalLog = new ImportLogBean(currentDate, importType);
        finalLog.setStatus(9);

        given(importLogDao.anyImportRunningOrRunnedToday(importType, currentDate)).willReturn(false);
        willAnswer(byCheckingLogEquals(finalLog)).given(importLogDao).alter(any(ImportLogBean.class));

        //when
        importManager.startImportProcess(importType, currentDate);

        //then
        verify(importLogDao).alter(any(ImportLogBean.class));
    }

    private Answer byCheckingLogEquals(final ImportLogBean status) {
        return new Answer() {
            public Object answer(InvocationOnMock invocation) throws Throwable {
                ImportLogBean bean = (ImportLogBean) invocation.getArguments()[0];
                assertEquals(status, bean);
                return null;
            }
        };
    }

    public class ImportManager {

        public ImportManager(ImportLogDao pImportLogDao) {
            super();
            importLogDao = pImportLogDao;
        }

        private ImportLogDao importLogDao = null;

        public void startImportProcess(int importType, Date date) {
            ImportLogBean importLogBean = null;

            try {
                importLogBean = createResume(importType, date);
                if (isOkToImport(importType, date)) {
                    // get the right handler
                    //importLogBean = ImportHandlerFactory.singleton().getImportHandler(importType).processImport(importLogBean);
                    // 2 = ok
                    importLogBean.setStatus(2);
                } else {
                    // 5 = failed - is there a running process
                    importLogBean.setStatus(9);
                }
            } catch (Exception e) {
                // 9 = failed - exception
                if (importLogBean != null)
                    importLogBean.setStatus(9);
            } finally {
                if (importLogBean != null)
                    finalizeResume(importLogBean);
            }
        }

        private boolean isOkToImport(int importType, Date date) {
            return importLogDao.anyImportRunningOrRunnedToday(importType, date);
        }

        private ImportLogBean createResume(int importType, Date date) {
            ImportLogBean importLogBean = new ImportLogBean(date,
                    importType);
            // 1 = running
            importLogBean.setStatus(1);
            importLogDao.include(importLogBean);
            return importLogBean;
        }

        private void finalizeResume(ImportLogBean importLogBean) {
            importLogDao.alter(importLogBean);
        }
    }

    private interface ImportLogDao {
        public boolean anyImportRunningOrRunnedToday(int importType, Date currentDate);

        void include(ImportLogBean importLogBean);

        void alter(ImportLogBean importLogBean);
    }

    private class IImportHandler {
    }

    private class ImportLogBean {
        private Date currentDate;
        private int importType;
        private int status;

        public ImportLogBean(Date currentDate, int importType) {
            this.currentDate = currentDate;
            this.importType = importType;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof ImportLogBean)) return false;

            ImportLogBean that = (ImportLogBean) o;

            if (importType != that.importType) return false;
            if (status != that.status) return false;
            if (currentDate != null ? !currentDate.equals(that.currentDate) : that.currentDate != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = currentDate != null ? currentDate.hashCode() : 0;
            result = 31 * result + importType;
            result = 31 * result + status;
            return result;
        }
    }
}


text:
/*
makes relative time out of "Sun Jul 08 19:01:12 +0000 2007" type string
Borrowed from Mike Demers (slightly altered)
https://twitter.pbwiki.com/RelativeTimeScripts
*/
function get_relative_time(time_value) {

	// air.trace(time_value);
	//
	// return time_value;
	//
	// time.start('getUnixTime');
	// var unixtime = Date.parse(time_value);
	// time.stop('getUnixTime');
	//
	// time.start('setParsedDate');
	var parsed_date = new Date(time_value);
	// parsed_date.setTime(unixtime);
	// time.stop('setParsedDate');
	//
	// time.start('getNow');
	var now = new Date;
	// time.stop('getNow');
	//
	// time.start('calcDelta');
	var delta = parseInt( (now.getTime() - parsed_date.getTime()) / 1000);
	// time.stop('calcDelta');

	if (delta < 10) {
		return 'Just now';
	} else if(delta < 60) {
		return delta.toString() +' sec ago';
	} else if(delta < 120) {
		return '1 min ago';
	} else if(delta < (45*60)) {
		return Math.round(parseInt(delta / 60)).toString() + ' min ago';
	} else if(delta < (90*60)) {
		return '1 hr ago';
	} else if(delta < (24*60*60)) {
		if (Math.round(delta / 3600) == 1) {
			return '2 hr ago';
		} else {
			return Math.round(delta / 3600).toString() + ' hr ago';
		}
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return Math.round(delta / 86400).toString() + ' days ago';
	}
}

function httpTimeToInt(entryDate) {
	var parsedDate = new Date;
	parsedDate.setTime(Date.parse(entryDate));
	return parsedDate.getTime();
	// var now = new Date;
}

function getTimeAsInt() {
	var now = new Date;
	return now.getTime();
}


text:
layout: bidder
title: Rtbdemand bidder
description: Prebid Rtbdemand Media Bidder Adapter
top_nav_section: dev_docs
nav_section: reference
pbjs: true
biddercode: rtbdemand
enable_download: false
pbjs_version_notes: not ported to 5.x
---

### Bid Params

{: .table .table-bordered .table-striped }
| Name     | Scope    | Description                         | Example                   | Type     |
|----------|----------|-------------------------------------|---------------------------|----------|
| `zoneid` | required | The ad zone or tag specific ID      | `'9999'`                  | `string` |
| `floor`  | optional | The floor CPM price for the request | `0.1234`                  | `float`  |
| `server` | optional | Bidder domain                       | `'bidding.rtbdemand.com'` | `string` |


text:
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NBitcoin;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.P2P.Peer;
using Stratis.Bitcoin.P2P.Protocol.Payloads;
using Stratis.Bitcoin.Utilities;
using Stratis.Bitcoin.Utilities.Extensions;

namespace Stratis.Bitcoin.P2P
{
    ///
    /// The connector used to connect to peers specified with the -addnode argument
    ///
    public sealed class PeerConnectorAddNode : PeerConnector
    {
        /// Constructor for dependency injection.
        public PeerConnectorAddNode(
            IAsyncLoopFactory asyncLoopFactory,
            IDateTimeProvider dateTimeProvider,
            ILoggerFactory loggerFactory,
            Network network,
            INetworkPeerFactory networkPeerFactory,
            INodeLifetime nodeLifetime,
            NodeSettings nodeSettings,
            ConnectionManagerSettings connectionSettings,
            IPeerAddressManager peerAddressManager,
            ISelfEndpointTracker selfEndpointTracker) :
            base(asyncLoopFactory, dateTimeProvider, loggerFactory, network, networkPeerFactory, nodeLifetime, nodeSettings, connectionSettings, peerAddressManager, selfEndpointTracker)
        {
            this.Requirements.RequiredServices = NetworkPeerServices.Nothing;
        }

        /// <inheritdoc/>
        public override void OnInitialize()
        {
            // For the -addnode connector, effectively disable burst mode by preventing high frequency connection attempts.
            // The initial -addnode list will all have their connection attempts made in parallel regardless, so this
            // does not slow down the startup.
            this.burstConnectionInterval = TimeSpans.Second;

            this.MaxOutboundConnections = this.ConnectionSettings.AddNode.Count;

            // Add the endpoints from the -addnode arg to the address manager.
            foreach (IPEndPoint ipEndpoint in this.ConnectionSettings.AddNode)
            {
                this.peerAddressManager.AddPeer(ipEndpoint.MapToIpv6(), IPAddress.Loopback);
            }
        }

        /// This connector is always started.
        public override bool CanStartConnect
        {
            get { return true; }
        }

        /// <inheritdoc/>
        public override void OnStartConnect()
        {
            this.CurrentParameters.PeerAddressManagerBehaviour().Mode = PeerAddressManagerBehaviourMode.AdvertiseDiscover;
        }

        ///
        /// Only connect to nodes as specified in the -addnode arg.
        ///
        public override async Task OnConnectAsync()
        {
            await this.ConnectionSettings.AddNode.ForEachAsync(this.ConnectionSettings.MaxOutboundConnections, this.nodeLifetime.ApplicationStopping,
                async (ipEndpoint, cancellation) =>
                {
                    if (this.nodeLifetime.ApplicationStopping.IsCancellationRequested)
                        return;

                    PeerAddress peerAddress = this.peerAddressManager.FindPeer(ipEndpoint);
                    if (peerAddress != null && !this.IsPeerConnected(peerAddress.Endpoint))
                    {
                        await this.ConnectAsync(peerAddress).ConfigureAwait(false);
                    }
                }).ConfigureAwait(false);
        }
    }
}


text:
      Previous

      Next


text:
.class final Landroid/view/ViewRootImpl$ImeInputStage;
.super Landroid/view/ViewRootImpl$AsyncInputStage;
.source "ViewRootImpl.java"

# interfaces
.implements Landroid/view/inputmethod/InputMethodManager$FinishedInputEventCallback;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/ViewRootImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x10
    name = "ImeInputStage"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/view/ViewRootImpl;

# direct methods
.method public constructor <init>(Landroid/view/ViewRootImpl;Landroid/view/ViewRootImpl$InputStage;Ljava/lang/String;)V
    .locals 0

    iput-object p1, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    invoke-direct {p0, p1, p2, p3}, Landroid/view/ViewRootImpl$AsyncInputStage;-><init>(Landroid/view/ViewRootImpl;Landroid/view/ViewRootImpl$InputStage;Ljava/lang/String;)V

    return-void
.end method

# virtual methods
.method public onFinishedInputEvent(Ljava/lang/Object;Z)V
    .locals 3

    move-object v0, p1

    check-cast v0, Landroid/view/ViewRootImpl$QueuedInputEvent;

    if-eqz p2, :cond_0

    const/4 v1, 0x1

    invoke-virtual {p0, v0, v1}, Landroid/view/ViewRootImpl$ImeInputStage;->finish(Landroid/view/ViewRootImpl$QueuedInputEvent;Z)V

    iget-object v1, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    invoke-static {v1}, Landroid/view/ViewRootImpl;->-get7(Landroid/view/ViewRootImpl;)Ljava/lang/String;

    move-result-object v1

    const-string/jumbo v2, "The input has been finished in ImeInputStage."

    invoke-static {v1, v2}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    return-void

    :cond_0
    invoke-virtual {p0, v0}, Landroid/view/ViewRootImpl$ImeInputStage;->forward(Landroid/view/ViewRootImpl$QueuedInputEvent;)V

    return-void
.end method

.method protected onProcess(Landroid/view/ViewRootImpl$QueuedInputEvent;)I
    .locals 6

    const/4 v5, 0x1

    const/4 v4, 0x0

    iget-object v3, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    iget-boolean v3, v3, Landroid/view/ViewRootImpl;->mLastWasImTarget:Z

    if-eqz v3, :cond_2

    iget-object v3, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    invoke-static {v3}, Landroid/view/ViewRootImpl;->-wrap3(Landroid/view/ViewRootImpl;)Z

    move-result v3

    xor-int/lit8 v3, v3, 0x1

    if-eqz v3, :cond_2

    invoke-static {}, Landroid/view/inputmethod/InputMethodManager;->peekInstance()Landroid/view/inputmethod/InputMethodManager;

    move-result-object v1

    if-eqz v1, :cond_2

    iget-object v0, p1, Landroid/view/ViewRootImpl$QueuedInputEvent;->mEvent:Landroid/view/InputEvent;

    iget-object v3, p0, Landroid/view/ViewRootImpl$ImeInputStage;->this$0:Landroid/view/ViewRootImpl;

    iget-object v3, v3, Landroid/view/ViewRootImpl;->mHandler:Landroid/view/ViewRootImpl$ViewRootHandler;

    invoke-virtual {v1, v0, p1, p0, v3}, Landroid/view/inputmethod/InputMethodManager;->dispatchInputEvent(Landroid/view/InputEvent;Ljava/lang/Object;Landroid/view/inputmethod/InputMethodManager$FinishedInputEventCallback;Landroid/os/Handler;)I

    move-result v2

    if-ne v2, v5, :cond_0

    return v5

    :cond_0
    if-nez v2, :cond_1

    return v4

    :cond_1
    const/4 v3, 0x3

    return v3

    :cond_2
    return v4
.end method


text:
#include "ui/UIText.h"

NS_CC_BEGIN

namespace ui {

static const int LABEL_RENDERER_Z = (-1);

IMPLEMENT_CLASS_GUI_INFO(Text)

Text::Text():
_touchScaleChangeEnabled(false),
_normalScaleValueX(1.0f),
_normalScaleValueY(1.0f),
_fontName("Thonburi"),
_fontSize(10),
_onSelectedScaleOffset(0.5),
_labelRenderer(nullptr)
{
}

Text::~Text()
{

}

Text* Text::create()
{
    Text* widget = new Text();
    if (widget && widget->init())
    {
        widget->autorelease();
        return widget;
    }
    CC_SAFE_DELETE(widget);
    return nullptr;
}

bool Text::init()
{
    if (Widget::init())
    {
        return true;
    }
    return false;
}

void Text::initRenderer()
{
    _labelRenderer = LabelTTF::create();
    Node::addChild(_labelRenderer, LABEL_RENDERER_Z, -1);
}

void Text::setText(const std::string& text)
{
    _labelRenderer->setString(text);
    labelScaleChangedWithSize();
}

const std::string& Text::getStringValue()
{
    return _labelRenderer->getString();
}

ssize_t Text::getStringLength()
{
    return _labelRenderer->getString().size();
}

void Text::setFontSize(int size)
{
    _fontSize = size;
    _labelRenderer->setFontSize(size);
    labelScaleChangedWithSize();
}

int Text::getFontSize()
{
    return _fontSize;
}

void Text::setFontName(const std::string& name)
{
    _fontName = name;
    _labelRenderer->setFontName(name);
    labelScaleChangedWithSize();
}

const std::string& Text::getFontName()
{
    return _fontName;
}

void Text::setTextAreaSize(const Size &size)
{
    _labelRenderer->setDimensions(size);
    labelScaleChangedWithSize();
}

const Size& Text::getTextAreaSize()
{
    return _labelRenderer->getDimensions();
}

void Text::setTextHorizontalAlignment(TextHAlignment alignment)
{
    _labelRenderer->setHorizontalAlignment(alignment);
    labelScaleChangedWithSize();
}

TextHAlignment Text::getTextHorizontalAlignment()
{
    return _labelRenderer->getHorizontalAlignment();
}

void Text::setTextVerticalAlignment(TextVAlignment alignment)
{
    _labelRenderer->setVerticalAlignment(alignment);
    labelScaleChangedWithSize();
}

TextVAlignment Text::getTextVerticalAlignment()
{
    return _labelRenderer->getVerticalAlignment();
}

void Text::setTouchScaleChangeEnabled(bool enable)
{
    _touchScaleChangeEnabled = enable;
}

bool Text::isTouchScaleChangeEnabled()
{
    return _touchScaleChangeEnabled;
}

void Text::onPressStateChangedToNormal()
{
    if (!_touchScaleChangeEnabled)
    {
        return;
    }
    _labelRenderer->setScale(_normalScaleValueX, _normalScaleValueY);
}

void Text::onPressStateChangedToPressed()
{
    if (!_touchScaleChangeEnabled)
    {
        return;
    }
    _labelRenderer->setScale(_normalScaleValueX + _onSelectedScaleOffset, _normalScaleValueY + _onSelectedScaleOffset);
}

void Text::onPressStateChangedToDisabled()
{

}

void Text::updateFlippedX()
{
    _labelRenderer->setFlippedX(_flippedX);

}

void Text::updateFlippedY()
{
    _labelRenderer->setFlippedY(_flippedY);
}

void Text::setAnchorPoint(const Point &pt)
{
    Widget::setAnchorPoint(pt);
    _labelRenderer->setAnchorPoint(pt);
}

void Text::onSizeChanged()
{
    Widget::onSizeChanged();
    labelScaleChangedWithSize();
}

const Size& Text::getContentSize() const
{
    return _labelRenderer->getContentSize();
}

Node* Text::getVirtualRenderer()
{
    return _labelRenderer;
}

void Text::labelScaleChangedWithSize()
{
    if (_ignoreSize)
    {
        _labelRenderer->setDimensions(Size::ZERO);
        _labelRenderer->setScale(1.0f);
        _size = _labelRenderer->getContentSize();
        _normalScaleValueX = _normalScaleValueY = 1.0f;
    }
    else
    {
        _labelRenderer->setDimensions(_size);
        Size textureSize = _labelRenderer->getContentSize();
        if (textureSize.width <= 0.0f || textureSize.height <= 0.0f)
        {
            _labelRenderer->setScale(1.0f);
            return;
        }
        float scaleX = _size.width / textureSize.width;
        float scaleY = _size.height / textureSize.height;
        _labelRenderer->setScaleX(scaleX);
        _labelRenderer->setScaleY(scaleY);
        _normalScaleValueX = scaleX;
        _normalScaleValueY = scaleY;
    }

}

std::string Text::getDescription() const
{
    return "Label";
}

void Text::updateTextureColor()
{
    updateColorToRenderer(_labelRenderer);
}

void Text::updateTextureOpacity()
{
    updateOpacityToRenderer(_labelRenderer);
}

void Text::updateTextureRGBA()
{
    updateRGBAToRenderer(_labelRenderer);
}

Widget* Text::createCloneInstance()
{
    return Text::create();
}

void Text::copySpecialProperties(Widget *widget)
{
    Text* label = dynamic_cast<Text*>(widget);
    if (label)
    {
        setFontName(label->_fontName.c_str());
        setFontSize(label->_labelRenderer->getFontSize());
        setText(label->getStringValue());
        setTouchScaleChangeEnabled(label->_touchScaleChangeEnabled);
        setTextHorizontalAlignment(label->_labelRenderer->getHorizontalAlignment());
        setTextVerticalAlignment(label->_labelRenderer->getVerticalAlignment());
        setTextAreaSize(label->_labelRenderer->getDimensions());
    }
}

}

NS_CC_END