text:
Tabelizr
========

Responsive sortable tables bro.

Options / Defaults
------------------

````json
{
    breakpoint: 767,
    sort: true,
    respond: true,
    respondStyle: 'split',
    classSwitchOnly: false,
    sortHandler: null,
    onBeforeSort: null,
    onAfterSort: null,
    css : {
        'pinned': {
            'position': 'absolute',
            'left': '0',
            'top': '0',
            'background': '#fff',
            'width': '35%',
            'overflow': 'hidden',
            'overflow-x': 'auto'
        },
        'table-wrapper-nosplit': {
            'overflow': 'scroll',
            '-webkit-overflow-scrolling': 'touch',
            'overflow-y': 'hidden'
        },
        'scrollable': {
            'margin-left': '35%',
            'overflow': 'scroll',
            '-webkit-overflow-scrolling': 'touch',
            'overflow-y': 'hidden'
        },
        'table-wrapper': {
            'white-space': 'nowrap',
            'position': 'relative',
            'margin-bottom': '20px',
            'overflow': 'hidden'
        },
        'sort-trigger': {
            'cursor': 'pointer'
        }
    }
};
````

- `breakpoint`: the point at which the responsive tables kick in (the pixel width of the screen)
- `sort`: enables / disables the row sorter
- `respond`: enables / disable the responsive tables
- `respondStyle`: `split` or `nosplit` - split pins first col in place and make others scrollable, nosplit makes entire table scrollable
- `classSwitchOnly`: enables \ disables the use of inline styles in case you want greater control over the css used
- `sortHandler`: a function that defines how the sort occurs - tabelizr passes the supplied function a conf object with the following properties:
    - `el`: a jquery object representing the attached table
    - `rows`: a jquery object representing the rows
    - `col`: the index of the column being sorted
    - `isSorted`: a boolean that indicates if the column already has a sort direction applied
    - `sortDirection`: a string that indicates the sort direction - `asc` or `desc`
    - `tablizr`: the tablizr plugin object
    - Once finished manipulating the rows you need to call `conf.tablizr.applySort(rows, col, sortDirection);` to apply the sort - see `demo-ajax-sort.html` for an example
- `onBeforeSort`: a callback function to run prior to the sort
- `onAfterSort`: a callback fucntion to run after the sort
- `css`: controls what inline styles are being applied when the table goes into responsive mode.

## Sorting

If you want to use a different value to sort by rather than the cell contents simply add a `data-sort` attribute to the td:

````html
<table class="table">
    <thead>
        <tr>
            <th>Perk</th>
            <th>Description</th>
            <th>ID</th>
            <th>Skill Req</th>
            <th>Perk Req</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-sort="Fish Sticks">Steel Smithing</td>
            <td>Can create Steel armor and weapons at forges, and improve them twice as much.</td>
            <td>000cb40d</td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>Arcane Blacksmith</td>
            <td>You can improve magical weapons and armor.</td>
            <td>0005218e</td>
            <td>60 Smithing</td>
            <td>Steel Smithing</td>
        </tr>
    </tbody>
</table>
````

Limitations
-----------

- the sort functionality doesn't work on nested tables or tables that use colspan or rowspan.
- the sort functionality assumes that the first row is the heading row

Todo
----

- provide a more automated way of attaching ajax sorts
- allow for more data attribute overrides
- improve pagr support


text:
/**
 * Run extension
 */
showdown.subParser('makehtml.runExtension', function (ext, text, options, globals) {
  'use strict';

  if (ext.filter) {
    text = ext.filter(text, globals.converter, options);

  } else if (ext.regex) {
    // TODO remove this when old extension loading mechanism is deprecated
    var re = ext.regex;
    if (!(re instanceof RegExp)) {
      re = new RegExp(re, 'g');
    }
    text = text.replace(re, ext.replace);
  }

  return text;
});

redpajama_set_name: RedPajamaGithub


text:
<?php
////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2014-2016, New York University.
// Copyright (C) 2011-2014, NYU-Poly.
// Copyright (C) 2006-2011, University of Utah.
// All rights reserved.
// Contact: contact@vistrails.org
//
// This file is part of VisTrails.
//
// "Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  - Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  - Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  - Neither the name of the New York University nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
//
////////////////////////////////////////////////////////////////////////////

require_once 'functions.php';
require_once 'config.php';

if (array_key_exists('getvt', $_GET)) {

    $host = $DB_HOST;
    $port = $DB_PORT;
    $dbname = $_GET["db"];
    $vtid = $_GET["getvt"];
    $version = $_GET["version"];
    $version_tag = '';
    $execute = 'False';
    $showspreadsheetonly = 'False';
    $forceDB = 'False';
    $includeFullTree = 'False';
    $embedWorkflow = 'False';

    if(array_key_exists('port', $_GET))
        $port = $_GET['port'];
    if(array_key_exists('host', $_GET))
        $host = $_GET['host'];
    if(array_key_exists('tag', $_GET))
        $version_tag = $_GET['tag'];
    if(array_key_exists('execute', $_GET))
        $execute = $_GET['execute'];
    if(array_key_exists('showspreadsheetonly', $_GET))
        $showspreadsheetonly = $_GET['showspreadsheetonly'];
    if(array_key_exists('forceDB', $_GET))
        $forceDB = $_GET['forceDB'];
    if(array_key_exists('includeFullTree', $_GET))
        $includeFullTree = $_GET['includeFullTree'];
    if(array_key_exists('embedWorkflow', $_GET))
        $embedWorkflow = $_GET['embedWorkflow'];

    $filename = md5($host . '_'. $dbname .'_' . $port .'_' .$vtid . '_' . $version);
    $filename = $filename . ".vtl";

    //change the address below to appropriate folder
    //(with read+write access to apache user) if required
    $fileHandle = fopen($PATH_TO_IMAGES. $filename, 'w') or die("can't open file");
    $text = '<vtlink database="' . $dbname . '" host="'. $host .
            '" port="'. $port . '" vtid="' . $vtid . '" execute="'.
            $execute . '" showSpreadsheetOnly="'. $showspreadsheetonly.
            '" forceDB="'.$forceDB.'"';
    if(strcasecmp($embedWorkflow, 'True') == 0){
        if (strcasecmp($includeFullTree,'True') == 0){
           $request = xmlrpc_encode_request('get_vt_zip', array($host, $port,
                                                                $dbname, $vtid));
           $response = do_call($VT_HOST,$VT_PORT,$request);
           $vtcontent = get_vt_from_response($response);
           $text .= ' version="' . $version . '" tag="' . $version_tag .'"';
           //echo $vtcontent;
        }
        else{
           $request = xmlrpc_encode_request('get_wf_vt_zip', array($host, $port,
                                                                $dbname, $vtid,
                                                                $version));
           $response = do_call($VT_HOST,$VT_PORT,$request);
           $vtcontent = get_vt_from_response($response);
           //when a workflow is embedded the version is written only when
           //forceDB is True. Or else version points to the wrong workflow
           if (strcasecmp($forceDB, 'True') == 0){
                $text .= ' version="' . $version . '" tag="' . $version_tag .'"';
           }
        }
        $text .= ' vtcontent="'.$vtcontent .'"';
    }
    else{
        $text .= ' version="' . $version . '" tag="' . $version_tag .'"';
    }
    $text .= ' />';
    fputs($fileHandle, $text);
    fclose($fileHandle);

    header("Content-Type: text/vistrails");
    header("Content-Disposition: attachment;filename=" . $filename);

    //the address below should be the same as one above in line 12
    readfile($PATH_TO_IMAGES.$filename);
    exit();
}
function get_vt_from_response($xmlstring) {
    try{
        $node = @new SimpleXMLElement($xmlstring);
        return $node->params[0]->param[0]->value[0]->array[0]->data[0]->value[0]->string[0];
    } catch(Exception $e) {
        echo "bad xml";
    }
}
?>

<html>
<head>
<title>Vistrails Download</title>
<body>

Wrong parameters set!

</body>
</html>
<? //Ends ?>


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..","..",".."))

require 'puppet_x/elastic/plugin_parsing'

module Puppet::Parser::Functions
  newfunction(
    :es_plugin_name,
    :type => :rvalue,
    :doc => <<-'ENDHEREDOC') do |args|
    Given a string, return the best guess at what the directory name
    will be for the given plugin. Any arguments past the first will
    be fallbacks (using the same logic) should the first fail.

    For example, all the following return values are "plug":

        es_plugin_name('plug')
        es_plugin_name('foo/plug')
        es_plugin_name('foo/plug/1.0.0')
        es_plugin_name('foo/elasticsearch-plug')
        es_plugin_name('foo/es-plug/1.3.2')

    @return String
    ENDHEREDOC

    if args.length < 1
      raise Puppet::ParseError,
        'wrong number of arguments, at least one value required'
    end

    ret = args.select do |arg|
      arg.is_a? String and not arg.empty?
    end.first

    if ret
      Puppet_X::Elastic::plugin_name ret
    else
      raise Puppet::Error,
        'could not determine plugin name'
    end
  end
end


text:
package basellog

//适配器接口
type AdapterInterface interface {
	InitLlogger(channelLength int64)                        //日志适配器初始化
	SetLloggers(configinfo []byte) error                    //通过配置信息配置日志
	SetLlogger(adaptername string, configinfo []byte) error //指定适配器,通过配置信息配置日志
	Debug(val ...interface{})
	Info(val ...interface{})
	Warn(val ...interface{})
	Error(val ...interface{})
	Fatal(val ...interface{})
	Debugf(format string, val ...interface{})
	Infof(format string, val ...interface{})
	Warnf(format string, val ...interface{})
	Errorf(format string, val ...interface{})
	Fatalf(format string, val ...interface{})
}


text:
from setuptools import setup, find_packages
setup(
    name="terminal_advisor",
    version="1.1",
    packages=find_packages(),
    install_requires=['bs4', 'configparser', 'keyring', 'pdfkit', 'PyQt5', 'selenium'],
    package_data={
        '': ['LICENSE.txt'],
    },
    entry_points = {
        'console_scripts': ['terminal_advisor = terminal_advisor.__main__:main'],
    },
    # metadata for upload to PyPI
    author="Cory Nance",
    author_email="canance@coastal.edu",
    description="This script aims to automate mundane tasks in Webadvisor for faculty advisors.",
    license="MIT",
    keywords="webadvisor terminal_advisor",
    url="https://github.com/canance/terminaladvisor",
)


