text:
// Userscript functions.
(function(window, document) {

// Map symbols to key codes.
// Edit this to change keys. Beware your changes won't persist if the
// userscript updates.
var keyMap = {
  'NUM_0': "96",
  'NUM_1': "97",
  'NUM_2': "98",
  'NUM_3': "99",
  'NUM_4': "100",
  'NUM_5': "101",
  'NUM_6': "102",
  'NUM_7': "103",
  'NUM_8': "104",
  'NUM_9': "105",
  '/': "111",
  '*': "106",
  '-': "109",
  '+': "107",
  '.': "110"
};

// Reverse keyMap.
var keyCodes = Object.keys(keyMap).reduce(function (keyCodes, symbol) {
  var val = keyMap[symbol];
  keyCodes[val] = symbol;
  return keyCodes;
}, {});

// Run provided function when body is present.
function runOnBody(fn) {
  if (document.body) {
      fn();
  } else {
    setTimeout(function() {
      runOnBody(fn);
    }, 150);
  }
}

function runOnTagpro(fn) {
  if (typeof tagpro !== 'undefined') {
    fn();
  } else {
    setTimeout(function() {
      runOnTagpro(fn);
    }, 0);
  }
}

function runOnChat(fn) {
  if (typeof tagpro !== "undefined" && tagpro.playerId) {
    // Additional delay is for compatibility with chat enhancer.
    setTimeout(fn, 1000);
  } else {
    setTimeout(function() {
        runOnChat(fn);
    }, 0);
  }
}

runOnBody(function() {
  // This dummy input will handle macro keypresses
  var btn = document.createElement("input");
  btn.style.opacity = 0;
  btn.style.position = "absolute";
  btn.style.top = "-100px";
  btn.style.left = "-100px";
  btn.id = "macro-handler";
  document.body.appendChild(btn);

  btn.focus();
  btn.addEventListener('keydown', keydownHandler, false);
  document.addEventListener('keydown', documentKeydown, false);
  runOnChat(function() {
    showInfo("TagPro Neomacro Plus Loaded!");
  });
});

// Checks for macro inputs associated with TagPro NeoMacro and
// Watball's macro generator.
var conflictCheck = setInterval(function() {
  var input = document.getElementById("macrohandlerbutton");
  if (input !== null) {
    // Clean up changes.
    document.removeEventListener('keydown', documentKeydown, false);
    var thisInput = document.getElementById("macro-handler");
    thisInput.removeEventListener('keydown', keydownHandler, false);
    thisInput.remove();
    // Add listener to existing input, assumes focus is handled in
    // other script.
    input.addEventListener('keydown', keydownHandler, false);
    clearInterval(conflictCheck);
  }
}, 200);

// Given a string of keys pressed, parse it into an object to be
// turned into a message, or throw an exception if invalid.
function parseMacro(str) {
  if (str) {
    return Macro.parse(str);
  }
}

function validFirst(keyCode) {
  return Macro.firsts.indexOf(keyCodes[keyCode]) !== -1;
}

var allowedKeys = Object.keys(keyCodes);

function validKey(keyCode) {
  return allowedKeys.indexOf(keyCode.toString()) !== -1;
}

function controlsDisabled() {
  return typeof tagpro !== "undefined" && tagpro.disableControls;
}

// Prevent macro keys from impacting tagpro play.
runOnTagpro(function() {
  tagpro.ready(function() {
    function keyNotInUse(k) {
      return !validKey(k);
    }
    for (var key in tagpro.keys) {
      tagpro.keys[key] = tagpro.keys[key].filter(keyNotInUse);
    }
  });
});

function documentKeydown(event) {
  if (!controlsDisabled()) {
    // The handler button should be always focused
    document.getElementById("macro-handler").focus();

    // Disables
    // * backspace
    // * ctrl - to prevent leaving page accidentally
    // * numpad 4 - because it is tied to right navigation.
    if ((event.keyCode==8 || event.ctrlKey || event.keyCode == 100) && !controlsDisabled()) {
      event.preventDefault();
      event.stopPropagation();
      return false;
    }
  }
}

// Main macro keypresses handler
// Last time key was pressed.
var lastKey = 0;
// Time to wait after last keypress before trying macro, maximum time before
// macro will go after pressing keys.
var keypressLimit = 3e3;

// The . key on the numpad.
var resetKey = keyMap["."];

// Keys pressed.
var keys = [];
var clearKeys;
function keydownHandler(event) {
  if (controlsDisabled()) return;
  // Reset key in case user presses incorrect key.
  if (event.keyCode == resetKey) {
    keys = [];
    showInfo("Key combination reset! You can restart your macro now.");
    if (clearKeys) {
      clearTimeout(clearKeys);
    }
    return;
  }

  // If no sequence has started and this doesn't match a valid start
  // token, then disregard.
  if (keys.length === 0 && !validFirst(event.keyCode)) return;

  // Ignore irrelevant keys and don't allow them to interfere with the
  // macro key sequence.
  if (!validKey(event.keyCode)) return;
  // Remove existing macro parsing to be called if it exists.
  if (clearKeys) {
    clearTimeout(clearKeys);
  }

  event.preventDefault();
  event.stopPropagation();

  keys.push(keyCodes[event.keyCode]);

  // Parse already-pressed keys if no other keys come in.
  try {
    var result = parseMacro(keys.join(" "));
    var message = {
      text: parseMessage(result),
      global: false
    };
    chat(message);
    keys = [];
  } catch(e) {
    //console.debug("Parse error: " + e);
    // Not ready, clear keys after time period.
    clearKeys = setTimeout(function() {
      showInfo("Try your macro again.");
      keys = [];
    }, keypressLimit);
  }
}

/**
 * Send a message.
 * @param {object} chatMessage - The message information. It has
 *   properties `text` and `global` corresponding to the message
 *   to send and whether it should go to everyone (as opposed to
 *   just the user's own team.)
 * @param {boolean} group - Whether this message should be sent
 *   to the group.
 */
var lastMessage = 0;
var messageLimit = 300;
function chat(chatMessage, group) {
  if (typeof group == "undefined") group = false;
  var now = Date.now();
  var timeDiff = now - lastMessage;
  if (timeDiff > messageLimit) {
    if (!group) {
      tagpro.socket.emit("chat", {
        message: chatMessage.text,
        toAll: chatMessage.global
      });
    } else {
      tagpro.group.socket.emit("chat", chatMessage);
    }
    lastMessage = Date.now();
  } else if (timeDiff >= 0) {
    setTimeout(function() {
      chat(chatMessage, group);
    }, messageLimit - timeDiff);
  }
}

// Show feedback to user.
function showInfo(message) {
  if (typeof io !== "undefined" && io.__loopback &&
    typeof tagpro !== "undefined") {
    tagpro.socket.emit("local:chat", {
      to: "all",
      from: null,
      message: "TNP: " + message
    });
  }
}

var Symbols = {};
Symbols.directions = {
  "sw": "\u21d9",
  "s": "\u21d3",
  "se": "\u21d8",
  "w": "\u21d0",
  "c": "\u2a00",
  "e": "\u21d2",
  "nw": "\u21d6",
  "n": "\u21d1",
  "ne": "\u21d7"
};

// Text expansions for macro values.
var Shorthand = {
  // Directions.
  "sw": "bottom left",
  "s": "bottom",
  "se": "bottom right",
  "w": "left",
  "c": "middle",
  "e": "right",
  "nw": "top left",
  "n": "top",
  "ne": "top right",
  // Powerups.
  "jj": "juke juice",
  "tp": "tagpro",
  "rb": "rolling bomb",
  "ts": "top speed",
  // Pronouns.
  "self": "I",
  "enemy": "enemy",
  "teammate": "teammate"
};

// Operation that can be applied in templates.
var Operations = {
  expand: function(val) {
    return Shorthand[val];
  },
  dir: function(val) {
    return Symbols.directions[val];
  },
  capitalize: function(val) {
    return val.slice(0, 1).toUpperCase() + val.slice(1);
  },
  dbl: function(val) {
    return val + val;
  }
};

// Sentences that the parsed key strokes are placed into.
var Templates = {
  "fc_position": "{{loc|dir|dbl}} Enemy FC is {{loc|expand}} {{loc|dir|dbl}}",
  "pup_grabbed": "{{who|expand|capitalize}} got {{what|expand}} on {{where|expand}} @ :{{when}}",
  "pup_time": "{{where|expand}} powerup @ :{{when}}",
  "fc_position_lane": "Enemy FC is {{lane}}.",
  "pup_respawn": "{{where|expand|capitalize}} powerup is respawning soon.",
  "base_status": "Number of enemies in base: {{num}}"
};

// Given text from within a replacement, parse it.
function parseReplacement(replacement, info) {
  var vals = replacement.split("|");
  var out = info[vals[0]];
  var fns = vals.slice(1);
  fns.forEach(function(fn) {
    if (Operations.hasOwnProperty(fn)) {
      out = Operations[fn].call(null, out);
    }
  });
  return out;
}

// TODO: Transition to jison-backed parser?
// Parse message information into sentence for output.
function parseMessage(info) {
  var template = Templates[info.type];
  var literal_re = /(?:(.*?)(\{\{))|(?:.*)/g;
  var replace_re = /(.*?)?\}\}/g;
  var tok = literal_re.exec(template);
  var tok_type = "literal";
  var tok_stream = [];
  var out = "";
  while (tok !== null) {
    if (tok_type == "literal") {
      // Start of replacement found.
      if (tok[2]) {
        out += tok[1];
        replace_re.lastIndex = literal_re.lastIndex;
        tok = replace_re.exec(template);
        tok_type = "replacement";
      } else {
        // No replacements found.
        // Append text if matched.
        out += tok[0];
        break;
      }
    } else {
      // Replacement.
      if (tok.length == 2) {
        // Replacement text found.
        out += parseReplacement(tok[1], info);
        literal_re.lastIndex = replace_re.lastIndex;
        tok = literal_re.exec(template);
        tok_type = "literal";
      }
    }
  }
  return out;
}

})(window, document);