text:
package org.activiti.runtime.api.impl;

import org.activiti.engine.delegate.Expression;
import org.activiti.engine.delegate.VariableScope;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.interceptor.DelegateInterceptor;

public class VariableScopeExpressionEvaluator implements ExpressionEvaluator {

    private VariableScope variableScope;

    public VariableScopeExpressionEvaluator(VariableScope variableScope) {
        this.variableScope = variableScope;
    }

    @Override
    public Object evaluate(Expression expression,
        ExpressionManager expressionManager,
        DelegateInterceptor delegateInterceptor) {
        return expression.getValue(variableScope);
    }
}


text:
package mil.nga.giat.geowave.examples.ingest;

import mil.nga.giat.geowave.accumulo.BasicAccumuloOperations;
import mil.nga.giat.geowave.store.DataStore;
import mil.nga.giat.geowave.store.index.Index;
import mil.nga.giat.geowave.vector.adapter.FeatureDataAdapter;
import org.apache.log4j.Logger;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class SimpleIngestProducerConsumer extends
		SimpleIngest
{

	private static Logger log = Logger.getLogger(SimpleIngestProducerConsumer.class);
	private final FeatureCollection features = new FeatureCollection();

	public static void main(
			final String[] args ) {
		if (args.length != 5) {
			log.error("Invalid arguments, expected: zookeepers, accumuloInstance, accumuloUser, accumuloPass, geowaveNamespace");
			System.exit(1);
		}

		final SimpleIngestProducerConsumer si = new SimpleIngestProducerConsumer();

		try {
			final BasicAccumuloOperations bao = si.getAccumuloOperationsInstance(
					args[0],
					args[1],
					args[2],
					args[3],
					args[4]);
			final DataStore geowaveDataStore = si.getGeowaveDataStore(bao);
			si.generateGrid(geowaveDataStore);
		}
		catch (final Exception e) {
			log.error(
					"Error creating BasicAccumuloOperations",
					e);
			System.exit(1);
		}

		System.out.println("Finished ingesting data to namespace: " + args[4] + " at accumulo instance: " + args[1]);

	}

	/***
	 * Here we will change the ingest mechanism to use a producer/consumer
	 * pattern
	 */
	@Override
	protected void generateGrid(
			final DataStore geowaveDataStore ) {

		// In order to store data we need to determine the type of data store
		final SimpleFeatureType point = createPointFeatureType();

		// This a factory class that builds simple feature objects based on the
		// type passed
		final SimpleFeatureBuilder pointBuilder = new SimpleFeatureBuilder(
				point);

		// This is an adapter, that is needed to describe how to persist the
		// data type passed
		final FeatureDataAdapter adapter = createDataAdapter(point);

		// This describes how to index the data
		final Index index = createSpatialIndex();

		final Thread ingestThread = new Thread(
				new Runnable() {
					@Override
					public void run() {
						geowaveDataStore.ingest(
								adapter,
								index,
								features);
					}
				},
				"Ingestion Thread");

		ingestThread.start();

		// build a grid of points across the globe at each whole
		// latitude/longitude intersection
		for (SimpleFeature sft : getGriddedFeatures(
				pointBuilder,
				-10000)) {
			features.add(sft);
		}
		features.ingestCompleted = true;
		try {
			ingestThread.join();
		}
		catch (final InterruptedException e) {
			log.error(
					"Error joining ingest thread",
					e);
		}
	}

	protected static class FeatureCollection implements
			Iterator<SimpleFeature>
	{
		private final BlockingQueue<SimpleFeature> queue = new LinkedBlockingQueue<>(
				10000);
		public boolean ingestCompleted = false;

		public void add(
				final SimpleFeature sft ) {
			try {
				queue.put(sft);
			}
			catch (final InterruptedException e) {
				log.error(
						"Error inserting next item into queue",
						e);
			}
		}

		@Override
		public boolean hasNext() {
			return !(ingestCompleted && queue.isEmpty());
		}

		@Override
		public SimpleFeature next() {
			try {
				return queue.take();
			}
			catch (final InterruptedException e) {
				log.error(
						"Error getting next item from queue",
						e);
			}
			return null;
		}

		@Override
		public void remove() {
			log.error("Remove called, method not implemented");
		}
	}
}


text:
package trip;

/* You MAY add public @Test methods to this class.  You may also add
 * additional public classes containing "Testing" in their name. These
 * may not be part of your trip package per se (that is, it must be
 * possible to remove them and still have your package work). */

import org.junit.Test;
import ucb.junit.textui;
import static org.junit.Assert.*;

/** Unit tests for the trip package. */
public class UnitTest {

    /** Run all JUnit tests in the graph package. */
    public static void main(String[] ignored) {
        System.exit(textui.runClasses(trip.UnitTest.class));
    }

    @Test
    public void dummyTest() {
    }

}


text:
<?php

namespace Magento\CatalogRule\Model\Product;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\PriceModifierInterface;
use Magento\CatalogRule\Model\RuleFactory;

class PriceModifier implements PriceModifierInterface
{
    /**
     * @var \Magento\CatalogRule\Model\RuleFactory
     */
    protected $ruleFactory;

    /**
     * @param RuleFactory $ruleFactory
     */
    public function __construct(RuleFactory $ruleFactory)
    {
        $this->ruleFactory = $ruleFactory;
    }

    /**
     * Modify price
     *
     * @param mixed $price
     * @param Product $product
     * @return mixed
     */
    public function modifyPrice($price, Product $product)
    {
        if ($price !== null) {
            $resultPrice = $this->ruleFactory->create()->calcProductPriceRule($product, $price);
            if ($resultPrice !== null) {
                $price = $resultPrice;
            }
        }
        return $price;
    }
}


text:
#include "main/glheader.h"
#include "main/mtypes.h"
#include "main/imports.h"
#include "program/prog_cache.h"
#include "program/program.h"

struct cache_item
{
   GLuint hash;
   void *key;
   struct gl_program *program;
   struct cache_item *next;
};

struct gl_program_cache
{
   struct cache_item **items;
   struct cache_item *last;
   GLuint size, n_items;
};

/**
 * Compute hash index from state key.
 */
static GLuint
hash_key(const void *key, GLuint key_size)
{
   const GLuint *ikey = (const GLuint *) key;
   GLuint hash = 0, i;

   assert(key_size >= 4);

   /* Make a slightly better attempt at a hash function:
    */
   for (i = 0; i < key_size / sizeof(*ikey); i++)
   {
      hash += ikey[i];
      hash += (hash << 10);
      hash ^= (hash >> 6);
   }

   return hash;
}

/**
 * Rebuild/expand the hash table to accomodate more entries
 */
static void
rehash(struct gl_program_cache *cache)
{
   struct cache_item **items;
   struct cache_item *c, *next;
   GLuint size, i;

   cache->last = NULL;

   size = cache->size * 3;
   items = (struct cache_item**) malloc(size * sizeof(*items));
   memset(items, 0, size * sizeof(*items));

   for (i = 0; i < cache->size; i++)
      for (c = cache->items[i]; c; c = next) {
	 next = c->next;
	 c->next = items[c->hash % size];
	 items[c->hash % size] = c;
      }

   free(cache->items);
   cache->items = items;
   cache->size = size;
}

static void
clear_cache(GLcontext *ctx, struct gl_program_cache *cache)
{
   struct cache_item *c, *next;
   GLuint i;

   cache->last = NULL;

   for (i = 0; i < cache->size; i++) {
      for (c = cache->items[i]; c; c = next) {
	 next = c->next;
	 free(c->key);
         _mesa_reference_program(ctx, &c->program, NULL);
	 free(c);
      }
      cache->items[i] = NULL;
   }

   cache->n_items = 0;
}

struct gl_program_cache *
_mesa_new_program_cache(void)
{
   struct gl_program_cache *cache = CALLOC_STRUCT(gl_program_cache);
   if (cache) {
      cache->size = 17;
      cache->items = (struct cache_item **)
         calloc(1, cache->size * sizeof(struct cache_item));
      if (!cache->items) {
         free(cache);
         return NULL;
      }
   }
   return cache;
}

void
_mesa_delete_program_cache(GLcontext *ctx, struct gl_program_cache *cache)
{
   clear_cache(ctx, cache);
   free(cache->items);
   free(cache);
}

struct gl_program *
_mesa_search_program_cache(struct gl_program_cache *cache,
                           const void *key, GLuint keysize)
{
   if (cache->last &&
       memcmp(cache->last->key, key, keysize) == 0) {
      return cache->last->program;
   }
   else {
      const GLuint hash = hash_key(key, keysize);
      struct cache_item *c;

      for (c = cache->items[hash % cache->size]; c; c = c->next) {
         if (c->hash == hash && memcmp(c->key, key, keysize) == 0) {
            cache->last = c;
            return c->program;
         }
      }

      return NULL;
   }
}

void
_mesa_program_cache_insert(GLcontext *ctx,
                           struct gl_program_cache *cache,
                           const void *key, GLuint keysize,
                           struct gl_program *program)
{
   const GLuint hash = hash_key(key, keysize);
   struct cache_item *c = CALLOC_STRUCT(cache_item);

   c->hash = hash;

   c->key = malloc(keysize);
   memcpy(c->key, key, keysize);

   c->program = program;  /* no refcount change */

   if (cache->n_items > cache->size * 1.5) {
      if (cache->size < 1000)
	 rehash(cache);
      else
	 clear_cache(ctx, cache);
   }

   cache->n_items++;
   c->next = cache->items[hash % cache->size];
   cache->items[hash % cache->size] = c;
}


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res) {
    var obj = {title: 'Angular tutorial'};
    res.render('requirec', obj);
});

module.exports = router;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400,300,700,800' rel='stylesheet' type='text/css'>

{{{name}}}

{{{direccion}}}

VALPARAÍSO

Locomoción gratuita desde el 16 al 24 de abril app.


text:
<phpunit bootstrap="tests/bootstrap.php">
    <testsuites>
        <testsuite name="PageCache">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   iron-doc-viewer-behavior.js
 */

import {flush} from '@polymer/polymer/lib/legacy/polymer.dom.js';

import {afterNextRender} from '@polymer/polymer/lib/utils/render-status.js';

export {IronDocViewerBehavior};

interface IronDocViewerBehavior {

  /**
   * The [Polymer
   * Analyzer](https://github.com/Polymer/polymer-analyzer)-generated element
   * descriptor to display details for.
   */
  descriptor: object|null|undefined;

  /**
   * The base href where this doc viewer is located.
   */
  baseHref: string|null|undefined;

  /**
   * Prefix for fragment identifiers used in anchors.
   * For static routing `iron-component-page` can
   * set this to a string identifying the current component.
   */
  fragmentPrefix: string|null|undefined;

  /**
   * Whether protected members should be hidden or shown.
   */
  _showProtected: boolean|null|undefined;

  /**
   * Whether inherited members should be hidden or shown.
   */
  _showInherited: boolean|null|undefined;
  _filterMembers(items: any, showProtected: any, showInherited: any): any;
  _noneToShow(showProtected: any, showInherited: any, descriptor: any, name: any): any;

  /**
   * Scroll to the descriptor (element, function, etc.) with an `anchor-id`
   * matching the given URL hash (`#` optional). If no hash is specified,
   * uses `window.location.hash`.
   *
   * Whichever element or script is in charge of routing should call this
   * method on initial page load and on `hashchange` events.
   */
  scrollToAnchor(hash: any): void;
  _getElementName(element: any): any;
  _getElementId(element: any): any;
  _getPolymerBehaviors(descriptor: any): any;

  /**
   * Compare two analysis descriptors (elements, functions, etc.) by
   * display name.
   */
  _compareDescriptors(a: any, b: any): any;
}

declare const IronDocViewerBehavior: object;


text:
package org.radargun.stages.cache;

import java.util.Random;

import org.radargun.DistStageAck;
import org.radargun.config.Property;
import org.radargun.config.Stage;
import org.radargun.stages.AbstractDistStage;
import org.radargun.stages.cache.background.BackgroundOpsManager;
import org.radargun.traits.BasicOperations;
import org.radargun.traits.CacheInformation;
import org.radargun.traits.InjectTrait;
import org.radargun.traits.LocalBasicOperations;
import org.radargun.traits.Transactional;
import org.radargun.utils.Utils;

/**
 * Distributed stage that will clear the content of the cache wrapper on each slave.
 *
 * @author Mircea Markus <Mircea.Markus@jboss.com>
 */
@Stage(doc = "Removes all data from the cache")
public class ClearCacheStage extends AbstractDistStage {

   @Property(doc = "Execute local variant of clear on each slave. Default is null - local clear is performed, only if it is provided by the service." +
         " True enforces local clear - if given service does not provide the feature, exception is thrown.")
   private Boolean local = null;

   @Property(doc = "Execute the clear inside explicit transaction.")
   private boolean useTransaction = false;

   @Property(doc = "Name of the cache to be cleared. Default is the default cache.")
   private String cacheName;

   @InjectTrait(dependency = InjectTrait.Dependency.MANDATORY)
   private BasicOperations basicOperations;

   @InjectTrait
   private LocalBasicOperations localBasicOperations;

   @InjectTrait
   private Transactional transactional;

   @InjectTrait
   private CacheInformation cacheInformation;

   public DistStageAck executeOnSlave() {
      BackgroundOpsManager.beforeCacheClear(slaveState);
      if (!isServiceRunnning()) {
         log.info("This slave is dead, cannot clear cache.");
         return successfulResponse();
      }
      if (Boolean.TRUE.equals(local) && localBasicOperations == null) {
         return errorResponse("This cache does not support local clear", null);
      }
      if (useTransaction && transactional == null) {
         return errorResponse("This cache does not support transactions", null);
      }
      for (int i = 0; i < 5; i++) {
         try {
            log.info(Utils.printMemoryFootprint(true));
            if (shouldExecute()) {
               DistStageAck response = executeClear();
               if (response != null) return response;
               if (cacheInformation == null) return successfulResponse();
            } else {
               if (Boolean.FALSE.equals(local) || localBasicOperations == null) {
                  int size;
                  for (int count = new Random().nextInt(20) + 10; count > 0 && (size = cacheInformation.getCache(cacheName).getLocalSize()) > 0; --count) {
                     log.debug("Waiting until the cache gets empty (contains " + size + " entries)");
                     Thread.sleep(1000);
                  }
                  if ((size = cacheInformation.getCache(cacheName).getLocalSize()) > 0) {
                     log.error("The cache was not cleared from another node (contains " + size + " entries), clearing locally");
                     DistStageAck response = executeClear();
                     if (response != null) return response;
                     if (cacheInformation == null) return successfulResponse();
                  }
               }
            }
            return successfulResponse();
         } catch (Exception e) {
            log.warn("Failed to clear cache(s)", e);
         } finally {
            System.gc();
            log.info(Utils.printMemoryFootprint(false));
         }
      }
      return errorResponse("Failed to clear the cache.", null);
   }

   protected DistStageAck executeClear() {
      BasicOperations.Cache cache;
      if (!Boolean.FALSE.equals(local) && localBasicOperations != null) {
         cache = localBasicOperations.getLocalCache(cacheName);
      } else {
         cache = basicOperations.getCache(cacheName);
      }
      if (cache == null) {
         return errorResponse("There is no cache '" + cacheName + "'", null);
      }
      Transactional.Transaction tx = null;
      try {
         if (useTransaction) {
            if (transactional.getConfiguration(cacheName) == Transactional.Configuration.NON_TRANSACTIONAL) {
               return errorResponse("No transactions for '" + cacheName + "'", null);
            }
            tx = transactional.getTransaction();
            cache = tx.wrap(cache);
            tx.begin();
         }
         cache.clear();
         if (useTransaction) {
            tx.commit();
         }
      } catch (RuntimeException e) {
         if (tx != null) {
            try {
               tx.rollback();
            } catch (Exception e2) {
               log.error("Cannot roll back", e2);
            }
         }
         throw e;
      }
      return null;
   }
}


text:
<?php
/**
 * The Template for displaying all single posts.
 *
 * @package Forever
 * @since Forever 1.0
 */

get_header(); ?>

			<?php while ( have_posts() ) : the_post(); ?>

				<?php forever_content_nav( 'nav-above' ); ?>

				<?php get_template_part( 'content', 'single' ); ?>

				<?php
					// If comments are open or we have at least one comment, load up the comment template
					if ( comments_open() || '0' != get_comments_number() )
						comments_template( '', true );
				?>

				<?php forever_content_nav( 'nav-below' ); ?>

			<?php endwhile; // end of the loop. ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
package io.rong.callkit;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.Fragment;
import android.widget.Toast;

import java.util.ArrayList;

import io.rong.calllib.RongCallClient;
import io.rong.calllib.RongCallCommon;
import io.rong.calllib.RongCallSession;
import io.rong.common.RLog;
import io.rong.imkit.RongExtension;
import io.rong.imkit.RongIM;
import io.rong.imkit.plugin.IPluginModule;
import io.rong.imkit.utilities.PermissionCheckUtil;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Discussion;

/**
 * Created by weiqinxiao on 16/8/16.
 */
public class VideoPlugin implements IPluginModule {
    private static final String TAG = "VideoPlugin";
    private ArrayList<String> allMembers;
    private Context context;

    private Conversation.ConversationType conversationType;
    private String targetId;

    @Override
    public Drawable obtainDrawable(Context context) {
        return context.getResources().getDrawable(R.drawable.rc_ic_video_selector);
    }

    @Override
    public String obtainTitle(Context context) {
        return context.getString(R.string.rc_voip_video);
    }