text:
describe("TodoCtrl", function() {
	var scope;

	beforeEach(function() {
		this.addMatchers({
			toEqualData: function(expected) {
				return angular.equals(this.actual, expected);
			}
		});
	});

	beforeEach(module("app"));

	beforeEach(inject(function($controller, $rootScope) {
		scope = $rootScope.$new();
		$controller("TodoCtrl as vm", { $scope: scope });
	}));

	it("should create todos model with zero item", function() {
		expect(scope.vm.todos.length).toBe(0);
	});

	describe("addNewTodo()", function() {
		it("should add newTodo to todo list", function() {
			scope.vm.todos = [];
			scope.vm.newTodo = "new item";

			scope.vm.addNewTodo();

			var item = { title: "new item" , done: false };
			expect(scope.vm.todos).toEqualData([item]);
		});
	});

	describe("clearDoneItems()", function() {
		it("should delete items marked as done", function() {
			scope.vm.todos = [{ title: "a", done: true}, { title: "b", done: false}, { title: "c", done: true}];

			scope.vm.clearDoneItems();

			expect(scope.vm.todos).toEqualData([{ title: "b", done: false}]);
		});
	});
});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

 <script src="assets/js/model/shape.js"></script>
 <script src="assets/js/model/circle.js"></script>
 <script src="assets/js/app.js"></script>

</body>
</html>


text:
try {
    var handler = require("readline").createInterface({
        input : process.stdin,
        output: process.stdout
    });
} catch(e) {
    // If ReadLine fails or is not available use process (will fail to do anything on Windows)
    var handler = process;
}