    @Override
    public void onClick(Fragment currentFragment, final RongExtension extension) {

        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
        if (!PermissionCheckUtil.requestPermissions(currentFragment, permissions)) {
            return;
        }
        context = currentFragment.getActivity().getApplicationContext();
        conversationType = extension.getConversationType();
        targetId = extension.getTargetId();

        RongCallSession profile = RongCallClient.getInstance().getCallSession();
        if (profile != null && profile.getActiveTime() > 0) {
            Toast.makeText(context,
                    profile.getMediaType() == RongCallCommon.CallMediaType.AUDIO ?
                            context.getString(R.string.rc_voip_call_audio_start_fail) :
                            context.getString(R.string.rc_voip_call_video_start_fail),
                    Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()) {
            Toast.makeText(context, context.getString(R.string.rc_voip_call_network_error), Toast.LENGTH_SHORT).show();
            return;
        }
        if (conversationType.equals(Conversation.ConversationType.PRIVATE)) {
            Intent intent = new Intent(RongVoIPIntent.RONG_INTENT_ACTION_VOIP_SINGLEVIDEO);
            intent.putExtra("conversationType", conversationType.getName().toLowerCase());
            intent.putExtra("targetId", targetId);
            intent.putExtra("callAction", RongCallAction.ACTION_OUTGOING_CALL.getName());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setPackage(context.getPackageName());
            context.getApplicationContext().startActivity(intent);
        } else if (conversationType.equals(Conversation.ConversationType.DISCUSSION)) {
            RongIM.getInstance().getDiscussion(targetId, new RongIMClient.ResultCallback<Discussion>() {
                @Override
                public void onSuccess(Discussion discussion) {

                    Intent intent = new Intent(context, CallSelectMemberActivity.class);
                    allMembers = (ArrayList<String>) discussion.getMemberIdList();
                    intent.putStringArrayListExtra("allMembers", allMembers);
                    String myId = RongIMClient.getInstance().getCurrentUserId();
                    ArrayList<String> invited = new ArrayList<>();
                    invited.add(myId);
                    intent.putStringArrayListExtra("invitedMembers", invited);
                    intent.putExtra("mediaType", RongCallCommon.CallMediaType.VIDEO.getValue());
                    extension.startActivityForPluginResult(intent, 110, VideoPlugin.this);
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {
                    RLog.d(TAG, "get discussion errorCode = " + e.getValue());
                }
            });
        } else if (conversationType.equals(Conversation.ConversationType.GROUP)) {
            Intent intent = new Intent(context, CallSelectMemberActivity.class);
            String myId = RongIMClient.getInstance().getCurrentUserId();
            ArrayList<String> invited = new ArrayList<>();
            invited.add(myId);
            intent.putStringArrayListExtra("invitedMembers", invited);
            intent.putExtra("groupId", targetId);
            intent.putExtra("mediaType", RongCallCommon.CallMediaType.VIDEO.getValue());
            extension.startActivityForPluginResult(intent, 110, this);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        Intent intent = new Intent(RongVoIPIntent.RONG_INTENT_ACTION_VOIP_MULTIVIDEO);
        ArrayList<String> userIds = data.getStringArrayListExtra("invited");
        userIds.add(RongIMClient.getInstance().getCurrentUserId());
        intent.putExtra("conversationType", conversationType.getName().toLowerCase());
        intent.putExtra("targetId", targetId);
        intent.putExtra("callAction", RongCallAction.ACTION_OUTGOING_CALL.getName());
        intent.putStringArrayListExtra("invitedUsers", userIds);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(context.getPackageName());
        context.getApplicationContext().startActivity(intent);
    }
}


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

<project
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>org.aries.pom</groupId>
	<artifactId>file-bom</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Aries FILE Support Bom</name>
	<packaging>pom</packaging>

	<properties>
		<drewnoakes.version>2.4.0-beta-1</drewnoakes.version>
	</properties>

	<dependencyManagement>
		<dependencies>
        	<dependency>
               	<groupId>com.drewnoakes</groupId>
                <artifactId>metadata-extractor</artifactId>
                <version>${drewnoakes.version}</version>
            </dependency>
		</dependencies>
	</dependencyManagement>
</project>


text:
import '../../../common'

window.initMap = () => { }

const ko = require('knockout')
const Listing = require('../../../models/accommodation/listing')
const Map = require('../../../models/accommodation/map')

const listing = new Listing('&hasLocation=true')
const map = new Map()

listing.items.subscribe((newItems) => {
  map.init(newItems)
})

ko.applyBindings({
  listing,
  map
})


text:
#!/usr/bin/env lua
--------------------------------------------------------------------------------
-- @script  Lua Module Pre-Loader
-- @version 1.1
-- @author  Renato Maia <maia@tecgraf.puc-rio.br>
--

local assert = assert
local ipairs = ipairs
local pairs  = pairs
local select = select
local io     = require "io"
local os     = require "os"

module("preloader", require "loop.compiler.Arguments")

local FILE_SEP = "/"
local FUNC_SEP = "_"
local OPEN_PAT = "int%s+luaopen_([%w_]+)%s*%(%s*lua_State%s*%*[%w_]*%);"

help      = false
names     = false
include   = {}
funcname  = ""
output    = "preload"
prefix    = "LUAPRELOAD_API"
directory = ""

_optpat = "^%-(%-?%w+)(=?)(.-)$"
_alias = {
	I = "include",
	["-help"] = "help",
}
for name in pairs(_M) do
	_alias[name:sub(1, 1)] = name
end

local start, errmsg = _M(...)
if not start or help then
	if errmsg then io.stderr:write("ERROR: ", errmsg, "\n") end
	io.stderr:write([[
Lua Module Pre-Loader 1.1  Copyright (C) 2006-2008 Tecgraf, PUC-Rio
Usage: ]],_NAME,[[.lua [options] [inputs]

  [inputs] is a sequence of names that may be header file paths or package
  names, use the options described below to indicate how they should be
  interpreted. If no [inputs] is provided then such names are read from the
  standard input.

Options:

  -d, -directory    Directory where the output files should be generated. Its
                    default is the current directory.

  -I, -i, -include  Adds a directory to the list of paths where the header files
                    are searched.

  -f, -funcname     Name of the generated function that pre-loads all library
                    modules. Its default is 'luapreload_' plus the name defined
                    by option '-output'.

  -n, -names        Flag that indicates provided input names are actually
                    package names and not header files.

  -o, -output       Name used to form the name of the files generated. Two files
                    are generated: a source code file with the sufix '.c' with
                    the pre-loading code and a header file with the sufix '.h'
                    with function signatures. Its default is ']],output,[['.

  -p, -prefix       Prefix added to the signature of the functions generated.
                    Its default is ']],prefix,[['.

]])
	os.exit(1)
end

--------------------------------------------------------------------------------

local function escapepattern(pattern)
	return pattern:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
end

local filesep  = escapepattern(FILE_SEP)
local funcsep  = escapepattern(FUNC_SEP)

local function adjustpath(path)
	if path ~= "" and not path:find(filesep.."$") then
		return path..FILE_SEP
	end
	return path
end

local filepath = adjustpath(directory)..output

if funcname == "" then funcname = "luapreload_"..output end

--------------------------------------------------------------------------------

local function openheader(name)
	local file, errmsg = io.open(name)
	if not file then
		for _, path in ipairs(include) do
			path = adjustpath(path)..name
			file, errmsg = io.open(path)
			if file then break end
		end
	end
	return file, errmsg
end

--------------------------------------------------------------------------------

local outh = assert(io.open(filepath..".h", "w"))

local guard = output:upper():gsub("[^%w]", "_")

outh:write([[
#ifndef __]],guard,[[__
#define __]],guard,[[__

#ifndef ]],prefix,[[
#define ]],prefix,[[
#endif

]],prefix,[[ int ]],funcname,[[(lua_State *L);

#endif /* __]],guard,[[__ */
]])
outh:close()

--------------------------------------------------------------------------------

local inputs = { select(start, ...) }
if #inputs == 0 then
	for name in io.stdin:lines() do
		inputs[#inputs+1] = name
	end
end

local outc = assert(io.open(filepath..".c", "w"))
outc:write([[
#include <lua.h>
#include <lauxlib.h>

]])

for i, input in ipairs(inputs) do
	if names then
		outc:write('int luaopen_',input:gsub("%.", FUNC_SEP),'(lua_State*);\n')
	else
		outc:write('#include "',input,'"\n')
	end
end

outc:write([[
#include "]],output,[[.h"

]],prefix,[[ int ]],funcname,[[(lua_State *L) {
	luaL_findtable(L, LUA_GLOBALSINDEX, "package.preload", ]], #inputs, [[);

]])
local code = [[
	lua_pushcfunction(L, luaopen_%s);
	lua_setfield(L, -2, "%s");
]]
for i, input in ipairs(inputs) do
	if names then
		outc:write(code:format(input:gsub("%.", FUNC_SEP), input))
	else
		local input = assert(openheader(input))
		local header = input:read("*a")
		input:close()
		for func in header:gmatch(OPEN_PAT) do
			outc:write(code:format(func, func:gsub(funcsep, ".")))
		end
	end
end
outc:write([[

	lua_pop(L, 1);
	return 0;
}
]])

outc:close()


text:
package seedu.typed.logic.parser;

import static seedu.typed.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.typed.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT;

import java.util.regex.Matcher;

import seedu.typed.commons.util.FileUtil;
import seedu.typed.logic.commands.Command;
import seedu.typed.logic.commands.ExportCommand;
import seedu.typed.logic.commands.IncorrectCommand;

//@@author A0139392X
/**
 * Parses input argument and exports the file.
 */
public class ExportCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the
     * ExportCommand and returns an SaveCommand object for execution.
     */
    public Command parse(String args) {
        final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
        if (!matcher.matches()) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ExportCommand.MESSAGE_USAGE));
        }

        // keywords delimited by whitespace
        final String[] keywords = matcher.group("keywords").split("\\s+");

        // if there are whitespace, invalid input by user
        if ((keywords.length) != 1) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ExportCommand.MESSAGE_USAGE));
        }

        String fileName = keywords[0];

        if (isAPath(fileName)) {
            return new ExportCommand(1, FileUtil.createProperExtension(fileName));
        } else if (FileUtil.isValidName(fileName)) {
            return new ExportCommand(2, FileUtil.createProperExtension(fileName));
        } else {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ExportCommand.MESSAGE_USAGE));
        }
    }

    /*
     * Returns true is the input given by the user is a path. False otherwise.
     *
     * @param   String fileName
     *              Input given by the user.
     */
    private boolean isAPath(String fileName) {
        return fileName.contains("/");
    }
}
//@@author


text:
package org.openqa.selenium.qtwebkit.quick_tests;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.testing.JUnit4TestBase;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;

public class CoordinatesTest extends JUnit4TestBase {

    @Before
    public void setUpWebDriver()
    {
        driver.get(pages.coordinatesTest);
    }

    @Test
    public void testShouldGetCoordinatesOfAnElementInViewPort() {
        assertThat(getLocationOnScreen(By.id("mainRectangle")), is(new Point(10, 10)));
    }

    @Test
    public void testShouldGetCoordinatesOfAnZeroSizeElement() {
        assertThat(getLocationOnScreen(By.id("zeroSizedElement")), is(new Point(8, 8)));
    }

    @Test
    public void testShouldGetCoordinatesOfATransparentElement() {
        assertThat(getLocationOnScreen(By.id("transparentRect")), is(new Point(10, 120)));
    }

    @Test
    public void testShouldGetCoordinatesOfAHiddenElement() {
        assertThat(getLocationOnScreen(By.id("hiddenRect")), is(new Point(120, 10)));
    }

    @Test
    public void testShouldGetCoordinatesOfAnInvisibleElement() {
        assertThat(getLocationOnScreen(By.id("invisibleItem")), is(new Point(3, 3)));
    }