module.exports = function interrupt(callback, context) {
    // Possibly optimize in the future by iterating.
    var parameters = Array.prototype.slice(arguments, 2);

    handler.on("SIGINT", function() {
        callback.apply(context, parameters);

        process.nextTick(process.exit.bind(process));
    });
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 ~ Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ 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.
-->

<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/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.wso2.carbon</groupId>
        <artifactId>as-runtimes-feature</artifactId>
        <version>4.3.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.as.runtimes.j2ee.feature</artifactId>
    <packaging>pom</packaging>
    <name>WSO2 Carbon - J2EE Runtime Environment</name>
    <version>4.3.0-SNAPSHOT</version>
    <url>http://wso2.org</url>
    <description>This feature contains the J2EE runtime environment for running J2EE webapps</description>

    <dependencies>
        <!-- Apache MyFaces dependancies-->
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-impl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-api</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
        <!-- end of My-faces dependancies-->

        <!-- Apache OpenJPA dependancies-->
        <dependency>
            <groupId>org.apache.openjpa</groupId>
            <artifactId>openjpa</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.serp</groupId>
            <artifactId>serp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jms_1.1_spec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jpa_2.0_spec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-jta_1.1_spec</artifactId>
        </dependency>
        <!-- end of OpenJPA dependancies-->

        <!-- common dependancies -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
        </dependency>
        <!-- end of common dependancies-->
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>${project.build.directory}/runtime/</directory>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/runtime/j2ee</outputDirectory>

                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.wso2.maven</groupId>
                <artifactId>carbon-p2-plugin</artifactId>
                <version>${carbon.p2.plugin.version}</version>
                <executions>
                    <execution>
                        <id>p2-feature-generation</id>
                        <phase>package</phase>
                        <goals>
                            <goal>p2-feature-gen</goal>
                        </goals>
                        <configuration>
                            <id>org.wso2.carbon.as.runtimes.j2ee</id>
                            <propertiesFile>../../../features/etc/feature.properties</propertiesFile>
                            <importFeatures>
                                <importFeatureDef>org.wso2.carbon.webapp.mgt:${project.version}
                                </importFeatureDef>
                            </importFeatures>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</project>


text:
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    $ vtkInsideClosedSurface.h $
  Author:    Marie-Gabrielle Vallet
       MGV Research
  Date:      Jan 30, 2008
  Version:   0.1

=========================================================================*/
// .NAME vtkInsideClosedSurface - sample data values at specified point
// locations .SECTION Description vtkInsideClosedSurface is a filter that
// computes a point scalar field at specified point positions. The filter
// has two inputs: the Input and Source. The Source is a triangular mesh and
// should be a closed surface. The Input geometric structure is passed
// through the filter. The point scalar is computed at the Input point
// positions by finding whether the point is inside the volume bounded by
// the source data.
//
// The filter adds or updates two data to the Input structure:
//  - a set of lines representing the boundary edges (ideally must be empty)
//  - an attribute on the points ( 1 iff inside, 0 iff outside )
//

#ifndef __vtkInsideClosedSurface_h
#define __vtkInsideClosedSurface_h

#include "vtkDataSetAlgorithm.h"

class VTK_EXPORT vtkInsideClosedSurface : public vtkDataSetAlgorithm
{
public:

	static vtkInsideClosedSurface *New();
   vtkTypeRevisionMacro(vtkInsideClosedSurface,vtkDataSetAlgorithm);
   void PrintSelf(ostream& os, vtkIndent indent);

//BTX
	enum vtkPointSetDefinition {VERTEX, CELLCENTER};
//ETX
   //Description
   //Set/Get the point set location
   //void SetPointSetDefinition( vtkPointSetDefinition where );
   //   vtkGetMacro(distInfluence, double);

   // Description:
   // Get a pointer to the source object.
   vtkPolyData *GetSource();

   // Description:
   // Specify the point locations used to probe input. Any geometry
   // can be used. New style. Equivalent to SetInputConnection(1, algOutput).
   void SetSourceConnection(vtkAlgorithmOutput* algOutput);

protected:
   vtkInsideClosedSurface();
   ~vtkInsideClosedSurface();
   virtual int FillInputPortInformation(int port, vtkInformation* info);
   virtual int RequestData(vtkInformation *,
                           vtkInformationVector **,
                           vtkInformationVector *);

   // data membre
   vtkPointSetDefinition pointSet;

private:

   // Checking data
   int IsClosed();                // topological closeness
   void boundaryEdges( vtkPolyData* edges );  // to visualise the gaps (geometric closeness)

   // Count source intersections with a line
   // return the number of intersections between the line AB and the source.
   // return -1 in undetermined cases
   int nbIntersections( double *ptA, double *ptB, double epsilon );

   // Use brut force to check if a point is inside or not
   int isInside( double *pt, double epsilon );

   // Loop on points from input and add a scalar field
   void ConstructOutput( vtkDataSet *input, vtkDataSet *output );
   vtkPointSetDefinition insidePoints( vtkDataSet *input, vtkDataArray *infield );

   vtkInsideClosedSurface(const vtkInsideClosedSurface&);  // Not implemented.
   void operator=(const vtkInsideClosedSurface&);  // Not implemented.
	 vtkPolyData *source;
};

#endif


text:
<?php

namespace Magento\DesignEditor\Controller\Adminhtml\System\Design\Editor\Tools;

use Magento\Framework\Model\Exception as CoreException;

class UploadStoreLogo extends \Magento\DesignEditor\Controller\Adminhtml\System\Design\Editor\Tools
{
    /**
     * Upload store logo
     *
     * @return void
     * @throws CoreException
     */
    public function execute()
    {
        $storeId = (int)$this->getRequest()->getParam('store_id');
        $themeId = (int)$this->getRequest()->getParam('theme_id');
        try {
            /** @var $theme \Magento\Framework\View\Design\ThemeInterface */
            $theme = $this->_objectManager->create('Magento\Framework\View\Design\ThemeInterface');
            if (!$theme->load($themeId)->getId() || !$theme->isEditable()) {
                throw new CoreException(__('The file can\'t be found or edited.'));
            }

            /** @var $customizationConfig \Magento\Theme\Model\Config\Customization */
            $customizationConfig = $this->_objectManager->get('Magento\Theme\Model\Config\Customization');
            $store = $this->_objectManager->get('Magento\Store\Model\Store')->load($storeId);

            if (!$customizationConfig->isThemeAssignedToStore($theme, $store)) {
                throw new CoreException(__('This theme is not assigned to a store view #%1.', $theme->getId()));
            }
            /** @var $storeLogo \Magento\DesignEditor\Model\Editor\Tools\QuickStyles\LogoUploader */
            $storeLogo = $this->_objectManager->get(
                'Magento\DesignEditor\Model\Editor\Tools\QuickStyles\LogoUploader'
            );
            $storeLogo->setScope('stores')->setScopeId($store->getId())->setPath('design/header/logo_src')->save();

            $this->_reinitSystemConfiguration();

            $response = ['error' => false, 'content' => ['name' => basename($storeLogo->getValue())]];
        } catch (CoreException $e) {
            $response = ['error' => true, 'message' => $e->getMessage()];
            $this->_objectManager->get('Magento\Framework\Logger')->logException($e);
        } catch (\Exception $e) {
            $errorMessage = __(
                'Something went wrong uploading the image.' .
                ' Please check the file format and try again (JPEG, GIF, or PNG).'
            );
            $response = ['error' => true, 'message' => $errorMessage];
            $this->_objectManager->get('Magento\Framework\Logger')->logException($e);
        }
        $this->getResponse()->representJson(
            $this->_objectManager->get('Magento\Core\Helper\Data')->jsonEncode($response)
        );
    }
}


text:
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// Licensed under the MIT License.

using Microsoft.AspNetCore.OData.Query.Container;
using Microsoft.AspNetCore.OData.Query.Wrapper;
using Microsoft.OData.Edm;
using Newtonsoft.Json;
using System;
using System.Diagnostics.CodeAnalysis;

namespace Microsoft.AspNetCore.Datasync.Converters
{
    /// <summary>
    /// Represents a custom <see cref="JsonConverter"/> to serialize <see cref="ISelectExpandWrapper"/> instances to JSON.
    /// </summary>
    /// <remarks>
    /// See: https://github.com/OData/AspNetCoreOData/blob/master/src/Microsoft.AspNetCore.OData.NewtonsoftJson/JSelectExpandWrapperConverter.cs
    /// </remarks>
    internal class JSelectExpandWrapperConverter : JsonConverter
    {
        private readonly Func<IEdmModel, IEdmStructuredType, IPropertyMapper> _mapperProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="SelectExpandWrapperConverter"/> class.
        /// </summary>
        public JSelectExpandWrapperConverter() : this((IEdmModel model, IEdmStructuredType type) => new JsonPropertyNameMapper(model, type))
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SelectExpandWrapperConverter"/> class.
        /// </summary>
        /// <param name="mapperProvider">The mapper provider.</param>
        public JSelectExpandWrapperConverter(Func<IEdmModel, IEdmStructuredType, IPropertyMapper> mapperProvider)
        {
            _mapperProvider = mapperProvider ?? throw new ArgumentNullException(nameof(mapperProvider));
        }

        public override bool CanRead => false;

        /// <summary>
        /// Determines whether this instance can convert the specified <see cref="ISelectExpandWrapper"/> type.
        /// </summary>
        /// <param name="objectType">Type of the object.</param>
        /// <returns>true if this instance can convert the specified object type; otherwise, false.</returns>
        public override bool CanConvert(Type objectType)
        {
            if (objectType is null)
            {
                throw new ArgumentNullException(nameof(objectType));
            }

            return typeof(ISelectExpandWrapper).IsAssignableFrom(objectType);
        }

        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        [SuppressMessage("General", "RCS1079:Throwing of new NotImplementedException.", Justification = "Only valid in write scenario.")]
        [ExcludeFromCodeCoverage]
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException("SelectExpandWrapper is only valid in write scenario.");
        }

        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, ((ISelectExpandWrapper)value).ToDictionary(_mapperProvider));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <artifactId>java-codes</artifactId>
        <groupId>com.github.lihengming</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>socket</artifactId>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/io.netty/netty -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty</artifactId>
            <version>3.5.2.Final</version>
        </dependency>
    </dependencies>
</project>


text:
package org.xnio.nio;

import org.xnio.Xnio;
import org.xnio.XnioProvider;

/**
 * The NIO XNIO provider.
 *
 * @author David M. Lloyd
 */
public final class NioXnioProvider implements XnioProvider {
    private static final Xnio INSTANCE = new NioXnio();

    /** {@inheritDoc} */
    public Xnio getInstance() {
        return INSTANCE;
    }

    /** {@inheritDoc} */
    public String getName() {
        return INSTANCE.getName();
    }
}


text:
Functions for the time counter in the GUI
Reads time from the FPGA and displays it in real time in seconds
=#
function _make_clock()

    s_label=Label("0")
    m_label=Label("0")
    h_label=Label("0")
    sm_label=Label(":")
    mh_label=Label(":")

    frame_time=Frame("Time Elapsed")
    hbox_time=ButtonBox(:h)
    push!(frame_time,hbox_time)

    push!(hbox_time,h_label)
    push!(hbox_time,mh_label)
    push!(hbox_time,m_label)
    push!(hbox_time,sm_label)
    push!(hbox_time,s_label)

    mytime_widgets=mytime(0,h_label,0,m_label,0,s_label)

    (mytime_widgets,frame_time)
end

function update_time(rhd::RHD2000,han::Gui_Handles)

    total_seconds=convert(Int64,div(rhd.time[1,1],rhd.sr))

    this_h=div(total_seconds,3600)

    total_seconds=total_seconds - this_h*3600

    this_m=div(total_seconds,60)

    this_s=total_seconds - this_m*60

    if this_s != han.time.s
        setproperty!(han.time.s_l,:label,string(this_s))
        han.time.s=this_s
    end
    if this_m != han.time.m
        setproperty!(han.time.m_l,:label,string(this_m))
        han.time.m=this_m
    end
    if this_h != han.time.h
        setproperty!(han.time.h_l,:label,string(this_h))
        han.time.h=this_h
    end

    nothing
end


text:
"use strict";
var UniqueChronologicalKeys = require("./UniqueChronologicalKeys");
/** Handler for removing items from a full LocalStore object based on oldest chronological IDs extracted from the store's keys
 * @author TeamworkGuy2
 * @since 2016-3-25
 */
var ClearFullStore = /** @class */ (function () {
    function ClearFullStore(extractChronoId, itemsRemovedCallback, removePercentage) {
        if (removePercentage === void 0) { removePercentage = 0.3; }
        /** [0.0, 1.0] when the local store gets too full, remove this percentage of the entries */
        this.removePercentage = 0.3;
        /** an internal counter of how many times clearOldItems() has been called */
        this.removalAttemptsCount = 0;
        this.extractChronoId = extractChronoId;
        this.itemsRemovedCallback = itemsRemovedCallback;
        this.removePercentage = removePercentage;
    }
    /** Remove old items
     */
    ClearFullStore.prototype.clearOldItems = function (store, logInfo, err, removePercentage, minItemsRemoved, maxItemsRemoved) {
        if (removePercentage === void 0) { removePercentage = this.removePercentage; }
        if (minItemsRemoved === void 0) { minItemsRemoved = 1; }
        var start = 0, end = 0;
        if (logInfo) {
            start = UniqueChronologicalKeys.getMillisecondTime();
        }
        var removedItems = ClearFullStore.removeOldItems(store, this.extractChronoId, removePercentage, minItemsRemoved, maxItemsRemoved);
        this.removalAttemptsCount++;
        if (logInfo) {
            end = UniqueChronologicalKeys.getMillisecondTime();
        }
        if (this.itemsRemovedCallback && removedItems.removedCount > 0) {
            this.itemsRemovedCallback(store, removedItems.items, {
                error: err,
                message: "removed " + removedItems.items.length + " local store entries" + (logInfo ? " in " + Math.round(end - start) + " ms" : "") + ", " +
                    "because local store threw error" + (err ? ": '" + err.message + "': " + JSON.stringify(err.stack) : ""),
            }, removedItems.removedCount);
        }
        return removedItems.items;
    };
    /** Given a LocalStore with integer based keys (not all keys must be integers),
     * remove 'removePercentage' percent of the smallest integer keys
     * @param removePercentage a value in the range [0.0, 1.0] that specifies the percentage of timestamped values to remove
     * @param localStore the local storage object to remove old timestamped items from
     * @param minItemsRemoved (default=1) the minimum number of items to remove
     * @param maxItemsRemoved (default=(localStore keys where key is Integer).length) the maximum number of items to remove,
     * this defaults to the total number of integer based keys in 'localStore'
     * @return the number of items removed from the 'localStore'
     */
    ClearFullStore.removeOldItems = function (localStore, extractChronoId, removePercentage, minItemsRemoved, maxItemsRemoved) {
        if (minItemsRemoved === void 0) { minItemsRemoved = 1; }
        var idsKeys = [];
        // get a list of chronological keys from the local store
        var keys = localStore.getKeys();
        for (var i = 0, size = keys.length; i < size; i++) {
            var val = extractChronoId(keys[i]);
            if (Number.isInteger(val)) {
                idsKeys.push({
                    id: val,
                    key: keys[i]
                });
            }
        }
        // sort ascending
        idsKeys.sort(function (a, b) { return a.id - b.id; });
        var idCount = idsKeys.length;
        maxItemsRemoved = maxItemsRemoved === undefined ? idCount : Math.min(idCount, maxItemsRemoved);
        var removeCount = Math.max(Math.min(Math.round(idCount * removePercentage), maxItemsRemoved), Math.min(minItemsRemoved, idCount));
        var removedItems = [];
        // remove the oldest timestamped entries (always remove between [1, timestamps.length] entries)
        for (var i = 0; i < removeCount; i++) {
            var keyId = idsKeys[i];
            var existingItem = localStore.getItem(keyId.key, true);
            removedItems.push({
                key: idsKeys[i].key,
                keyId: idsKeys[i].id,
                value: existingItem,
            });
            localStore.removeItem(keyId.key);
        }
        return { items: removedItems, idsSorted: idsKeys, removedCount: removeCount };
    };
    ClearFullStore.newInst = function (extractChronoId, itemsRemovedCallback, removePercentage) {
        return new ClearFullStore(extractChronoId, itemsRemovedCallback, removePercentage);
    };
    return ClearFullStore;
}());
module.exports = ClearFullStore;


text:
import { Component } from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {Response} from "@angular/http";
import {SecureComponent} from "../../../services/secure.component";
import {APIService} from "../../../services/api.service";

@Component({
  selector: 'viewexperiment',
  template: require('./view.experiment.component.html'),
  styles: [require('./view.experiment.component.css')],

})

export class ViewExperiment extends SecureComponent {
  private filteredData: any;
  private experiment: any;
  private id:number;
  private numberOfJobs:number = 0;
  private numberOfJobsLoaded = 0;
  private loaded: boolean = false;
  private average: boolean = true;
  private measurementTypeFilter:Array<any> = [];
  private datasetFilter:Array<any> = [];
  private datasets:Array<any> = [];
  private summaryJobs:Array<any>=[];
  private showCompareMenu:boolean = false;
  private showCompare:boolean = false;
  private compareLoaded: boolean = true;
  private compareExperiments:Array<any>=[];
  private compareExperimentAverages:Array<any>=[];
  private compareExperimentsSelected:Array<any>=[];
  private compareData:any= {}

  constructor(router:Router, protected client: APIService, private route: ActivatedRoute){

    super(router, client);
    this.authorities = ["ROLE_ADMIN", "ROLE_USER"];
  }

  ngOnInit():void{
    super.ngOnInit();
    this.route.params.subscribe(params => {
      let id = params['id'];
      this.id = id;
      this.getExperiment();
      this.getCompareExperiments();
    });
    this.measurementTypeFilter.push("CPU");
    this.measurementTypeFilter.push("TIME");
    this.measurementTypeFilter.push("MEM");
  }

  compare(){
    this.compareExperimentAverages = [];
    this.compareData = {};
    this.compareData.datasetCompare = [];
    //console.log(this.summaryJobs);
    this.showCompare = !this.showCompare;
    for(var experimentId of this.compareExperimentsSelected){
      for(var experiment of this.compareExperiments){
        if(experiment.id == experimentId){
          let compareExerimentAverage: any = {};
          compareExerimentAverage.id = experiment.id;
          compareExerimentAverage.data = [];
          this.generateExperimentDataForCompare(experiment, compareExerimentAverage.data);
          this.compareExperimentAverages.push(compareExerimentAverage);
        }
      }
    }
    //console.log(this.compareExperimentAverages);

    let datasetCompare:Array<any>=[];
    for(var averageData of this.summaryJobs){
      this.addSummaryDataToCompareData(averageData, this.experiment.id);
    }

    for(var compareExperimentData of this.compareExperimentAverages){
      for(var averageData of compareExperimentData.data){
        this.addSummaryDataToCompareData(averageData, compareExperimentData.id);
      }
    }
    console.log(this.compareData);
  }

  addSummaryDataToCompareData(avgData:any, experiment_id:number){
    //console.log(avgData);
    let datasetCompare:any = null;
    for(var dc of this.compareData.datasetCompare){
      if(dc.name == avgData.dataset.name){
        datasetCompare = dc;
      }
    }
    if(datasetCompare == null){
      datasetCompare = {};
      datasetCompare.name = avgData.dataset.name;
      datasetCompare.measurementData = [];
      this.compareData.datasetCompare.push(datasetCompare);
    }
    this.addDataToDatasetCompare(avgData, experiment_id, datasetCompare);
  }

  addDataToDatasetCompare(avgData:any, experiment_id:number, datasetCompare:any){
    let measurementData:any = null;
    for(var md of datasetCompare.measurementData){
      if(md.type == avgData.measurementType){
        measurementData = md;
      }
    }

    if(measurementData == null){
      measurementData = {};
      measurementData.type = avgData.measurementType;
      measurementData.data = [];
      measurementData.labels = ["Min", "Max", "Avg"];
      datasetCompare.measurementData.push(measurementData);
    }
    this.addDataToMeasurementData(avgData, experiment_id, measurementData);
  }

  addDataToMeasurementData(avgData:any, experiment_id:any, measurementData:any){
    var data = {data: [avgData.min, avgData.max, avgData.average], label:experiment_id};
    measurementData.data.push(data);
  }

  getCompareExperiments(){
    this.client.getCompareExperimentsWithGET(this.id).subscribe((res:Response)=>{
      this.compareExperiments = JSON.parse(res.text())["experiments"];
      //console.log(this.compareExperiments);
    },(err)=>{
      this.hasError = true;
      this.errorMessage = "Could not get compare experiments!";
    });
  }

  getExperiment(){
    this.client.getExperimentByIdWithGET(this.id).subscribe((res:Response)=>{
      this.experiment = JSON.parse(res.text())['experiment'];
      this.numberOfJobs = this.experiment.jobs.length;
      for(var job of this.experiment.jobs){
        if(!this.datasets.includes(job.dataset.name)){
          this.datasets.push(job.dataset.name);
          this.datasetFilter.push(job.dataset.name);
        }

        this.checkJobOnQueue(job);
        this.generateJobData(job);
        this.updateFilteredData();
        this.addJobToSummaryJobs(job);
      }
    },(err)=>{
      this.hasError = true;
      this.errorMessage = JSON.parse(err)['message'];
    });
  }

  generateExperimentDataForCompare(experiment:any, experimentAverage:Array<any>){
    for(var job of experiment.jobs){
      this.generateJobData(job);
      this.addJobToCompareAverage(job, experimentAverage);
    }
  }

  generateJobData(job:any){
    job.labels = [];
    let data: Array<number> = [];
    var probeCount = 1;
    for(var measurement of job['measurements']){
      data.push(measurement.value);
      job.labels.push("Probe("+probeCount*this.experiment.probeInterval+"s)");
      probeCount++;
    }
    switch(job.measurementType){
      case "TIME":
        data[0] = data[0]/1000;
        job.barChartData = [{data:data, label:'Wall Time (s)'}];
        job.labels = ["Probe"];
        break;
      case "CPU":
        for(var i=0; i < data.length; i++){
          data[i] = data[i]/100;
        }
        job.barChartData = [{data:data, label:'CPU (%)'}];
        break;
      case "MEM":
        for(var i=0; i < data.length; i++){
          data[i] = data[i]/1024/1024;
        }
        job.barChartData = [{data:data, label:'Memory (MB)'}];
        break;
    }
  }

  checkJobOnQueue(job:any){
    this.client.isJobOnQueueWithGET(job.id).subscribe((res:Response)=>{
      var onQueue = JSON.parse(res.text());
      job.onQueue = onQueue['onQueue'];
      this.numberOfJobsLoaded ++;
      if(this.numberOfJobsLoaded == this.numberOfJobs){
        this.loaded = true;
      }
    });
  }

  downloadCSV(job_id: number){
    this.client.getJobCSVWithGET(job_id).subscribe((res:Response)=>{
      var blob = new Blob([res.text()],{type:'text/csv'});
      var url = window.URL.createObjectURL(blob);
      window.open(url);
    })
  }

  changeReport(){
    this.average = !this.average;
  }

  getJobClass(type:string):any{
    switch(type.toUpperCase()){
      case "TIME":
            return {
              teal: true
            }
      case "CPU":
            return{
              amber:true
            }
      case "MEM":
            return {
              red:true
            }
    }
  }

  private typeChange(value:any){
    for(var option of value.target){
      if(option.selected && !option.disabled){
        if(!this.measurementTypeFilter.includes(option.value)){
          this.measurementTypeFilter.push(option.value);
        }
      }else if(!option.selected && !option.disabled){
        if(this.measurementTypeFilter.includes(option.value)){
          var index = this.measurementTypeFilter.indexOf(option.value)
          this.measurementTypeFilter.splice(index,1);
        }
      }
    }

    this.updateFilteredData();
  }

  private datasetChange(value:any){
    for(var option of value.target){
      if(option.selected && !option.disabled){
        if(!this.datasetFilter.includes(option.value)){
          this.datasetFilter.push(option.value);
        }
      }else if(!option.selected && !option.disabled){
        if(this.datasetFilter.includes(option.value)){
          var index = this.datasetFilter.indexOf(option.value)
          this.datasetFilter.splice(index,1);
        }
      }
    }

    this.updateFilteredData();
  }

  private experimentChange(value:any){
    for(var option of value.target){
      if(option.selected && !option.disabled){
        if(!this.compareExperimentsSelected.includes(option.value)){
          this.compareExperimentsSelected.push(option.value);
        }
      }else if(!option.selected && !option.disabled){
        if(this.compareExperimentsSelected.includes(option.value)){
          var index = this.compareExperimentsSelected.indexOf(option.value)
          this.compareExperimentsSelected.splice(index,1);
        }
      }
    }
  }

  private updateFilteredData() {
    let newFilteredData:Array<any> = [];
    for (let obj of this.experiment.jobs) {
      if (this.measurementTypeFilter.includes(obj.measurementType) &&
        this.datasetFilter.includes(obj.dataset.name)) {
        newFilteredData.push(obj);
      }
    }
    this.filteredData = newFilteredData;
  }

  checkIfJobExists(incoming_job:any):any{
    for(var job of this.summaryJobs){
      if(job.dataset.name == incoming_job.dataset.name && job.measurementType == incoming_job.measurementType){
        return job;
      }
    }
    return null;
  }

  checkIfJobExistsCompare(incoming_job:any, compareList:any):any{
    for(var job of compareList){
      if(job.dataset.name == incoming_job.dataset.name && job.measurementType == incoming_job.measurementType){
        return job;
      }
    }
    return null;
  }

  addJobToSummaryJobs(incoming_job:any){
    let job:any = this.checkIfJobExists(incoming_job);
    if(job == null){
      job = {};
      job.dataset = incoming_job.dataset;
      job.algorithm = incoming_job.algorithm;
      job.measurementType = incoming_job.measurementType;
      job.barChartData = [];
      job.barChartData.push(incoming_job.barChartData[0]);
      job.labels = incoming_job.labels;
      this.createJobStats(job);
      this.summaryJobs.push(job);
    }else{
      if(!incoming_job.onQueue){
        job.barChartData.push(incoming_job.barChartData[0]);
        this.createJobStats(job);
      }

    }
  }

  addJobToCompareAverage(incoming_job:any, experimentAverage:Array<any>){
    let job:any = this.checkIfJobExistsCompare(incoming_job, experimentAverage);
    if(job == null){
      job = {};
      job.dataset = incoming_job.dataset;
      job.algorithm = incoming_job.algorithm;
      job.measurementType = incoming_job.measurementType;
      job.barChartData = [];
      job.barChartData.push(incoming_job.barChartData[0]);
      job.labels = incoming_job.labels;
      this.createJobStats(job);
      experimentAverage.push(job);
    }else{
        job.barChartData.push(incoming_job.barChartData[0]);
        this.createJobStats(job);
    }
  }

  createJobStats(job:any){
    let min:number = 9999999999;
    let max:number = -1;
    let average:number = 0;
    let total:number = 0;
    let count:number = 0;
    for(var data of job.barChartData){
      for(var i=0; i < data.data.length; i++){
        if(data.data[i] > max){
          max = data.data[i];
        }
        if(data.data[i] < min){
          min = data.data[i];
        }
        total += data.data[i];
        count ++;
      }
    }
    average = total/count;
    job.min = min;
    job.max = max;
    job.average = average;
  }
}


text:
package org.arquillian.extension.recorder.screenshooter.impl;

import org.arquillian.extension.recorder.screenshooter.AnnotationScreenshootingStrategy;
import org.arquillian.extension.recorder.screenshooter.ScreenshooterConfiguration;
import org.arquillian.extension.recorder.screenshooter.api.Screenshot;
import org.jboss.arquillian.core.spi.Validate;
import org.jboss.arquillian.core.spi.event.Event;
import org.jboss.arquillian.test.spi.TestResult;
import org.jboss.arquillian.test.spi.TestResult.Status;
import org.jboss.arquillian.test.spi.event.suite.After;
import org.jboss.arquillian.test.spi.event.suite.AfterTestLifecycleEvent;
import org.jboss.arquillian.test.spi.event.suite.Before;

/**
 * This strategy is treated after {@link DefaultScreenshootingStrategy} because of higher precedence. It overrides global
 * configuration by placing {@link Screenshot} annotation on a test method.
 *
 * @author Stefan Miklosovic
 *
 */
public class DefaultAnnotationScreenshootingStrategy implements AnnotationScreenshootingStrategy {

    private ScreenshooterConfiguration configuration;

    @Override
    public void setConfiguration(ScreenshooterConfiguration configuration) {
        Validate.notNull(configuration, "Screenshooter configuration is a null object!");
        this.configuration = configuration;
    }

    @Override
    public boolean isTakingAction(Event event, TestResult result) {
        if (event instanceof AfterTestLifecycleEvent && !(event instanceof After)) {
            Screenshot screenshotAnnotation = ScreenshotAnnotationScanner.getScreenshotAnnotation(((AfterTestLifecycleEvent) event).getTestMethod());

            if (screenshotAnnotation != null) {
                if (screenshotAnnotation.takeAfterTest()) {
                    return true;
                }
                if (result.getStatus() == Status.FAILED && screenshotAnnotation.takeWhenTestFailed()) {
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public boolean isTakingAction(Event event) {

        if (event instanceof Before) {
            Screenshot screenshotAnnotation = ScreenshotAnnotationScanner.getScreenshotAnnotation(((Before) event).getTestMethod());

            if (screenshotAnnotation != null) {
                return screenshotAnnotation.takeBeforeTest();
            }
        }

        return false;
    }

    @Override
    public int precedence() {
        return 1;
    }

}


text:
:- module(bc_action, [
    bc_register_action/6,   % +Name, +Label, +Icon, +Type, +Role, :Closure
    bc_execute_access_id/3, % +Actor, +Action, +EntryId
    bc_execute/4,           % +Actor, +Action, +EntryId, -Result
    bc_available_actions/3  % +Actor, +Id, -Actions
]).

:- use_module(library(error)).

:- use_module(bc_type).
:- use_module(bc_role).
:- use_module(bc_entry).

:- dynamic(action/6).

:- meta_predicate(bc_register_action(+, +, +, +, +, 3)).

%! bc_register_action(+Name, +Label, Icon, +Type, +Role, :Closure) is det.
%
% Registers a new action.

bc_register_action(Name, Label, Icon, Type, Role, Closure):-
    must_be(atom, Name),
    must_be(atom, Label),
    must_be(atom, Icon),
    must_be(atom, Type),
    must_be(atom, Role),
    (   action(Name, _, _, _, _, _)
    ->  retractall(action(Name, _, _, _, _, _))
    ;   true),
    assertz(action(Name, Label, Icon, Type, Role, Closure)),
    debug(bc_action, 'action ~w registered', [Name]).

%! bc_execute_access_id(+Actor, +Action, +EntryId) is semidet.
%
% Checks whether the actor has execute access for the
% given action on the entry.

bc_execute_access_id(Actor, _, _):-
    Actor.type = admin, !.

bc_execute_access_id(Actor, Action, EntryId):-
    bc_entry_type(EntryId, Type),
    action(Action, _, _, Type, Actor.type, _).

% TODO: comment.

bc_execute(Actor, Action, EntryId, Result):-
    (   action(Action, _, _, _, _, Closure)
    ->  run_closure(Closure, Actor, EntryId, Result)
    ;   throw(error(no_action))).

run_closure(Closure, Actor, EntryId, Result):-
    catch_with_backtrace(
        call(Closure, Actor, EntryId, Result),
        Error,
        print_message(error, Error)),
    (   nonvar(Error)
    ->  !, throw(error(action_failed))
    ;   true).

run_closure(_, _, _, _):-
    throw(error(action_failed)).

%! bc_available_actions(+Actor, +Id, -Actions) is det.
%
% Find the list of available actions for the entry.

bc_available_actions(Actor, _, Actions):-
    Actor.type = admin, !,
    all_actions(Actions).

bc_available_actions(Actor, Id, Actions):-
    bc_entry_type(Id, Type),
    role_type_actions(Actor.type, Type, Actions).

role_type_actions(Role, Type, Actions):-
    findall(
        _{ name: Name, label: Label, icon: Icon, type: Type },
        action(Name, Label, Icon, Type, Role, _),
        Actions).

all_actions(Actions):-
    findall(
        _{ name: Name, label: Label, icon: Icon, type: Type },
        action(Name, Label, Icon, Type, _, _),
        Actions).


text: alias b='ssh blog'


text:
using System;
using System.Diagnostics.CodeAnalysis;
using NFluent;
using NUnit.Framework;
using Sharpility.Extensions;
using Sharpility.Util;

namespace Sharpility.Tests.Util
{
    [TestFixture]
    public class InstanceCreatorTests
    {
        [Test]
        public void ShouldCreateInstanceOfSimpleObject()
        {
            // when
            var instance = InstanceCreator.CreateInstance<SimpleObject>();

            // then
            Check.That(instance).IsNotNull();
        }

        [Test]
        public void ShouldCreateInstanceOfObjectWithPrivateConstructor()
        {
            // when
            var instance = InstanceCreator.CreateInstance<PrivateConstructor>();

            // then
            Check.That(instance).IsNotNull();
        }

        [Test]
        public void ShouldCreateInstanceOfObjectWithoutDefaultConstrutor()
        {
            // when
            var instance = InstanceCreator.CreateInstance<NoDefaultConstructor>();

            // then
            Check.That(instance).IsNotNull();
            Check.That(instance)
                .IsEqualTo(new NoDefaultConstructor(a: null, b: 0, timeSpan: default(TimeSpan), obj: null));
        }

        // ReSharper disable once ClassNeverInstantiated.Local
        private class SimpleObject
        {
        }

        // ReSharper disable once ClassNeverInstantiated.Local
        private class PrivateConstructor
        {
            private PrivateConstructor()
            {
            }
        }

        [SuppressMessage("ReSharper", "NotAccessedField.Local")]
        private class NoDefaultConstructor
        {
            private int b;
            private string a;
            private TimeSpan timeSpan;
            private SimpleObject obj;

            internal NoDefaultConstructor(int b, string a, TimeSpan timeSpan, SimpleObject obj)
            {
                this.b = b;
                this.a = a;
                this.timeSpan = timeSpan;
                this.obj = obj;
            }

            public override bool Equals(object obj)
            {
                return this.EqualsByFields(obj);
            }

            public override int GetHashCode()
            {
                return this.FieldsHash();
            }

            public override string ToString()
            {
                return this.FieldsToString();
            }
        }
    }
}


text:
package org.jclouds.orion.blobstore.functions.parsers.param;

import org.jclouds.orion.OrionUtils;
import org.jclouds.orion.domain.OrionBlob;

import com.google.common.base.Function;

public class BlobNameParamParser implements Function<Object, String> {

	/**
	 * Returns encoded blob name
	 */
	@Override
	public String apply(Object blob) {

		return OrionUtils.getRequestLocation(((OrionBlob) blob).getProperties().getName());
	}

}


text:
#ifndef WRAPPER_POLYNOMIAL_H
#define WRAPPER_POLYNOMIAL_H

#include <node.h>

namespace PolynomialWrapper
{
/**
 * @brief   Calculates the best-fit polynomial function of an arbitrary set of
 *          points, interfaced with Node.js.
 */
void bestFit(const v8::FunctionCallbackInfo<v8::Value> & args);

}  // namespace PolynomialWrapper

#endif


text:
namespace TellOP.DataModels.ApiModels.LexTutor
{
    using Newtonsoft.Json;

    /// <summary>
    /// Ratios and statistics for a given word class.
    /// </summary>
    [JsonObject]
    public class LexTutorResultRatios
    {
        /// <summary>
        /// Gets or sets the number of words appearing in the text for this
        /// word class.
        /// </summary>
        [JsonProperty("wordsInText")]
        public int WordsInText { get; set; }

        /// <summary>
        /// Gets or sets the number of different words for this word class.
        /// </summary>
        [JsonProperty("differentWords")]
        public int DifferentWords { get; set; }

        /// <summary>
        /// Gets or sets the type/token ratio for this word class.
        /// </summary>
        [JsonProperty("typeTokenRatio")]
        public float TypeTokenRatio { get; set; }

        /// <summary>
        /// Gets or sets the tokens per type number for this word class.
        /// </summary>
        [JsonProperty("tokensPerType")]
        public float TokensPerType { get; set; }

        /// <summary>
        /// Gets or sets the number of tokens on the list for this word class.
        /// </summary>
        [JsonProperty("tokensOnList")]
        public int TokensOnList { get; set; }

        /// <summary>
        /// Gets or sets the number of types on the list for this word class.
        /// </summary>
        [JsonProperty("typesOnList")]
        public int TypesOnList { get; set; }

        /// <summary>
        /// Gets or sets the number of families on the list for this word class.
        /// </summary>
        [JsonProperty("familiesOnList")]
        public int FamiliesOnList { get; set; }

        /// <summary>
        /// Gets or sets the number of tokens per family on the list for this word class.
        /// </summary>
        [JsonProperty("tokensPerFamily")]
        public float TokensPerFamily { get; set; }

        /// <summary>
        /// Gets or sets the number of types per family on the list for this word class.
        /// </summary>
        [JsonProperty("typesPerFamily")]
        public float TypesPerFamily { get; set; }

        /// <summary>
        /// Gets or sets the number of cognate tokens for this word class.
        /// </summary>
        [JsonProperty("cognatesTokens")]
        public int CognatesTokens { get; set; }

        /// <summary>
        /// Gets or sets the number of "cognate with French" tokens for this word class.
        /// </summary>
        [JsonProperty("cognatesWithFrench")]
        public int CognatesWithFrench { get; set; }

        /// <summary>
        /// Gets or sets the number of "not cognate with French" tokens for this word class.
        /// </summary>
        [JsonProperty("notCognatesWithFrench")]
        public int NotCognatesWithFrench { get; set; }

        /// <summary>
        /// Gets or sets the cognateness for this word class.
        /// </summary>
        [JsonProperty("cognateness")]
        public float Cognateness { get; set; }

        /// <summary>
        /// Gets or sets the sum of individual frequencies for this word class.
        /// </summary>
        [JsonProperty("sumIndividualFreqs")]
        public float SumIndividualFrequencies { get; set; }

        /// <summary>
        /// Gets or sets the frequencies by rateable tokens for this word class.
        /// </summary>
        [JsonProperty("freqsByRateableTokens")]
        public int FrequenciesByRateableTokens { get; set; }

        /// <summary>
        /// Gets or sets the mean frequency for this class.
        /// </summary>
        [JsonProperty("meanFrequency")]
        public LexTutorResultValueStandardDeviation MeanFrequency { get; set; }

        /// <summary>
        /// Gets or sets the logarithm (in base 10) of the count index for this word class.
        /// </summary>
        [JsonProperty("countIndexLog10")]
        public LexTutorResultValueStandardDeviation CountIndexLog10 { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02.BankAccounts
{
    class CompanyCustomer : Customer
    {
        private string name;

        public CompanyCustomer(string name, string address)
            : base (address)
        {
            this.Name = name;
        }

        public string Name
        {
            get { return this.name; }
            set
            {
                if (string.IsNullOrEmpty(value) || value == " ")
                {
                    throw new ArgumentNullException("The company name cannot be empty");
                }
                this.name = value;
            }
        }
    }
}


text:
<!DOCTYPE html>

<link href="resources/flexbox.css" rel="stylesheet">

before text

  baseline

after text

Should align

with the

bottom of

the grey box.

Should align with the

bottom of the pink box.

Should align 8px

below the bottom

of the pink box.

Should align with the bottom

of the horizontal scrollbar.

Should align 10px below the

of the horizontal scrollbar, if one is visible.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/toshiyukiando/Documents/AndroidStudioWorkSpace/Jphacks-Eye-et/TK_09/Eye-et-glass-Advance/AdvancedLayout/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.1.1/res/values-v23/values-v23.xml -->
    <eat-comment/>
    <style name="Base.TextAppearance.AppCompat.Widget.Button.Inverse" parent="android:TextAppearance.Material.Widget.Button.Inverse"/>
    <style name="Base.Theme.AppCompat" parent="Base.V23.Theme.AppCompat"/>
    <style name="Base.Theme.AppCompat.Light" parent="Base.V23.Theme.AppCompat.Light"/>
    <style name="Base.V23.Theme.AppCompat" parent="Base.V22.Theme.AppCompat">
        <!-- We can use the platform drawable on v23+ -->
        <item name="actionBarItemBackground">?android:attr/actionBarItemBackground</item>
        <!-- We can use the platform styles on v23+ -->
        <item name="actionMenuTextColor">?android:attr/actionMenuTextColor</item>
        <item name="actionMenuTextAppearance">?android:attr/actionMenuTextAppearance</item>

        <item name="controlBackground">@drawable/abc_control_background_material</item>
    </style>
    <style name="Base.V23.Theme.AppCompat.Light" parent="Base.V22.Theme.AppCompat.Light">
        <!-- We can use the platform drawable on v23+ -->
        <item name="actionBarItemBackground">?android:attr/actionBarItemBackground</item>
        <!-- We can use the platform styles on v23+ -->
        <item name="actionMenuTextColor">?android:attr/actionMenuTextColor</item>
        <item name="actionMenuTextAppearance">?android:attr/actionMenuTextAppearance</item>

        <item name="controlBackground">@drawable/abc_control_background_material</item>
    </style>
    <style name="Base.Widget.AppCompat.Button.Colored" parent="android:Widget.Material.Button.Colored"/>
</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/rc_radio_button_on" />
    <item android:drawable="@drawable/rc_radio_button_off" />
</selector><!-- From: file:/Users/rhj/AndroidStudioProjects/EveryDayBuild/TestRongCloud01/IMKit/src/main/res/drawable/rc_switch_btn.xml --><!-- From: file:/Users/rhj/AndroidStudioProjects/EveryDayBuild/TestRongCloud01/IMKit/build/intermediates/bundles/debug/res/drawable/rc_switch_btn.xml -->


text:
// <license>
//     The MIT License (MIT)
// </license>
// <copyright company="TTRider Technologies, Inc.">
//     Copyright (c) 2014-2017 All Rights Reserved
// </copyright>

namespace TTRider.FluidSql
{
    public class DateFunctionExpressionToken : FunctionExpressionToken
    {
    }
}


text:
module Depp
  class Contact
    include ActiveModel::Model
    include DisableHtml5Validation

    attr_accessor :id, :name, :email, :phone, :org_name,
      :ident, :ident_type, :ident_country_code,
      :street, :city, :zip, :state, :country_code,
      :password, :legal_document, :statuses, :code

    DISABLED = 'Disabled'
    DISCLOSURE_TYPES = [DISABLED, '1', '0']
    TYPES = %w( org priv birthday )
    SELECTION_TYPES = [
      ['Business code', 'org'],
      ['Personal identification code', 'priv'],
      ['Birthday', 'birthday']
    ]

    class << self
      attr_reader :epp_xml, :user

      def new_from_params(params)
        new(
          id: params[:code],
          code: params[:code],
          email: params[:email],
          phone: params[:phone],
          ident: params[:ident],
          ident_type: params[:ident_type],
          ident_country_code: params[:ident_country_code],

          # postalInfo
          name: params[:name],
          org_name: params[:org_name],

          # address
          street:       params[:street],
          city:         params[:city],
          zip:          params[:zip],
          state:        params[:state],
          country_code: params[:country_code]
        )
      end

      # rubocop:disable Metrics/AbcSize
      def find_by_id(id)
        data = info_xml(id)

        res = data.css('epp response resData infData')
        ext = data.css('epp response extension')
        new(
          id: res.css('id').text,
          code: res.css('id').text,
          email: res.css('email').text,
          phone: res.css('voice').text,
          ident: ext.css('ident').text,
          ident_type: ext.css('ident').first.try(:attributes).try(:[], 'type').try(:value),
          ident_country_code: ext.css('ident').first.try(:attributes).try(:[], 'cc').try(:value),

          # postalInfo
          name: res.css('postalInfo name').text,
          org_name: res.css('postalInfo org').text,

          # address
          street:       res.css('postalInfo addr street').text,
          city:         res.css('postalInfo addr city').text,
          zip:          res.css('postalInfo addr pc').text,
          state:        res.css('postalInfo addr sp').text,
          country_code: res.css('postalInfo addr cc').text,

          # authInfo
          password: res.css('authInfo pw').text,

          # statuses
          statuses: data.css('status').map { |s| [s['s'], s.text] }
        )
      end
      # rubocop:enable Metrics/AbcSize

      def user=(user)
        @user = user
        @epp_xml = EppXml::Contact.new(cl_trid_prefix: user.tag)
      end

      def info_xml(id, password = nil)
        xml = epp_xml.info(
          id: { value: id },
          authInfo: { pw: { value: password } }
        )
        user.request(xml)
      end

      def construct_check_hash_from_data(data)
        res = data.css('epp response resData chkData cd')
        @contacts = []
        res.each do |_r|
          id = res.css('id').try(:text)
          reason = res.css('reason').present? ? res.css('reason').text : I18n.t(:available)
          @contacts << { id: id, reason: reason  }
        end
        @contacts
      end

      def contact_id_from_xml(data)
        id = data.css('epp response resData creData id').text
        id.blank? ? nil : id
      end

      def construct_create_disclosure_xml(cph, flag)
        xml = { disclose: {} }
        cph.each do |k, v|
          xml[:disclose][k] = {}
          xml[:disclose][k][:value] = v
        end
        xml[:disclose][:attrs] = {}
        xml[:disclose][:attrs][:flag] = flag
        xml.with_indifferent_access
      end

      def extract_disclosure_hash(cpd) # cpd = contact_params[:disclose]
        return {} unless cpd
        cpd = cpd.delete_if { |k, v| v if v != '1' && k == 'flag' }
        cpd
      end

      def extract_info_disclosure(data)
        hash = {}
        data.css('disclose').each do |d|
          flag = d.attributes['flag'].value
          next unless flag
          hash[flag] = {}
          d.children.each do |c|
            hash[flag][c.name] = flag if %w( name email fax voice addr org_name ).include?(c.name)
          end
        end
        hash
      end

      def type_string(type_code)
        return '' if type_code.blank?
        t = SELECTION_TYPES.select { |tp| tp.second == type_code }
        t.try(:first).try(:first)
      end
    end

    def save
      hash = {
        id: { value: code },
        postalInfo: {
          name: { value: name },
          org:  { value: org_name },
          addr: {
            street: { value: street },
            city:   { value: city },
            sp:     { value: state },
            pc:     { value: zip },
            cc:     { value: country_code }
          }
        },
        voice: { value: phone },
        email: { value: email }
      }

      hash[:id] = nil if code.blank?
      create_xml = Depp::Contact.epp_xml.create(hash, extension_xml(:create))

      data = Depp::Contact.user.request(create_xml)
      self.id = data.css('id').text
      handle_errors(data)
    end

    # rubocop:disable Metrics/MethodLength
    # rubocop:disable Metrics/AbcSize
    def update_attributes(params)
      self.ident_country_code = params[:ident_country_code]
      self.ident_type   = params[:ident_type]
      self.ident        = params[:ident]

      self.name  = params[:name]
      self.email = params[:email]
      self.phone = params[:phone]

      self.org_name     = params[:org_name]
      self.street       = params[:street]
      self.city         = params[:city]
      self.zip          = params[:zip]
      self.state        = params[:state]
      self.country_code = params[:country_code]

      update_xml = Depp::Contact.epp_xml.update(
        {
          id: { value: id },
          chg: {
            postalInfo: {
              name: { value: name },
              org:  { value: org_name },
              addr: {
                street: { value: street },
                city:   { value: city },
                sp:     { value: state },
                pc:     { value: zip },
                cc:     { value: country_code }
              }
            },
            voice: { value: phone },
            email: { value: email },
            authInfo: {
              pw: { value: password }
            }
          }
        },
        extension_xml(:update)
      )
      data = Depp::Contact.user.request(update_xml)
      handle_errors(data)
    end
    # rubocop:enbale Metrics/AbcSize
    # rubocop:enable Metrics/MethodLength

    def delete
      delete_xml = Contact.epp_xml.delete(
        {
          id: { value: id },
          authInfo: { pw: { value: password } }
        },
        extension_xml(:delete)
      )
      data = Depp::Contact.user.request(delete_xml)
      handle_errors(data)
    end

    # rubocop:disable Metrics/CyclomaticComplexity
    # rubocop:disable Style/NegatedIf
    # rubocop:disable Style/RedundantSelf
    def extension_xml(action)
      xml = { _anonymus: [] }

      case action
      when :create
        ident = ident_xml[:_anonymus].try(:first)
      when :update
        # detect if any ident has changed, nb! ident and self.ident is not always same
        if !(ident == self.ident && ident == self.ident_type && ident_country_code == self.ident_country_code)
          ident = ident_xml[:_anonymus].try(:first)
        end
      end

      legal = legal_document_xml[:_anonymus].try(:first)
      xml[:_anonymus] << ident if ident.present?
      xml[:_anonymus] << legal if legal.present?
      xml
    end
    # rubocop:enable Metrics/CyclomaticComplexity
    # rubocop:enable Style/NegatedIf
    # rubocop:enable Style/RedundantSelf

    def ident_xml
      {
        _anonymus: [
          ident: { value: ident, attrs: { type: ident_type, cc: ident_country_code } }
        ]
      }
    end

    def legal_document_xml
      return {} if legal_document.blank?

      type = legal_document.original_filename.split('.').last.downcase
      {
        _anonymus: [
          legalDocument: { value: Base64.encode64(legal_document.read), attrs: { type: type } }
        ]
      }
    end

    def check(id)
      xml = epp_xml.check(id: { value: id })
      current_user.request(xml)
    end

    def country_name
      Country.new(country_code) || 'No access'
    end

    def org?
      ident_type == 'org'
    end

    def priv?
      ident_type == 'priv'
    end

    def persisted?
      id.present?
    end

    def handle_errors(data)
      data.css('result').each do |x|
        success_codes = %(1000, 1300, 1301)
        next if success_codes.include?(x['code'])

        message = "#{x.css('msg').text} #{x.css('value').text}"
        attr = message.split('[').last.strip.sub(']', '') if message.include?('[')
        attr = :base if attr.nil?
        attr = 'phone' if attr == 'voice'
        attr = 'zip' if attr == 'pc'
        errors.add(attr, message)
      end
      errors.blank?
    end
  end
end


text:
<?php

class Google_Service_Compute_DiskType extends Google_Model
{
  public $creationTimestamp;
  public $defaultDiskSizeGb;
  protected $deprecatedType = 'Google_Service_Compute_DeprecationStatus';
  protected $deprecatedDataType = '';
  public $description;
  public $id;
  public $kind;
  public $name;
  public $selfLink;
  public $validDiskSize;
  public $zone;

  public function setCreationTimestamp($creationTimestamp)
  {
    $this->creationTimestamp = $creationTimestamp;
  }
  public function getCreationTimestamp()
  {
    return $this->creationTimestamp;
  }
  public function setDefaultDiskSizeGb($defaultDiskSizeGb)
  {
    $this->defaultDiskSizeGb = $defaultDiskSizeGb;
  }
  public function getDefaultDiskSizeGb()
  {
    return $this->defaultDiskSizeGb;
  }
  /**
   * @param Google_Service_Compute_DeprecationStatus
   */
  public function setDeprecated(Google_Service_Compute_DeprecationStatus $deprecated)
  {
    $this->deprecated = $deprecated;
  }
  /**
   * @return Google_Service_Compute_DeprecationStatus
   */
  public function getDeprecated()
  {
    return $this->deprecated;
  }
  public function setDescription($description)
  {
    $this->description = $description;
  }
  public function getDescription()
  {
    return $this->description;
  }
  public function setId($id)
  {
    $this->id = $id;
  }
  public function getId()
  {
    return $this->id;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
  public function setSelfLink($selfLink)
  {
    $this->selfLink = $selfLink;
  }
  public function getSelfLink()
  {
    return $this->selfLink;
  }
  public function setValidDiskSize($validDiskSize)
  {
    $this->validDiskSize = $validDiskSize;
  }
  public function getValidDiskSize()
  {
    return $this->validDiskSize;
  }
  public function setZone($zone)
  {
    $this->zone = $zone;
  }
  public function getZone()
  {
    return $this->zone;
  }
}


text:
vanilla-forums-api
==========================
[![Code Climate](https://codeclimate.com/github/corthmann/vanilla-forums-api/badges/gpa.svg)](https://codeclimate.com/github/corthmann/vanilla-forums-api)
[![Test Coverage](https://codeclimate.com/github/corthmann/vanilla-forums-api/badges/coverage.svg)](https://codeclimate.com/github/corthmann/vanilla-forums-api/coverage)

Connect Ruby applications with the Vanilla forums Platform

Installation
-------------
You can install this gem by using the following command:
```
gem install vanilla-forums-api
```
or by adding the the following line to your Gemfile.
```
gem 'vanilla-forums-api'
```

Configuration
-------------
```
require 'vanilla-forums-api'
VanillaForumsAPI.configure do |config|
    config.endpoint = 'https://yoursite.vanillaforums.com'
    config.access_token = '123'
end
```

Using the API
-------------
Get a list of categories:
```
require 'vanilla-forums-api/models/category'
categories = VanillaForumsAPI::Category.find_all
categories = VanillaForumsAPI::Category.find_all(page = 2)
```
Get the category with a given id
```
require 'vanilla-forums-api/models/category'
category = VanillaForumsAPI::Category.find_by_id(11)
```

API Support
-------------
The following APIs are supported:

API | Gem Version | Official Documentation
--- | --- | ---
categories | 1.0.0 | http://docs.vanillaforums.com/api/categories/
comments | 1.0.0 | http://docs.vanillaforums.com/api/comments/
forum administration | 1.0.0 | http://docs.vanillaforums.com/api/forum-administration/
role | 1.0.0 | http://docs.vanillaforums.com/api/roles/


text:
#import "WXThreadSafeMutableArray.h"
#import "WXUtility.h"
#import <os/lock.h>
#import <pthread/pthread.h>

@interface WXThreadSafeMutableArray () {
    pthread_mutex_t _safeThreadArrayMutex;
    pthread_mutexattr_t _safeThreadArrayMutexAttr;
}

@property (nonatomic, strong) dispatch_queue_t queue;
@property (nonatomic, strong) NSMutableArray* array;

@end

@implementation WXThreadSafeMutableArray

- (instancetype)initCommon
{
    self = [super init];
    if (self) {
        NSString* uuid = [NSString stringWithFormat:@"com.taobao.weex.array_%p", self];
        _queue = dispatch_queue_create([uuid UTF8String], DISPATCH_QUEUE_CONCURRENT);
        pthread_mutexattr_init(&(_safeThreadArrayMutexAttr));
        pthread_mutexattr_settype(&(_safeThreadArrayMutexAttr), PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&(_safeThreadArrayMutex), &(_safeThreadArrayMutexAttr));
    }
    return self;
}

- (instancetype)init
{
    self = [self initCommon];
    if (self) {
        _array = [NSMutableArray array];
    }
    return self;
}

- (instancetype)initWithCapacity:(NSUInteger)numItems
{
    self = [self initCommon];
    if (self) {
        _array = [NSMutableArray arrayWithCapacity:numItems];
    }
    return self;
}

- (NSArray *)initWithContentsOfFile:(NSString *)path
{
    self = [self initCommon];
    if (self) {
        _array = [NSMutableArray arrayWithContentsOfFile:path];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [self initCommon];
    if (self) {
        _array = [[NSMutableArray alloc] initWithCoder:aDecoder];
    }
    return self;
}

- (instancetype)initWithObjects:(const id [])objects count:(NSUInteger)cnt
{
    self = [self initCommon];
    if (self) {
        _array = [NSMutableArray array];
        for (NSUInteger i = 0; i < cnt; ++i) {
            [_array addObject:objects[i]];
        }
    }
    return self;
}

- (NSUInteger)count
{
    __block NSUInteger count;
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_sync(_queue, ^{
            count = _array.count;
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        count = [_array count];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
    return count;
}

- (id)objectAtIndex:(NSUInteger)index
{
    __block id obj;
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_sync(_queue, ^{
            obj = _array[index];
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        obj = _array[index];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
    return obj;
}

- (NSEnumerator *)keyEnumerator
{
    __block NSEnumerator *enu;
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_sync(_queue, ^{
            enu = [_array objectEnumerator];
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        enu = [_array objectEnumerator];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
    return enu;
}

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
{
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_barrier_async(_queue, ^{
            [_array insertObject:anObject atIndex:index];
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        [_array insertObject:anObject atIndex:index];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
}

- (void)addObject:(id)anObject;
{
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_barrier_async(_queue, ^{
            [_array addObject:anObject];
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        [_array addObject:anObject];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
}

- (void)removeObjectAtIndex:(NSUInteger)index
{
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_barrier_async(_queue, ^{
            [_array removeObjectAtIndex:index];
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        [_array removeObjectAtIndex:index];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
}

- (void)removeLastObject
{
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_barrier_async(_queue, ^{
            [_array removeLastObject];
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        [_array removeLastObject];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
}

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject
{
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_barrier_async(_queue, ^{
            [_array replaceObjectAtIndex:index withObject:anObject];
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        [_array replaceObjectAtIndex:index withObject:anObject];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }
}

- (NSUInteger)indexOfObject:(id)anObject
{
    __block NSUInteger index = NSNotFound;
    if (![WXUtility threadSafeCollectionUsingLock]) {
        dispatch_sync(_queue, ^{
            for (int i = 0; i < [_array count]; i ++) {
                if ([_array objectAtIndex:i] == anObject) {
                    index = i;
                    break;
                }
            }
        });
    } else {
        pthread_mutex_lock(&_safeThreadArrayMutex);
        index = [_array indexOfObject:anObject];
        pthread_mutex_unlock(&_safeThreadArrayMutex);
    }

    return index;
}

- (void)dealloc
{
    if (_queue) {
        _queue = NULL;
    }
    pthread_mutex_destroy(&_safeThreadArrayMutex);
    pthread_mutexattr_destroy(&_safeThreadArrayMutexAttr);
}

@end


text:
package parser

import (
	"fmt"
	"github.com/DrItanium/cores"
)

var parsers map[string]Registration

type Entry struct {
	Line  string
	Index int
}
type Registration interface {
	New(args ...interface{}) (Parser, error)
}
type Parser interface {
	cores.Dumper
	Parse(lines <-chan Entry) error
	Process() error
}

func Register(name string, reg Registration) error {
	if parsers == nil {
		parsers = make(map[string]Registration)
	}
	if _, ok := parsers[name]; ok {
		return fmt.Errorf("Parser %s is already registered!", name)
	} else {
		parsers[name] = reg
		return nil
	}

}

func GetRegistered() []string {
	var names []string
	if parsers != nil {
		for name, _ := range parsers {
			names = append(names, name)
		}
	}
	return names
}

func New(name string, args ...interface{}) (Parser, error) {
	if parsers == nil {
		return nil, fmt.Errorf("No parsers registered!")
	}
	if gen, ok := parsers[name]; ok {
		return gen.New(args)
	} else {
		return nil, fmt.Errorf("%s does not refer to a registered parser!", name)
	}
}
func IsRegistered(name string) bool {
	if parsers == nil {
		return false
	} else {
		_, ok := parsers[name]
		return ok
	}
}

func Activate() {}

type Registrar func(...interface{}) (Parser, error)

func (this Registrar) New(args ...interface{}) (Parser, error) {
	return this(args)
}


text:
var step = ''
            +'
Test Purpose:
'
            +'
Verifies the async and defer attributes of script element, classList, getElementsByClassName and matchesSelector work well.
'
            +'
Expected Result:
'
            +'
Test pass if a green PASS displays on the page, otherwise test fail
'
          +'';


text:
package com.yammer.dropwizard.config;

/**
 * An exception thrown where there is an error parsing a configuration object.
 */
public class ConfigurationException extends Exception {
    private static final long serialVersionUID = 5325162099634227047L;

    /**
     * Creates a new ConfigurationException for the given file with the given errors.
     *
     * @param file      the bad configuration file
     * @param errors    the errors in the file
     */
    public ConfigurationException(String file, Iterable<String> errors) {
        super(formatMessage(file, errors));
    }

    private static String formatMessage(String file, Iterable<String> errors) {
        final StringBuilder msg = new StringBuilder(file)
                .append(" has the following errors:\n");
        for (String error : errors) {
            msg.append("  * ").append(error).append('\n');
        }
        return msg.toString();
    }
}


text:
title: ITransactional::commit — Core Library
package: lib
packageTitle: Core Library
layout: default
className: ITransactional
type: method
---

# ITransactional::commit

## Synopsis

uses('db');

public function ITransactional::commit()


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutSelectFileActivityMain">

</RelativeLayout>


text:
"""fixtures.py - Module with fixture information and generating functions

"""
#Author: Ian Huston
#For license and copyright information see LICENSE.txt which was distributed with this file.

from pyflation import helpers

kmins_default = [1e-61, 3e-61, 1e-60]
deltaks_default = [1e-61, 3e-61, 1e-60]
nthetas_default = [129, 257, 513]
numsoks_default = [257, 513, 1025]
As_default = [2.7e57]
Bs_default = [1e-62]
etas_default = [-2.7559960682873626e+68]

def generate_fixtures(kmins=kmins_default, deltaks=deltaks_default, numsoks=numsoks_default,
                      nthetas=nthetas_default):
    """Generator for fixtures created from cartesian products of input lists."""
    c = helpers.cartesian_product([kmins, deltaks, numsoks, nthetas])
    for now in c:
        fullkmax = helpers.getkend(now[0], now[1], now[2])
        fx = {"kmin":now[0], "deltak":now[1], "numsoks":now[2], "fullkmax":fullkmax,
              "nthetas":now[3]}
        yield fx

def fixture_from_model(m, numsoks=None, nthetas=nthetas_default[-1]):
    """Generate a single fixture from a cosmomodels model.

    If numsoks is not specified, then use the last value in the defaults.
    """
    if not numsoks:
        numsoks = numsoks_default[-1]

    fullkmax = helpers.getkend(m.k[0], m.k[1]-m.k[0], numsoks)

    fx = {"kmin":m.k[0], "deltak":m.k[1]-m.k[0], "numsoks":numsoks,
               "fullkmax":fullkmax, "nthetas":nthetas}

    return fx


text:
---
layout: page
author: mikey
title: Winnu
comments: true
permalink: /races/Winnu/
published: true
---

![The Winnu]({{ site.baseurl }}/images/races/Winnu.jpg "The Winnu")

## THE WINNU

**In a word:** Custodians of the ancient empire

**Background:** Now that the empire has fallen and the imperial race has disappeared from the universe, the Winnu have upheld the lore, tradition, and culture of the old empire.  Although they had hoped that the imperial race would return and restore the glory of the empire, they have started to lose hope in that dream.  Now many of the Winnu feel that they are the rightful successors to the Empire.  Now is the time to put an end to this age of chaos and return the universe to it's former glory.  The Winnu will protect and honor the heritage of the empire forever.

**Advantages**: Unique Racial Abilities and Racial Technologies, resource-influence swapping very useful, all-around solid Race.

**Disadvantages**: Racial abilities all center around controlling Mecatol Rex, not especially powerful in any one area, mediocre flagship.

**Style:** Versatile with economic/diplomatic slant.

>**Homeworlds**: Winnu (3/4)
>
>**Starting Units**: 1 Carrier; 1 Cruiser; 2 Fighters; 2 Infantry; 1 Space Dock; 1 PDS
>
>**Starting Tech**: Choose any 1 technology that has no prerequisites.
>
>**Commodities**: 3
>
>**Promissory Note**: _Acquiescence_ - At the end of the strategy phase: Exchange 1 of your strategy cards with the strategy card that was chosen by the Winnu player. Then return this card to the Winnu player.
>
>**Abilities**
>
>_Blood Ties_: You do not have to spend influence to remove the custodians token form Mecatol Rex.
>
>_Reclamation_: After you resolve a tactical action during which you gaind control of Mecatol Rex, you may place 1 PDS and 1 space dock from your reinforcements on Mecatol Rex.
>
>**Special Units**
>
>_Salai Sai Corian_ (Flagship): Cost 8, Combat 7, Movement 1, Capacity 3;
>>_Sustain Damage_;
>>
>>When this unit makes a combat roll, it rolls a number of dice equal to the number of your opponent's non-fighter ships in this system
>
>**Race Technology**
>
>_Lazax Gate Folding_ (blue; req. BB): During your tactical actions, if you do not control Mecatol Rex, treat its system as if it contains both an alpha and beta wormhole; Action: If you control Mecatol Rex, exhaust this card to place 1 infantry from your reinforcements on Mecatol Rex.
>
>_Hegemonic Trade Policy_ (yellow; req. YY): Exhaust this card when 1 or more of you units use Production; swap the resource and influence values of 1 planet you control until the end of your turn.

{% if page.comments %}

Please enable JavaScript to view the comments powered by Disqus.

{% endif %}


text:
module.exports = function(options){
    //SETTINGS
    /*
     if(!options.avoidDefaultOperators){
     if(options.enabledOperators){
     for(var i=0; i< options.enabledOperators.length; i++){
     //trigger error if operator not present
     _operators = default_operators[options.enabledOperators[i]];
     }

     } else {
     _operators = default_operators;
     }

     if(options.disabledOperators){
     for(var i=0; i< options.disabledOperators.length; i++){
     //trigger error if operator not present
     delete _operators[options.disabledOperators[i]];
     }
     }
     }
     */

    var _addOperators = function(operators){
        for(var i=0; i< operators.length; i++){
            for (var key in operators[i]) {
                if( operators[i].hasOwnProperty(key) ) {
                    _operators[key] = operators[i][key];
                }
            }
        }
    };

    //set defaults
    var stringParser = require('./lib/parseString')({});
    var conditionParser = require('./lib/parseCondition')({});

    var _evaluate = function(str, values){
        var expression = stringParser.evaluateString(str);

        return conditionParser.evaluate(expression, values);
    };

    return {
        addOperators: _addOperators,
        evaluate: _evaluate
    }
};


text:
#pragma once
#include <aws/mediaconvert/MediaConvert_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace MediaConvert
{
namespace Model
{
  enum class CmfcTimedMetadata
  {
    NOT_SET,
    PASSTHROUGH,
    NONE
  };

namespace CmfcTimedMetadataMapper
{
AWS_MEDIACONVERT_API CmfcTimedMetadata GetCmfcTimedMetadataForName(const Aws::String& name);

AWS_MEDIACONVERT_API Aws::String GetNameForCmfcTimedMetadata(CmfcTimedMetadata value);
} // namespace CmfcTimedMetadataMapper
} // namespace Model
} // namespace MediaConvert
} // namespace Aws


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { environment } from '../../../../environments/environment';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AuthService } from '../../../core/services/auth.service';
import { Store } from '@ngrx/store';
import { AppAllState } from '../../../interfaces';
import { Router, ActivatedRoute } from '@angular/router';
import { getAuthStatus } from '../../../core/reducers/selectors';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {
  signInForm: FormGroup;
  loginSubs: Subscription;
  returnUrl: string;

  constructor(
    private fb: FormBuilder,
    private store: Store<AppAllState>,
    private route: ActivatedRoute,
    private router: Router,
    private authService: AuthService
  ) {
    this.redirectIfUserLoggedIn();
  }

  ngOnInit() {
    this.initForm();
    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/pages';
  }

  onSubmit() {
    const values = this.signInForm.value;
    const keys = Object.keys(values);

    if (this.signInForm.valid) {
      this.loginSubs = this.authService.login(values).subscribe(data => {
        const error = data.error;
        if (error) {
          keys.forEach(val => {
            this.pushErrorFor(val, error);
          });
        }
      });
    } else {
      keys.forEach(val => {
        const ctrl = this.signInForm.controls[val];
        if (!ctrl.valid) {
          this.pushErrorFor(val, null);
          ctrl.markAsTouched();
        };
      });
    }
  }

  private pushErrorFor(ctrl_name: string, msg: string) {
    this.signInForm.controls[ctrl_name].setErrors({'msg': msg});
  }

  initForm() {
    const nickname = '';
    const password = '';

    this.signInForm = this.fb.group({
      'nickname': [nickname, Validators.required],
      'password': [password, Validators.required]
    });
  }

  redirectIfUserLoggedIn() {
    this.store.select(getAuthStatus).subscribe(
      data => {
        if (data === true) { this.router.navigate([this.returnUrl]); }
      }
    );
  }

  ngOnDestroy() {
    if (this.loginSubs) { this.loginSubs.unsubscribe(); }
  }

}


text:
package com.xlythe.service.weather;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Base64;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class ParcelableUtils {
    @NonNull
    public static String toString(@NonNull Parcelable parcelable) {
        Parcel parcel = Parcel.obtain();
        parcelable.writeToParcel(parcel, 0);
        try {
            return Base64.encodeToString(parcel.marshall(), Base64.DEFAULT);
        } finally {
            parcel.recycle();
        }
    }

    @Nullable
    public static <T extends Parcelable> T fromString(@Nullable String data, @NonNull Parcelable.Creator<T> creator) {
        if (data == null) {
            return null;
        }
        byte[] bytes = Base64.decode(data, Base64.DEFAULT);
        Parcel parcel = Parcel.obtain();
        parcel.unmarshall(bytes, 0, bytes.length);
        parcel.setDataPosition(0);
        try {
            return creator.createFromParcel(parcel);
        } finally {
            parcel.recycle();
        }
    }

    public static void fromString(@Nullable String data, @NonNull RestorableParcelable parcelable) {
        if (data == null) {
            return;
        }
        byte[] bytes = Base64.decode(data, Base64.DEFAULT);
        Parcel parcel = Parcel.obtain();
        parcel.unmarshall(bytes, 0, bytes.length);
        parcel.setDataPosition(0);
        try {
            parcelable.readFromParcel(parcel);
        } finally {
            parcel.recycle();
        }
    }

    public interface RestorableParcelable extends Parcelable {
        void readFromParcel(Parcel in);
    }
}


text:
namespace Minion
{
    /// <summary>
    /// Encapsulates a method which returns a given type.
    /// </summary>
    /// <returns></returns>
    public delegate TResult Function<TResult>();

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public delegate TResult Function<T1, TResult>(T1 arg1);

    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    public delegate TResult Function<T1, T2, TResult>(T1 arg1, T2 arg2);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cortinarius archeri Berk.

### Remarks
null


text:
'use strict';

// PasswordValidator service used for testing the password strength
angular.module('users').factory('PasswordValidator', ['$window',
  function ($window) {
    var owaspPasswordStrengthTest = $window.owaspPasswordStrengthTest;

    return {
      getResult: function (password) {
        var result = owaspPasswordStrengthTest.test(password);
        return result;
      },
      getPopoverMsg: function () {
        var popoverMsg = 'Please enter a password with 4 or more characters.';
        return popoverMsg;
      }
    };
  }
]);


text:
<resources>
    <string name="app_name">147. Static ViewAnimator</string>
</resources>


text:
A bot that uses a lottery system to win free games on steam.

Using it is quite the dick move to be honest, so make sure to also give away games to give the people something back. Using the bot is technically allowed, it shouldn't be overused though.
Since the bot is backed by a cron script, it's up to you how often it should run.

### How to use
GiftFox should run on pretty much every system running PHP5+ & MySQL.
Its actual development version is running on a Synology DS

**Installation**
- Copy all the files to a location on your server
- Create a MySQL database for the bot and import the `database.sql` structure
- Adjust the `/app/config.php` file with your database configuration
- Adjust the `/index.php` file with the subdirectory of the script on your server
- Adjust the include paths in `/app/cron/execute.php`
 - Some systems require absolute paths when running the script from a cron!
- Create a cronjob to run `/app/cron/execute.php` once in a while.
 - The script itself has a minimum interval of 7h per user hardcoded
 - You can change this in the `execute.php` script if so desired.
- Manually create a new user in the database, give it a username, password and token.
 - Since this is not ment as a "serious" account system, nothing is encrypted
 - Also, there's no comfortable function to add a user yet
- Log in with the user via the GifFox UI
- GiftFox should ask you for a session token
 - Copy your `PHPSESSID` session cookie from steamgifts.com and enter it
- Everything should run fine now.