    private Point getLocationOnScreen(By locator) {
        WebElement element = driver.findElement(locator);
        return ((Locatable) element).getCoordinates().onScreen();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="24dp"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        app:srcCompat="@drawable/ic_code_black_24dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/text_margin_small"
            android:textStyle="bold"
            android:text="Attribute Name"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/text_margin_small"
            android:text="Attribute Value"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </LinearLayout>

</LinearLayout>


text:
package org.apache.ibatis.logging.jdbc;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.ibatis.logging.Log;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class ResultSetLoggerTest {

  @Mock
  private ResultSet rs;

  @Mock
  private Log log;

  @Mock
  private ResultSetMetaData metaData;

  private void setup(int type) throws SQLException {
    when(rs.next()).thenReturn(true);
    when(rs.getMetaData()).thenReturn(metaData);
    when(metaData.getColumnCount()).thenReturn(1);
    when(metaData.getColumnType(1)).thenReturn(type);
    when(metaData.getColumnLabel(1)).thenReturn("ColumnName");
    when(log.isTraceEnabled()).thenReturn(true);
    ResultSet resultSet = ResultSetLogger.newInstance(rs, log, 1);
    resultSet.next();
  }

  @Test
  void shouldNotPrintBlobs() throws SQLException {
    setup(Types.LONGNVARCHAR);
    verify(log).trace("<==    Columns: ColumnName");
    verify(log).trace("<==        Row: <<BLOB>>");
  }

  @Test
  void shouldPrintVarchars() throws SQLException {
    when(rs.getString(1)).thenReturn("value");
    setup(Types.VARCHAR);
    verify(log).trace("<==    Columns: ColumnName");
    verify(log).trace("<==        Row: value");
  }

}


text:
import { newSpecPage } from '@stencil/core/testing';
import { SearchFilterEditor } from '../search-filter-editor';

describe('search-filter-editor', () => {
  it('renders', async () => {
    const page = await newSpecPage({
      components: [SearchFilterEditor],
      html: '<search-filter-editor></search-filter-editor>',
    });
    expect(page.root).toEqualHtml(`
      <search-filter-editor>
        <mock:shadow-root>
          <slot></slot>
        </mock:shadow-root>
      </search-filter-editor>
    `);
  });
});


text:
package org.aeonbits.owner.loaders;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Properties;

/**
 * A {@link Loader loader} able to read properties from standard Java properties files.
 *
 * @since 1.0.5
 * @author Luigi R. Viggiano
 */
public class PropertiesLoader implements Loader {

    private static final long serialVersionUID = -1781643040589572341L;
    private static final String DEFAULT_ENCODING = "UTF-8";

    public boolean accept(URI uri) {
        try {
            uri.toURL();
            return true;
        } catch (MalformedURLException ex) {
            return false;
        }
    }

    public void load(Properties result, URI uri) throws IOException {
        URL url = uri.toURL();
        InputStream input = url.openStream();
        try {
            load(result, input);
        } finally {
            input.close();
        }
    }

    void load(Properties result, InputStream input) throws IOException {
        result.load(new InputStreamReader(input, DEFAULT_ENCODING));
    }

    public String defaultSpecFor(String uriPrefix) {
        return uriPrefix + ".properties";
    }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DMT.Core.Entities;
using DMT.Core.Interfaces;
using DMT.Matcher.Data.Interfaces;

namespace DMT.VIR.Data
{
    [Export(typeof(IEntityFactory))]
    public class VirEntityFactory : CoreEntityFactory
    {
        private readonly static Dictionary<string, Type> nodeTypes = new Dictionary<string, Type>
        {
            { "Person", typeof(Person) },
            { "Group", typeof(Group) },
            { "Membership", typeof(Membership) },
            { "SemesterValuation", typeof(SemesterValuation) },
            { "CommunityScore", typeof(CommunityScore) },

        };

        public VirEntityFactory()
        {
        }

        public override INode CreateNode(string typeInfo)
        {
            Type t = nodeTypes[typeInfo];
            return (INode)Activator.CreateInstance(t, this);
        }

        public override IEdge CreateEdge(INode nodeA, INode nodeB, EdgeDirection direction)
        {
            return new VirEdge(nodeA, nodeB, direction, this);
        }
    }
}


text:
include(VigraAddDep)

set(GIT_REPO "https://github.com/dmlc/xgboost.git")

set(GIT_CLONE_OPTS "--recursive")

function(vad_live)
  # Clone and add the subdirectory.
  git_clone(XGBoost)
  add_subdirectory("${VAD_EXTERNAL_ROOT}/XGBoost" "${VAD_EXTERNAL_ROOT}/XGBoost/build_external_dep")

  add_library(_VAD_XGBoost_STUB INTERFACE)
  list(APPEND _XGBoost_INCLUDE_DIRS "${VAD_EXTERNAL_ROOT}/XGBoost/include" "${VAD_EXTERNAL_ROOT}/XGBoost/dmlc-core/include" "${VAD_EXTERNAL_ROOT}/XGBoost/rabit/include")
  set_property(TARGET _VAD_XGBoost_STUB PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${_XGBoost_INCLUDE_DIRS})
  set_property(TARGET _VAD_XGBoost_STUB PROPERTY INTERFACE_LINK_LIBRARIES rabit libxgboost dmlccore)

  add_library(XGBoost::XGBoost ALIAS _VAD_XGBoost_STUB)
endfunction()


text:
package com.twitter.elephantbird.pig.util;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.pig.ResourceSchema.ResourceFieldSchema;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;

/**
 * Supports conversion between Pig types and {@link LongWritable}.
 *
 * @author Andy Schlaikjer
 */
public class LongWritableConverter extends AbstractWritableConverter<LongWritable> {
  public LongWritableConverter() {
    super(new LongWritable());
  }

  @Override
  public ResourceFieldSchema getLoadSchema() throws IOException {
    ResourceFieldSchema schema = new ResourceFieldSchema();
    schema.setType(DataType.LONG);
    return schema;
  }

  @Override
  public Object bytesToObject(DataByteArray dataByteArray) throws IOException {
    return bytesToLong(dataByteArray.get());
  }

  @Override
  protected String toCharArray(LongWritable writable) throws IOException {
    return String.valueOf(writable.get());
  }

  @Override
  protected Integer toInteger(LongWritable writable) throws IOException {
    return (int) writable.get();
  }

  @Override
  protected Long toLong(LongWritable writable) throws IOException {
    return writable.get();
  }

  @Override
  protected Float toFloat(LongWritable writable) throws IOException {
    return (float) writable.get();
  }

  @Override
  protected Double toDouble(LongWritable writable) throws IOException {
    return (double) writable.get();
  }

  @Override
  public void checkStoreSchema(ResourceFieldSchema schema) throws IOException {
    switch (schema.getType()) {
      case DataType.CHARARRAY:
      case DataType.INTEGER:
      case DataType.LONG:
      case DataType.FLOAT:
      case DataType.DOUBLE:
        return;
    }
    throw new IOException("Pig type '" + DataType.findTypeName(schema.getType()) + "' unsupported");
  }

  @Override
  protected LongWritable toWritable(String value) throws IOException {
    return toWritable(Long.parseLong(value));
  }

  @Override
  protected LongWritable toWritable(Integer value) throws IOException {
    return toWritable(value.longValue());
  }

  @Override
  protected LongWritable toWritable(Long value) throws IOException {
    writable.set(value);
    return writable;
  }

  @Override
  protected LongWritable toWritable(Float value) throws IOException {
    return toWritable(value.longValue());
  }

  @Override
  protected LongWritable toWritable(Double value) throws IOException {
    return toWritable(value.longValue());
  }
}


text:
import pytest
import numpy as np
from .base import TestRefuter

@pytest.mark.usefixtures("fixed_seed")
class TestDataSubsetRefuter(object):
    @pytest.mark.parametrize(["error_tolerance","estimator_method"],
                              [(0.01, "iv.instrumental_variable")])
    def test_refutation_data_subset_refuter_continuous(self, error_tolerance, estimator_method):
        refuter_tester = TestRefuter(error_tolerance, estimator_method, "data_subset_refuter")
        refuter_tester.continuous_treatment_testsuite() # Run both

    @pytest.mark.parametrize(["error_tolerance", "estimator_method"],
                             [(0.01, "backdoor.propensity_score_matching")])
    def test_refutation_data_subset_refuter_binary(self, error_tolerance, estimator_method):
        refuter_tester = TestRefuter(error_tolerance, estimator_method, "data_subset_refuter")
        refuter_tester.binary_treatment_testsuite(tests_to_run="atleast-one-common-cause")


text:
Template[getTemplate('user_edit')].helpers({
  profileIncomplete : function() {
    return this && !this.loading && !userProfileComplete(this);
  },
  userName: function(){
    return getUserName(this);
  },
  userEmail : function(){
    return getEmail(this);
  },
  getTwitter: function(){
    return getTwitterName(this) || "";
  },
  getGitHub: function(){
    return getGitHubName(this) || "";
  },
  profileUrl: function(){
    return getProfileUrlBySlugOrId(this.slug);
  },
  hasNotificationsUsers : function(){
    return getUserSetting('notifications.users', '', this) ? 'checked' : '';
  },
  hasNotificationsPosts : function(){
    return getUserSetting('notifications.posts', '', this) ? 'checked' : '';
  },
  hasNotificationsComments : function(){
    return getUserSetting('notifications.comments', '', this) ? 'checked' : '';
  },
  hasNotificationsReplies : function(){
    return getUserSetting('notifications.replies', '', this) ? 'checked' : '';
  },
  hasPassword: function () {
    return hasPassword(Meteor.user());
  }
});

Template[getTemplate('user_edit')].events({
  'submit #account-form': function(e){
    e.preventDefault();

    clearSeenErrors();
    if(!Meteor.user())
      throwError(i18n.t('you_must_be_logged_in'));

    var $target=$(e.target);
    var name = $target.find('[name=name]').val();
    var email = $target.find('[name=email]').val();
    var user = this;
    var update = {
      "profile.name": name,
      "profile.slug": slugify(name),
      "profile.bio": $target.find('[name=bio]').val(),
      "profile.email": email,
      "profile.twitter": $target.find('[name=twitter]').val(),
      "profile.github": $target.find('[name=github]').val(),
      "profile.site": $target.find('[name=site]').val(),
      "profile.notifications.users": $('input[name=notifications_users]:checked').length, // only actually used for admins
      "profile.notifications.posts": $('input[name=notifications_posts]:checked').length,
      "profile.notifications.comments": $('input[name=notifications_comments]:checked').length,
      "profile.notifications.replies": $('input[name=notifications_replies]:checked').length
    };

    var old_password = $target.find('[name=old_password]').val();
    var new_password = $target.find('[name=new_password]').val();

    if(old_password && new_password){
   		Accounts.changePassword(old_password, new_password, function(error){
        // TODO: interrupt update if there's an error at this point
        if(error)
          throwError(error.reason);
      });
    }

    update = userEditClientCallbacks.reduce(function(result, currentFunction) {
      return currentFunction(user, result);
    }, update);

    Meteor.users.update(user._id, {
      $set: update
    }, function(error){
      if(error){
        throwError(error.reason);
      } else {
        throwError(i18n.t('profile_updated'));
      }
      Deps.afterFlush(function() {
        var element = $('.grid > .error');
        $('html, body').animate({scrollTop: element.offset().top});
      });
    });

    Meteor.call('changeEmail', email);

  }

});


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Ketwaroo;

/**
 * Description of Xml
 *
 * @author Yaasir Ketwaroo
 */
class Xml extends \SimpleDOM
{

    /**
     *
     * @param int $level
     * @return static|boolean
     */
    public function getParentNode($level = 1)
    {
        $test = $this->xpath(trim(str_repeat('/..', $level), '/'));

        return empty($test) ? false : $test[0];
    }

    /**
     *
     * @param string $xpath
     * @param integer $level
     * @param boolean $flatten
     * @return static[];
     */
    public function findParentOfX($xpath, $level = 1, $flatten = false)
    {
        $found = [];
        foreach (($this->rootPart->xpath($xpath)) as $x)
        {
            if (false !== ( $test = $x->getParentNode($level)))
            {
                $found[] = $flatten ? $test->flatten() : $test;
            }
        }

        return $found;
    }

    public function appendNode(Xml $node, $namespace = null)
    {
        /* @var $c Xml */
        $c = $this->addChild($node->getName(), null, $namespace);
        foreach ($node->getAttributes() as $k => $v)
        {
            $c->addAttribute($k, $v, $namespace);
        }

        $c->insertXML($node->innerXML());

        return $this;
    }

    public function setAttribute($name, $value, $namespace = null)
    {
        if (isset($this[$name]))
        {
            $this[$name] = $value;
        }
        else
        {
            $this->addAttribute($name, $value);
        }
        return $this;
    }

    /**
     * Get all attributes of current element as associative array.
     * @return array
     */
    public function getAttributes()
    {
        $tmp = (array) $this->attributes();
        return empty($tmp['@attributes']) ? array() : $tmp['@attributes'];
    }

    /**
     *
     * @param type $paths
     * @return type
     */
    public function matchXPathFirst($paths)
    {

        foreach ((array) $paths as $path)
        {
            $test = $this->xpath($path);

            if (empty($test))
            {
                continue;
            }

            return $test; // return first non empty
        }

        return array();
    }

    public function matchXPathAll($paths)
    {
        $path = '(' . implode(') and (', (array) $paths) . ')';

        return $this->xpath($path);
    }

    /**
     * randomly picks one or more matched items.
     * Warning; will return single instance if num entires = 1 and array of entries if greater.
     *
     * @param string|array $path
     * @param int $numEntries number of entries to pick
     * @return SimplerDOM|array
     */
    public function matchXPathRandom($path, $numEntries = 1)
    {
        $nodes = $this->matchXPathAll($path);

        return array_rand($nodes, $numEntries);
    }

    /**
     * If current node was matched by xpath, this function flattens it and removes
     * references to the parent xml document so further xpath can per performed
     * without matching parent elements
     *
     * @return SimplerDOM
     */
    public function flatten()
    {
        return new static($this->asXML());
    }

    /**
     *
     * @param string $filename
     * @param int $options
     * @param string $ns
     * @param boolean $is_prefix
     * @return Xml
     */
    public static function loadXmlFile($filename, $options = 0, $ns = '', $is_prefix = false)
    {
        return new static(file_get_contents($filename), $options, $ns, $is_prefix);
    }

    /**
     * Add new CDATA child and return new node.
     * @param string $name
     * @param string $value
     * @param string $namespace
     * @return static
     */
    public function addChildCdata($name, $value=null, $namespace=null)
    {
        /* @var $c Xml */
        $c = $this->addChild($name, NULL, $namespace);
        $c->insertCDATA(strval($value));
        return $c;
    }

    /**
     * Converts to sort of an array representation
     * @return array
     */
    public function toArray($includeAttributes = true)
    {
        $out     = [];
        if ($includeAttributes
            && ($attribs = $this->getAttributes())
            && !empty($attribs))
        {

            $out['@attributes'] = $attribs;
        }
        if ($this->count())
        {
            foreach ($this->children() as $c)
            {
                $out[$c->getName()][] = $c->toArray();
            }
        }
        else
        {
            $out[] = strval($this);
        }
        return $out;
    }

}


text:
[![Build Status](https://travis-ci.org/ContainX/go-mesoslog.svg)](https://travis-ci.org/ContainX/go-mesoslog)

## Overview

Go-Mesoslog makes it easy to grab StdOut and StdErr logs from any task.  It allows you to find logs using the name of the task without the UUID portion.  Go-Mesoslog locates the logs via the master and then downloads the desired log from the allocated slave.

## Usage

```
go-mesoslog [global_flags] [action] <action_flags>
Actions
  list                      - List current application id's and task count (instances running)
  print [appId]             - Outputs the log for the given [appId] to StdOut.  Each running instance log will be outputed
  tail [appId]              - Tails the log from the given [appId] to StdOut.  All instances are part of the tail
  file [appId] [targetDir]  - Outputs the log for the given [appId] to a files in the [targetDir] prefixed with the instance TaskID
  help                      - Help about any cmmand

Global Flags
  -m, --master :            - Mesos Master host:port (eg. 192.168.2.1:5050)
```

### Binary Installation

Binaries are available through GitHub releases.  You can download the appropriate binary, package and version from the [Releases](https://github.com/ContainX/go-mesoslog/releases) page

### Build and Install the Binaries from Source

Add Go-Mesoslog and its package dependencies to your go `src` directory

    go get -v github.com/ContainX/go-mesoslog

Once the `get` has completed, you should find your new `go-mesoslog` (or `go-mesoslog.exe`) executable sitting inside the `$GOPATH/bin/`

To update Go-Mesoslog's dependencies, use `go get` with the `-u` option.

    go get -u -v github.com/ContainX/go-mesoslog

## Why Go-Mesoslog

Ideally in your larger clusters you should be log forwarding via Syslog, GELF, FluentD, etc but for smaller deployments where this isn't setup such as DEV or TEST environments this offers a quick view without exposing all of your cluster characteristics to the teams.

I wrote this quickly in one night to solve a few use cases.  Feel free to fork and contribute!

## Looking for Mesos/Marathon, Kubernetes or ECS deployment in one tool?

Checkout [depcon](https://github.com/ContainX/depcon)

## License

This software is licensed under the Apache 2 license, quoted below.

Copyright 2016 ContainX / Jeremy Unruh

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.


text:
function Controller($scope, $state, $window, $stateParams, AuthService, UserService, appSettings){
    "ngInject";
    this._AuthService = AuthService;
    this._UserService = UserService;
    this.sessionExpired = $stateParams.sessionExpired;
    this._$state = $state;
    this._$scope = $scope;
    this.error = null;
    this.userRoles = appSettings.ROLES;
    this.passwordReset = false;

    this.credentials = {
        username: '',
        password : ''
    };
};

Controller.prototype.login = function(){
    var self = this;
    self.passwordReset = false;
    self._AuthService.login(self.credentials).then(function(user){
        if(user.roles.indexOf(self.userRoles.user) != -1){
            self._$state.go("app.courses");
        } else if(user.roles.indexOf(self.userRoles.instructor) != -1) {
            self._$state.go("app.courses");
        } else if (user.roles.indexOf(self.userRoles.admin) != -1) {
            console.log("You're an admin!");
            self._$state.go("app.admin");
        }
    },function(err){
        self.error = "There was a problem logging in. Please try again";
    });
};

Controller.prototype.resetPassword = function(){
    var self = this;
    if(self.credentials.username == ""){
        self.error = "Email required to reset password";
    } else {
        var payload = {
            email : self.credentials.username
        }
        self._UserService.resetPassword(payload)
        .then(function(res){
            self.passwordReset = true;
        }, function(err){
            self.error = "ERROR Resetting Password. Double check email"
        })
    };
}

module.exports = angular.module('app.views.app.login.controller', [
    'app.components.popup_modal'
])
.controller('LoginCtrl', Controller);


text:
module.exports = {
  'Demo test': function (browser) {
    browser
      .url('http://localhost')
      .waitForElementPresent('#weblogin')
      .openNewWindow('window')
      .pause(100)
      .end();
  }
};


text: module.exports.escapeshellarg = require('./escapeshellarg');


text: <!DOCTYPE HTML>


text:
function [x,fval] = benchmark_getmin(data,stringid)
%BENCHMARK_GETMIN Find minimum from benchmark data.

ff = fieldnames(data);

x = [];
fval = Inf;

for iField = 1:numel(ff)
    idx = strfind(ff{iField}, ['_' stringid '_']);
    if isempty(idx); continue; end
    history = data.(ff{iField}).history;
    for iHist = 1:numel(history)
        Output = history{iHist}.Output;
        [fval_tmp,idx] = min(Output.fval);
        if fval_tmp < fval
            x = Output.x(idx,:);
            fval = fval_tmp;
        end
    end
end

fprintf('\n\tx = %s;\n\tfval = %s;\n', mat2str(x), mat2str(fval));

end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>networking on Reflections</title>
    <link>http://blog.shiv.me/tags/networking/</link>
    <description>Recent content in networking on Reflections</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <copyright>Copyright 2016 &copy; Shivanand Velmurugan</copyright>
    <lastBuildDate>Fri, 02 Jan 2009 00:00:00 +0000</lastBuildDate><atom:link href="http://blog.shiv.me/tags/networking/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Are you using Open-DNS?</title>
      <link>http://blog.shiv.me/2009/01/02/are-you-using-open-dns/</link>
      <pubDate>Fri, 02 Jan 2009 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2009/01/02/are-you-using-open-dns/</guid>
      <description>You should be using Open-DNS, if you answer yes to one of the following:
 Are you frustrated with crazy-long wait times before even the website url shows up? Is your ISP is a cheapo-*#$% using a crappy machine for DNS, and you wait enough to count the seconds between pressing enter and the little thingy on the browser status bar says &ldquo;done&rdquo;? Are you subject to phishing attacks? Do you want peace of mind?</description>
    </item>

    <item>
      <title>SNMP tutorials</title>
      <link>http://blog.shiv.me/2005/10/06/snmp-tutorials/</link>
      <pubDate>Thu, 06 Oct 2005 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2005/10/06/snmp-tutorials/</guid>
      <description>SNMP being the bread and butter for me, I decided to dig up some tutorials and links regarding the same.
For the uninitiated, SNMP is short for Simple Network Management Protocol, and is a protocol used to manage network devices such as routers, switches etc.
 Simple Web - Introduction to SNMP, and good set of tutorials Simple Times - technical articles and featured columns Cisco - SNMP Overview Cisco - whitepaper SnmpLink - Links to almost every possible SNMP resource  </description>
    </item>

  </channel>
</rss>


text:
<?php

/**
 * This is the model class for table "tbl_basic_relations_pivot".
 *
 * The followings are the available columns in table 'tbl_basic_relations_pivot':
 * @property integer $id
 * @property integer $column_main_id
 * @property string $column_many_many_id
 */
class BasicRelationsPivot extends RelationsActiveRecord {
	/**
	 * Returns the static model of the specified AR class.
	 * @return BasicRelationsPivot the static model class
	 */
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'tbl_basic_relations_pivot';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		return array(
			array ('column_main_id', 'numerical', 'integerOnly' => true),
			array ('column_many_many_id', 'length', 'max' => 255),
			array ('id, column_main_id, column_many_many_id', 'safe', 'on' => 'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		return array(
			'relation_belongs_to_main' => array (self::BELONGS_TO, 'BasicRelationsMain', 'column_main_id'),
			'relation_belongs_to_many_many' => array (self::BELONGS_TO, 'BasicRelationsManyMany', 'column_many_many_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id' => 'ID',
			'column_main_id' => 'Column Main ID',
			'column_many_many_id' => 'Column Many Many ID',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search() {
		$criteria=new CDbCriteria;
		$criteria->compare('id',$this->id);
		$criteria->compare('column_main_id',$this->column_main_id);
		$criteria->compare('column_many_many_id',$this->column_many_many_id,true);
		return new CActiveDataProvider('BasicRelationsPivot', array(
			'criteria'=>$criteria,
		));
	}
}


text:
import util
import sys
import requests
import json
import base64
import cStringIO

content = {
      "content": {
      },
      "meta": {
          "audio": {
              "type": False,
              "data": False
          }
      }
  }

content_type = 'data:image/%s;base64,'

headers = {
    'Content-Type' : 'application/json'
}

def get_image_type(loc):
    return loc.split('.')[-1]

def post(url, image_loc, output):
    image_type = get_image_type(image_loc)
    with open(image_loc, "rb") as img:
        content['content']['data'] = (content_type % image_type) + util.image_to_b64(img)
    service = '%s/service' % url
    print "POST to %s..." % service
    resp = requests.post(service, data = json.dumps(content), headers = headers).json()
    blob = resp['content']['data'].split(',')[1]
    decoded = base64.b64decode(blob)
    file_like = cStringIO.StringIO(decoded)
    with open(output, 'wb') as out:
        out.write(file_like.read())
    print "Saved result to %s" % output

def main():
    try:
        url = sys.argv[1]
        input_img = sys.argv[2]
        output_img = sys.argv[3]
    except:
        print "Usage: python test.py <api-server-address> <input-image> <output-image>"
        return
    post(url, input_img, output_img)

if __name__ == '__main__':
	main()


text:
#import <Foundation/Foundation.h>

@interface ZXPDF417ResultMetadata : NSObject

@property (nonatomic, assign) int segmentIndex;
@property (nonatomic, copy) NSString *fileId;
@property (nonatomic, assign) BOOL lastSegment;
@property (nonatomic, assign) int segmentCount;
@property (nonatomic, copy) NSString *sender;
@property (nonatomic, copy) NSString *addressee;
@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, assign) long long fileSize;
@property (nonatomic, assign) long long timestamp;
@property (nonatomic, assign) int checksum;
@property (nonatomic, strong) NSArray *optionalData;

@end


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.MachineLearning.Models;
using Azure.ResourceManager.Models;

namespace Azure.ResourceManager.MachineLearning
{
    public partial class MachineLearningComputeData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Identity))
            {
                writer.WritePropertyName("identity");
                var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } };
                JsonSerializer.Serialize(writer, Identity, serializeOptions);
            }
            if (Optional.IsDefined(Sku))
            {
                if (Sku != null)
                {
                    writer.WritePropertyName("sku");
                    writer.WriteObjectValue(Sku);
                }
                else
                {
                    writer.WriteNull("sku");
                }
            }
            if (Optional.IsDefined(Properties))
            {
                writer.WritePropertyName("properties");
                writer.WriteObjectValue(Properties);
            }
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WritePropertyName("location");
            writer.WriteStringValue(Location);
            writer.WriteEndObject();
        }

        internal static MachineLearningComputeData DeserializeMachineLearningComputeData(JsonElement element)
        {
            Optional<ManagedServiceIdentity> identity = default;
            Optional<MachineLearningSku> sku = default;
            Optional<Compute> properties = default;
            Optional<IDictionary<string, string>> tags = default;
            AzureLocation location = default;
            ResourceIdentifier id = default;
            string name = default;
            ResourceType type = default;
            Optional<SystemData> systemData = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("identity"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    var serializeOptions = new JsonSerializerOptions { Converters = { new ManagedServiceIdentityTypeV3Converter() } };
                    identity = JsonSerializer.Deserialize<ManagedServiceIdentity>(property.Value.ToString(), serializeOptions);
                    continue;
                }
                if (property.NameEquals("sku"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        sku = null;
                        continue;
                    }
                    sku = MachineLearningSku.DeserializeMachineLearningSku(property.Value);
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    properties = Compute.DeserializeCompute(property.Value);
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = new AzureLocation(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
                    continue;
                }
            }
            return new MachineLearningComputeData(id, name, type, systemData.Value, Optional.ToDictionary(tags), location, identity, sku.Value, properties.Value);
        }
    }
}


text:
layout: post
title: 4-Hours workweek
authors: Timothy Ferriss

---

- **Book Title**: The 4-hour workweek- Escape 9-5, Live Anywhere and Join the New Rich
- **Author**: Timothy Ferriss
- **Year written/published**: 2007
- **Contents page**:

1. First and Foremost
2. Step 1: D is for Definition
3. Step 2: E is for Elimination
4. Step 3: A is for Automation
5. Step 4: L is for Liberation

**Some quotations:**

- Whenever you find yourself on the side on the majority, it is time to pause and reflect ~ Mark Twain
- Anyone who lives within their means suffers form a lack of imagination ~ Oscar Wilde
- An expert is a person who has made all the mistakes that can be made in a very narrow filed ~ Niels Bohr
- Reality is merely an Illusion, albeit a very persistent one ~ Albert Einstein
- Everything popular is wrong ~ Oscar Wilde, The Importance of being Earnest
- Many a false step was made by standing still ~ Fortune Cookie
- Named must your fear be before banish it you can ~Yoda, Star Wars
- The reasonable man adapts himself to the world; the unreasonable man persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man. ~ George Bernard Shaw
- Perfection is not when there is no more to add, but no more to take away ~ Antione de Saint-Exupery
- There are many things of which a wise man wish to be ignorant. ~ Ralph Waldo Emerson
- A man is rich in proportion to the number of things he can afford to let alone ~ Henry David Thoreau

- **Some extracts**:

Top 13 New Rich mistakes...

1. Losing sight of dreams and falling into work for work's sake
2. micromanaging and emailing to fill time
3. handling problems your outsourcers or co-workers can handle
4. Helping outsourcers or co-workers with the same problem more than once, or with non-crisis problems.
5. Chasing customers, particularly unqualified or international prospects, when you have sufficient cash flow to finance your non-financial pursuits
6. answering email that willnot result in a sale or that cna be answered by a FAW/auto-responder
7. working where you live, sleep, or should relax
8. Not performing a thorough 80/20 analysis every 2 - 4 weeks for your business and personal life
9. Striving for endless perfection rather than great or simply good enogh, whether in your personal or professional life
10. blowing a minutiae and small problems out of proportion as an excuse to work
11. Making non-time-sensitive issues urgent in order to justify work
12. Viewing one product, job, or project as the end-all and be-all of your existence.
13. Ignoring the social rewards of life


text:
import csv
import os
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_curve, auc
from sklearn.preprocessing import label_binarize
from sklearn.externals import joblib
import matplotlib.pyplot as plt

def plotroc(traindata, trainlabel, testdata, testlabel, labels, rocfilename, cmfilename):
    print('# plot ROC curve')
    print('## train data shape: %s' % (traindata.shape,))
    #clf = LogisticRegression(C=0.0005)
    clf = RandomForestClassifier(10, oob_score=True, n_jobs=-1)
    clf.fit(traindata, trainlabel)
    print('## test data shape: %s' % (testdata.shape,))
    predlabel = clf.predict(testdata)
    predprob = clf.predict_proba(testdata)
    cm = confusion_matrix(testlabel, predlabel)
    print(cm)
    plotconfusionmatrix(cm, labels, cmfilename)
    print(classification_report(testlabel, predlabel, target_names=labels))

    testlabel = label_binarize(testlabel, classes=range(1,13))
    predlabel = label_binarize(predlabel, classes=range(1,13))
    nclasses = predlabel.shape[1]
    fpr = dict()
    tpr = dict()
    rocauc = dict()
    for i in xrange(nclasses):
        fpr[i], tpr[i], _ = roc_curve(testlabel[:,i], predprob[:,i])
        rocauc[i] = auc(fpr[i], tpr[i])

    fpr["micro"], tpr["micro"], _ = roc_curve(testlabel.ravel(), predprob.ravel())
    rocauc["micro"] = auc(fpr["micro"], tpr["micro"])

    plt.figure()
    plt.plot(fpr["micro"], tpr["micro"],
             label='micro-average ROC curve (area = {0:0.2f})'''.format(rocauc["micro"]))
    for i in range(nclasses):
        plt.plot(fpr[i], tpr[i], label='{0} (area = {1:0.2f})'
                 ''.format(labels[i], rocauc[i]))

        plt.plot([0, 1], [0, 1], 'k--')
        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        plt.xlabel('False Positive Rate')
        plt.ylabel('True Positive Rate')
        plt.title('Receiver operating characteristic')
        plt.legend(loc="lower right")
        plt.show()

    plt.savefig(rocfilename)

def plotconfusionmatrix(cm, labels, cmfilename):
    print('# plot confusion matrix')
    norm = []
    for i in cm:
        a = 0
        tmp = []
        a = sum(i, 0)
        for j in i:
            tmp.append(float(j)/float(a))
        norm.append(tmp)

    fig = plt.figure(figsize=(6,4))
    plt.clf()
    ax = fig.add_subplot(111)
    ax.set_aspect(1)
    res = ax.imshow(np.array(norm), cmap=plt.cm.jet, interpolation='nearest')

    width = len(cm)
    height = len(cm[0])

    for x in xrange(width):
        for y in xrange(height):
            ax.annotate(str(cm[x][y]), xy=(y, x),
                        horizontalalignment='center',
                        verticalalignment='center')

    plt.title('cat classification')
    plt.colorbar(res)

    #plt.xticks(range(width), labels[:width], fontsize=10)
    plt.yticks(range(height), labels[:height], fontsize=10)
    plt.tick_params(labelbottom="off")
    plt.show()

    plt.savefig(cmfilename)
    print('save ok: %s' % (cmfilename,))

def report(clf, testdata, testlabel, traindata_all, trainlabel_all, labels, cmfilename):
    print('# ----- Classification report -----')
    if hasattr(clf, 'best_estimator_'):
        print('## --- best estimator:')
        print(clf.best_estimator_)
    else:
        print('## --- estimator:')
        print(clf)

    print('## test data shape: %s' % (testdata.shape,))
    predlabel = clf.predict(testdata)

    print('## accuracy: %s' % (accuracy_score(testlabel, predlabel),))  ## == clf.score
    cm = confusion_matrix(testlabel, predlabel)
    print('## confusion matrix')
    print(cm)
    plotconfusionmatrix(cm, labels, cmfilename)
    cr = classification_report(testlabel, predlabel, target_names=labels)
    print(cr)

def getlabels(labelfilename):
    labels = []
    reader = csv.reader(file(labelfilename, 'r'), delimiter='\t', lineterminator='\n')
    for line in reader:
        labels.append(line[0])
    return labels

if __name__ == '__main__':
    os.chdir(os.path.dirname(__file__))

    LABELNAME_FILE = '../data/cat_label.tsv'
    TRAINDATA_OBJFILE = '../data/train_data.pkl'
    TRAINLABEL_OBJFILE = '../data/train_labels.pkl'
    MODEL_FILE = '../data/models/cat_model_lr.pkl'
    CM_FILE = './tmp/cm.png'
    ROC_FILE = './tmp/roc'

    labels = getlabels(LABELNAME_FILE)
    print('# ----- Target labels -----')
    print(labels)

    clf = joblib.load(MODEL_FILE)
    traindata_all = joblib.load(TRAINDATA_OBJFILE)
    trainlabel_all = joblib.load(TRAINLABEL_OBJFILE)
    traindata, testdata, trainlabel, testlabel = train_test_split(traindata_all, trainlabel_all)

    #report(clf, testdata, testlabel, traindata_all, trainlabel_all, labels, CM_FILE)
    plotroc(traindata, trainlabel, testdata, testlabel, labels, ROC_FILE, CM_FILE)


text:
namespace _06.Batteries
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Batteries
    {
        public static void Main()
        {
            //var text1 = "3000 3600 800,56 6000";
            //var text2 = "350 400 200 600";
            //var text3 = 8;

            var capacity = Console.ReadLine()
                .Split(new char[] { ' ' },
                StringSplitOptions.RemoveEmptyEntries)
                .Select(double.Parse)
                .ToArray();

            var usagePerHour = Console.ReadLine()
                .Split(new char[] { ' ' },
                StringSplitOptions.RemoveEmptyEntries)
                .Select(double.Parse)
                .ToArray();

            var hours = int.Parse(Console.ReadLine());

            var batteryChargePerHours = BatteryChargePerHours(capacity, usagePerHour, hours);

            var chargeLeft = BatteryChargeLeft(capacity, usagePerHour, batteryChargePerHours);

            ResultOutput(capacity, hours, chargeLeft);

        }

        static List<double> BatteryChargePerHours(double[] capacity, double[] usagePerHour, int hours)
        {
            var batteryChargePerHours = new List<double>();

            for (int mAh = 0; mAh < capacity.Length; mAh++)
            {
                var usage = usagePerHour[mAh] * (double)hours;

                batteryChargePerHours.Insert(mAh, usage);
            }

            return batteryChargePerHours;
        }

        static void ResultOutput(double[] capacity, int hours, List<double> chargeLeft)
        {
            for (int i = 0; i < chargeLeft.Count; i++)
            {
                var battery = chargeLeft[i];

                if (battery > hours)
                {
                    var percentage = (battery * 100) / capacity[i];
                    Console.WriteLine($"Battery {i+1}: {battery:f2} mAh ({percentage:f2})%");
                }
                else
                {
                    Console.WriteLine($"Battery {i+1}: dead (lasted {battery} hours)");
                }
            }
        }

        static List<double> BatteryChargeLeft(double[] capacity, double[] usagePerHour, List<double> batteryCharge)
        {
            var chargeLeft = new List<double>();

            for (int i = 0; i < capacity.Length; i++)
            {
                if (capacity[i] >= batteryCharge[i])
                {
                    var resultCapacity = capacity[i] - batteryCharge[i];
                    chargeLeft.Insert(i, resultCapacity);
                }
                else if (capacity[i] < batteryCharge[i])
                {
                    var deadHours = Math.Ceiling(capacity[i] / usagePerHour[i]);
                    chargeLeft.Insert(i, deadHours);
                }
            }

            return chargeLeft;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="disableWrapperSourceDistributionNotification" value="true" />
        <option name="distributionType" value="DEFAULT_WRAPPED" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="modules">
          <set>
            <option value="$PROJECT_DIR$" />
            <option value="$PROJECT_DIR$/AverageNoMapReduce" />
            <option value="$PROJECT_DIR$/FileWithNumbersGenerator" />
            <option value="$PROJECT_DIR$/HazelcastManagementCenter" />
            <option value="$PROJECT_DIR$/HazelcastMapAndQueueClient" />
            <option value="$PROJECT_DIR$/HazelcastMapAndQueueCluster" />
            <option value="$PROJECT_DIR$/HazelcastMapReducerCluster" />
            <option value="$PROJECT_DIR$/HazelcastMapReducerCommon" />
            <option value="$PROJECT_DIR$/HazelcastMapReducerJob" />
          </set>
        </option>
      </GradleProjectSettings>
    </option>
  </component>
</project>


text:
package com.orientechnologies.orient.etl.source;

import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.command.OBasicCommandContext;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.etl.OETLProcessor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.zip.GZIPInputStream;

public class OFileSource extends OAbstractSource {
  protected String            fileName;
  protected Object            path;
  protected boolean           lockFile    = false;
  protected long              byteParsed  = 0;
  protected long              byteToParse = -1;
  protected long              skipFirst   = 0;
  protected long              skipLast    = 0;

  protected RandomAccessFile  raf         = null;
  protected FileChannel       channel     = null;
  protected InputStreamReader fileReader  = null;
  protected FileInputStream   fis         = null;
  protected FileLock          lock        = null;

  @Override
  public String getUnit() {
    return "bytes";
  }

  @Override
  public ODocument getConfiguration() {
    return null;
  }

  @Override
  public void configure(OETLProcessor iProcessor, ODocument iConfiguration, OBasicCommandContext iContext) {
    super.configure(iProcessor, iConfiguration, iContext);

    path = resolve(iConfiguration.field("path"));
    if (iConfiguration.containsField("lock"))
      lockFile = (Boolean) iConfiguration.field("lock");

    if (iConfiguration.containsField("skipFirst"))
      skipFirst = Long.parseLong((String) iConfiguration.field("skipFirst"));

    if (iConfiguration.containsField("skipLast"))
      skipLast = Long.parseLong((String) iConfiguration.field("skipLast"));

    if (path instanceof String)
      path = new File((String) path);

    if (path instanceof File) {
      final File file = (File) path;
      if (!file.exists())
        throw new OSourceException("[File source] path '" + path + "' not exists");
      fileName = file.getName();
    }
  }

  @Override
  public void end() {
    if (lock != null)
      try {
        lock.release();
      } catch (IOException e) {
      }

    if (fis != null)
      try {
        fis.close();
      } catch (IOException e) {
      }

    if (fileReader != null)
      try {
        fileReader.close();
      } catch (IOException e) {
      }

    if (channel != null)
      try {
        channel.close();
      } catch (IOException e) {
      }

    if (raf != null)
      try {
        raf.close();
      } catch (IOException e) {
      }
  }

  @Override
  public String getName() {
    return "file";
  }

  @Override
  public void begin() {
    if (path instanceof File) {
      final File file = (File) path;

      try {
        final String fileMode = lockFile ? "rw" : "r";
        raf = new RandomAccessFile(file, fileMode);
        channel = raf.getChannel();
        fis = new FileInputStream(file);
        if (fileName.endsWith(".gz"))
          fileReader = new InputStreamReader(new GZIPInputStream(fis));
        else {
          fileReader = new FileReader(file);
          byteToParse = file.length();
        }

      } catch (Exception e) {
        end();
      }
    } else if (path instanceof InputStream) {
      fileName = null;
      byteToParse = -1;
      fileReader = new InputStreamReader((InputStream) path);
    } else if (path instanceof InputStreamReader) {
      fileName = null;
      byteToParse = -1;
      fileReader = (InputStreamReader) path;
    } else
      throw new OSourceException("[File source] Unknown input '" + path + "' of class '" + path.getClass() + "'");

    byteParsed = 0;

    if (lockFile)
      try {
        lock = channel.lock();
      } catch (IOException e) {
        OLogManager.instance().error(this, "Error on locking file: %s", e, fileName);
      }

    log(OETLProcessor.LOG_LEVELS.DEBUG, "Reading from file " + path);
  }

  public boolean isClosed() {
    return fileReader != null;
  }

  public Reader getFileReader() {
    return fileReader;
  }

  @Override
  public Reader read() {
    return fileReader;
  }
}