text:
"""
This will generate a movie data set of 1100 records.
These are the first 1100 movies which appear when querying the Freebase of type '/film/film'.
Here is the link to the freebase page - https://www.freebase.com/film/film?schema=

Usage - python3 film_data_generator.py
"""

import csv
import copy
import json
import codecs
import datetime
import urllib.parse
import urllib.request
import xml.etree.cElementTree as ET
from xml.dom import minidom

MAX_ITERATIONS=10  #10 limits it to 1100 docs

# You need an API Key by Google to run this
API_KEY = '<insert your Google developer API key>'
service_url = 'https://www.googleapis.com/freebase/v1/mqlread'
query = [{
  "id": None,
  "name": None,
  "initial_release_date": None,
  "directed_by": [],
  "genre": [],
  "type": "/film/film",
  "initial_release_date>" : "2000"
}]

def gen_csv(filmlist):
  filmlistDup = copy.deepcopy(filmlist)
  #Convert multi-valued to % delimited string
  for film in filmlistDup:
      for key in film:
        if isinstance(film[key], list):
          film[key] = '|'.join(film[key])
  keys = ['name', 'directed_by', 'genre', 'type', 'id', 'initial_release_date']
  with open('films.csv', 'w', newline='', encoding='utf8') as csvfile:
    dict_writer = csv.DictWriter(csvfile, keys)
    dict_writer.writeheader()
    dict_writer.writerows(filmlistDup)

def gen_json(filmlist):
  filmlistDup = copy.deepcopy(filmlist)
  with open('films.json', 'w') as jsonfile:
    jsonfile.write(json.dumps(filmlist, indent=2))

def gen_xml(filmlist):
  root = ET.Element("add")
  for film in filmlist:
    doc = ET.SubElement(root, "doc")
    for key in film:
      if isinstance(film[key], list):
        for value in film[key]:
          field = ET.SubElement(doc, "field")
          field.set("name", key)
          field.text=value
      else:
        field = ET.SubElement(doc, "field")
        field.set("name", key)
        field.text=film[key]
  tree = ET.ElementTree(root)
  with open('films.xml', 'w') as f:
    f.write( minidom.parseString(ET.tostring(tree.getroot(),'utf-8')).toprettyxml(indent="  ") )

def do_query(filmlist, cursor=""):
  params = {
          'query': json.dumps(query),
          'key': API_KEY,
          'cursor': cursor
  }
  url = service_url + '?' + urllib.parse.urlencode(params)
  data = urllib.request.urlopen(url).read().decode('utf-8')
  response = json.loads(data)
  for item in response['result']:
    del item['type'] # It's always /film/film. No point of adding this.
    try:
      datetime.datetime.strptime(item['initial_release_date'], "%Y-%m-%d")
    except ValueError:
      #Date time not formatted properly. Keeping it simple by removing the date field from that doc
      del item['initial_release_date']
    filmlist.append(item)
  return response.get("cursor")

if __name__ == "__main__":
  filmlist = []
  cursor = do_query(filmlist)
  i=0
  while(cursor):
      cursor = do_query(filmlist, cursor)
      i = i+1
      if i==MAX_ITERATIONS:
          break

  gen_json(filmlist)
  gen_csv(filmlist)
  gen_xml(filmlist)


text:
package com.kiddo.model;

import java.time.DayOfWeek;
import java.time.LocalTime;

import lombok.Data;

@Data
public class OpenHours {
	private DayOfWeek day;
	private LocalTime open;
	private LocalTime close;

	public void setOpen(String time) {
		this.open = LocalTime.parse(time);
	}

	public void setClose(String time) {
		this.close = LocalTime.parse(time);
	}
}

redpajama_set_name: RedPajamaGithub


text:
module FileHelper
end


text:
package gov.va.med.pharmacy.peps.external.common.preencapsulation.utility.drugcheck;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import gov.va.med.pharmacy.peps.common.exception.InterfaceValidationException;
import gov.va.med.pharmacy.peps.common.vo.DrugCheckVo;
import gov.va.med.pharmacy.peps.common.vo.OrderCheckHeaderVo;
import gov.va.med.pharmacy.peps.common.vo.OrderCheckVo;
import gov.va.med.pharmacy.peps.external.common.preencapsulation.vo.drug.check.request.Checks;
import gov.va.med.pharmacy.peps.external.common.preencapsulation.vo.drug.check.request.DoseInformation;
import gov.va.med.pharmacy.peps.external.common.preencapsulation.vo.drug.check.request.Drug;
import gov.va.med.pharmacy.peps.external.common.preencapsulation.vo.drug.check.request.DrugDoseCheck;
import gov.va.med.pharmacy.peps.external.common.preencapsulation.vo.drug.check.request.Header;
import gov.va.med.pharmacy.peps.external.common.preencapsulation.vo.drug.check.request.PEPSRequest;

/**
 * Converts an XML request into a VO
 */
public class RequestConverter {

    /**
     * Convert the given PEPSRequest into an OrderCheckVo.
     *
     * @param request PEPSRequest to convert
     * @return OrderCheckVo created from XML String
     */
    public static OrderCheckVo toOrderCheckVo(PEPSRequest request) {
        OrderCheckVo orderCheck = new OrderCheckVo();

        orderCheck.setHeader(toHeader(request.getHeader()));

        // the Body element does not need to be set if this is a ping request
        if (request.isSetBody()) {
            Checks checks = request.getBody().getDrugCheck().getChecks();

            if (checks.isSetUseCustomTables()) {
                orderCheck.setCustomTables(checks.isUseCustomTables());
            }
            else { // default use of custom tables to true
                orderCheck.setCustomTables(true);
            }

            if (checks.isSetProspectiveOnly()) {
                orderCheck.setProspectiveOnly(checks.isProspectiveOnly());
            }
            else { // prospective only defaults to false
                orderCheck.setProspectiveOnly(false);
            }

            orderCheck.setDrugDrugCheck(checks.isSetDrugDrugCheck());
            orderCheck.setDrugTherapyCheck(checks.isSetDrugTherapyCheck());

            if (checks.isSetDrugTherapyCheck() && checks.getDrugTherapyCheck().isSetUseDuplicateAllowance()) {
                orderCheck.setDuplicateAllowance(checks.getDrugTherapyCheck().isUseDuplicateAllowance());
            }
            else { // default use of duplicate allowance to true
                orderCheck.setDuplicateAllowance(true);
            }

            orderCheck.setDrugDoseCheck(checks.isSetDrugDoseCheck());
            orderCheck.setDrugsToScreen(new ArrayList<DrugCheckVo>(0));

            Collection<DrugCheckVo> prospectives;

            if (request.getBody().getDrugCheck().isSetProspectiveDrugs()) {
                prospectives = toDrugsToScreen(request.getBody().getDrugCheck().getProspectiveDrugs().getDrug(), true);
            }
            else {
                prospectives = Collections.emptyList();
            }

            orderCheck.getDrugsToScreen().addAll(prospectives);

            // if the check is for prospective drugs only, there must be at least one prospective drug
            if (orderCheck.isProspectiveOnly() && prospectives.isEmpty()) {
                throw new InterfaceValidationException(InterfaceValidationException.PROSPECTIVE_DRUGS_REQUIRED);
            }

            if (request.getBody().getDrugCheck().isSetMedicationProfile()) {
                orderCheck.getDrugsToScreen().addAll(
                    toDrugsToScreen(request.getBody().getDrugCheck().getMedicationProfile().getDrug(), false));
            }

            if (orderCheck.isDrugDoseCheck()) {
                addDemographicsData(checks.getDrugDoseCheck(), orderCheck);
            }
        }

        return orderCheck;
    }

    /**
     * All dose checks are completed on prospective drugs. Add the demographics information to the ORderCheckVo for the drugs
     * in the DrugDoseCheck type.
     *
     * @param drugDoseCheck DrugDoseCheckType XML object with dosing information
     * @param orderCheck OrderCheckVo to add demographics
     */
    private static void addDemographicsData(DrugDoseCheck drugDoseCheck, OrderCheckVo orderCheck) {
        orderCheck.setAgeInDays(drugDoseCheck.getDemographics().getAgeInDays());
        orderCheck.setWeightInKg(drugDoseCheck.getDemographics().getWeightInKG());
        orderCheck.setBodySurfaceAreaInSqM(drugDoseCheck.getDemographics().getBodySurfaceAreaInSqM());
    }

    /**
     * Convert a List of DrugType XML objects into a Collection of DrugCheckVo
     *
     * @param xmlDrugs List of DrugType XML objects
     * @param prospective true if the drugs in this list are prospective
     * @return Collection of DrugCheckVo
     */
    private static Collection<DrugCheckVo> toDrugsToScreen(List<Drug> xmlDrugs, boolean prospective) {
        Collection<DrugCheckVo> drugsToScreen = new ArrayList<DrugCheckVo>(xmlDrugs.size());

        for (Drug drugType : xmlDrugs) {
            drugsToScreen.add(toDrugCheckVo(drugType, prospective));
        }

        return drugsToScreen;
    }

    /**
     * Convert the DrugType into a DrugCheckVo
     *
     * @param drugType Drug XML object
     * @param prospective boolean true if this drug is prospective
     * @return DrugCheckVo
     */
    private static DrugCheckVo toDrugCheckVo(Drug drugType, boolean prospective) {
        DrugCheckVo drug = new DrugCheckVo();

        drug.setProspective(prospective);
        drug.setGcnSeqNo(String.valueOf(drugType.getGcnSeqNo()));

        if (drugType.isSetIen()) {
            drug.setIen(String.valueOf(drugType.getIen()));
        }

        if (drugType.isSetOrderNumber()) {
            drug.setOrderNumber(drugType.getOrderNumber());
        }

        if (drugType.isSetVuid()) {
            drug.setVuid(String.valueOf(drugType.getVuid()));
        }

        if (drugType.isSetDrugName()) {
            drug.setDrugName(drugType.getDrugName());
        }

        if (drugType.isSetDoseInformation()) {
            drug.setDoseCheck(true);

            DoseInformation doseInformation = drugType.getDoseInformation();
            drug.setDoseRate(doseInformation.getDoseRate().value());
            drug.setDoseRoute(doseInformation.getRoute().value());
            drug.setDoseType(doseInformation.getDoseType().value());
            drug.setDoseUnit(doseInformation.getDoseUnit().value());
            drug.setDuration(doseInformation.getDuration().longValue());
            drug.setDurationRate(doseInformation.getDurationRate().value());
            drug.setFrequency(doseInformation.getFrequency());
            drug.setSingleDoseAmount(doseInformation.getDoseAmount());
        }

        return drug;
    }

    /**
     * Convert the XML HeaderType into an OrderCheckHeaderVo
     *
     * @param header XML Header
     * @return OrderCheckHeaderVo
     */
    private static OrderCheckHeaderVo toHeader(Header header) {
        OrderCheckHeaderVo orderCheckHeaderVo = new OrderCheckHeaderVo();
        orderCheckHeaderVo.setDuz(header.getMUser().getDuz());
        orderCheckHeaderVo.setIp(header.getMServer().getIp());
        orderCheckHeaderVo.setJobNumber(header.getMUser().getJobNumber());
        orderCheckHeaderVo.setNamespace(header.getMServer().getNamespace());
        orderCheckHeaderVo.setServerName(header.getMServer().getServerName());
        orderCheckHeaderVo.setStationNumber(header.getMServer().getStationNumber());
        orderCheckHeaderVo.setTime(header.getTime().getValue());
        orderCheckHeaderVo.setUci(header.getMServer().getUci());
        orderCheckHeaderVo.setUserName(header.getMUser().getUserName());

        if (header.isSetPingOnly()) {
            orderCheckHeaderVo.setPingOnly(header.isPingOnly());
        }
        else {
            orderCheckHeaderVo.setPingOnly(false);
        }

        return orderCheckHeaderVo;
    }

    /**
     * Cannot instantiate class
     */
    private RequestConverter() {
        super();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO;
using System.ComponentModel;
using System.Globalization;

using FM4CC.FaultModels;
using FM4CC.ExecutionEngine;
using FM4CC.Environment;
using FM4CC.Util.Heatmap;
using FM4CC.TestCase;

namespace FM4CC.FaultModels.AllowedOscillation
{
    public class AllowedOscillationFaultModel : FaultModel
    {
        private bool setupDone;
        private const string prefix = "CT_";
        private const string shortName = "AllowedOscillationFaultModel";
        private const string name = "Allowed Oscillation";
        private const string description = "A common requirement for a controller is that when the difference between actual and desired value is less than a preset value the controller should take no action. This usually appears when the controlled system is known to have small oscillations upon reaching and stabilizing at the desired value. Given a controller-plant model and a desired value Desired, the algorithm computes four test cases, two below the limits of the allowed oscillation boundaries and two above the limits. To simulate starting from any initial arbitrary value, the function Desired(t) is defined in a similar way to the step fault model.";
        private string scriptsPath;

        #region Fault Model Implementation

        public AllowedOscillationFaultModel(ExecutionEnvironment executionEngine, string scriptsPath)
        {
            setupDone = false;
            this.scriptsPath = scriptsPath;
            this.ExecutionEngine = executionEngine;
            this.FaultModelConfiguration = new AllowedOscillationFaultModelConfiguration();
            this.SearchSpaceExplorationWorker = new SearchSpaceExplorationWorker();
            this.TestRunWorker = new TestRunWorker();
        }

        public AllowedOscillationFaultModel(ExecutionEnvironment executionEngine, FaultModelConfiguration configuration, string scriptsPath)
        {
            setupDone = false;
            this.scriptsPath = scriptsPath;
            this.ExecutionEngine = executionEngine;
            this.FaultModelConfiguration = (AllowedOscillationFaultModelConfiguration)configuration;
            this.SearchSpaceExplorationWorker = new SearchSpaceExplorationWorker();
            this.TestRunWorker = new TestRunWorker();
        }

        public override void SetUpEnvironment()
        {
            if (!setupDone)
            {
                // Get hold of the execution engine if not already
                ExecutionEngine.AcquireProcess();

                // Clear the workspace
                ExecutionEngine.ExecuteCommand("clear all;");
                ExecutionEngine.ExecuteCommand("pctRunOnAll clear all;");

                ExecutionEngine.PutVariable(prefix + "AccelerationDisabled", false);
                ExecutionEngine.PutVariable(prefix + "ScriptsPath", scriptsPath);

                string modelFile = ExecutionInstance.GetValue("SUTPath");
                string modelPath = modelFile.Substring(0, modelFile.LastIndexOf('\\'));

                ExecutionEngine.PutVariable(prefix + "ModelFile", modelFile);
                ExecutionEngine.PutVariable(prefix + "ModelPath", modelPath);
                ExecutionEngine.PutVariable(prefix + "ModelConfigurationFile", ExecutionInstance.GetValue("SUTSettingsPath"));
                ExecutionEngine.PutVariable(prefix + "ModelSimulationTime", SimulationSettings.ModelSimulationTime);

                string tempPath = modelPath + "\\ControllerTesterResults";
                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }
                ExecutionEngine.PutVariable(prefix + "TempPath", tempPath);
                ExecutionEngine.PutVariable(prefix + "UserTempPath", System.IO.Path.GetTempPath());
                // Add primitive parameters directly to the execution engine
                Dictionary<string, object>.Enumerator primitiveEnumerator = FaultModelConfiguration.GetParametersEnumerator();

                while (primitiveEnumerator.MoveNext())
                {
                    KeyValuePair<string, object> kvPair = primitiveEnumerator.Current;
                    ExecutionEngine.PutVariable(prefix + kvPair.Key, kvPair.Value);
                }

                ExecutionEngine.PutVariable(prefix + "DesiredValueRangeStart", Convert.ToDouble(this.SimulationSettings.DesiredVariable.FromValue));
                ExecutionEngine.PutVariable(prefix + "DesiredValueRangeEnd", Convert.ToDouble(this.SimulationSettings.DesiredVariable.ToValue));
                ExecutionEngine.PutVariable(prefix + "DesiredVariableName", this.SimulationSettings.DesiredVariable.Name);

                ExecutionEngine.PutVariable(prefix + "ActualValueRangeStart", Convert.ToDouble(this.SimulationSettings.ActualVariable.FromValue));
                ExecutionEngine.PutVariable(prefix + "ActualValueRangeEnd", Convert.ToDouble(this.SimulationSettings.ActualVariable.ToValue));
                ExecutionEngine.PutVariable(prefix + "ActualVariableName", this.SimulationSettings.ActualVariable.Name);

                ExecutionEngine.PutVariable(prefix + "DisturbanceAmplitude", Convert.ToDouble(this.SimulationSettings.DisturbanceVariable.ToValue));
                ExecutionEngine.PutVariable(prefix + "DisturbanceVariableName", this.SimulationSettings.DisturbanceVariable.Name);

                ExecutionEngine.PutVariable(prefix + "AllowedOscillationPercentage", (double)this.FaultModelConfiguration.GetValue("AllowedOscillationPercentage"));
                ExecutionEngine.PutVariable(prefix + "DesiredValueStepSize", (double)this.FaultModelConfiguration.GetValue("DesiredValueStepSize"));
                ExecutionEngine.PutVariable(prefix + "TimeStable", this.SimulationSettings.StableStartTime);
                ExecutionEngine.PutVariable(prefix + "GenerateSineWaveTestCases", FaultModelConfiguration.GetValue("GenerateSineWaveTestCases"));

                // add scripts to path
                ExecutionEngine.ExecuteCommand("addpath(strcat(CT_ScriptsPath, '\\ModelExecution'));");
                ExecutionEngine.ExecuteCommand("addpath(strcat(CT_ScriptsPath, '\\AllowedOscillation'));");

                ExecutionEngine.ChangeWorkingFolder(tempPath);

                setupDone = true;
            }
            else throw new FM4CCException("An execution instance is already under way. Please tear down the environment first!");
        }

        public override void TearDownEnvironment(bool relinquishExectionEngineControl = true)
        {
            // Clear the workspace
//            ExecutionEngine.ExecuteCommand("clear all;");
            if (relinquishExectionEngineControl)
            {
                ExecutionEngine.RelinquishProcess();
            }
            setupDone = false;
        }

        public override IList<string> GetSteps()
        {
            return new List<string>() { "SearchSpaceExploration" };
        }

        public override TimeSpan GetEstimatedDuration(string step)
        {
            switch(step)
            {
                case "SearchSpaceExploration":
                    return GetSearchSpaceExplorationEstimatedRunningTime();
                default:
                    return new TimeSpan(1000);
            }

        }

        public override object Run(string step, params object[] args)
        {
            switch(step)
            {
                case "TestRun":
                    return ExecuteSimulationRun();
                case "SearchSpaceExploration":
                    return ExecuteSearchSpaceExploration();
                default:
                    throw new FM4CCException("No such step exists");
            }
        }

        public override bool Run(FaultModelTesterTestCase testCase)
        {
            IDictionary<string, object> input = testCase.Input;
            SetTestRunParameters((double)input["Desired"], (int)input["TestCaseType"]);
            return (bool)(((List<object>)ExecuteSimulationRun())[1]);
        }

        public override string Name { get { return name; } }
        public override string Description { get { return description; } }
        public override string ToString()
        {
            return shortName;
        }

        #endregion

        #region Allowed Oscillation Fault Model

        public BackgroundWorker SearchSpaceExplorationWorker { get; protected set; }
        public BackgroundWorker TestRunWorker { get; protected set; }

        #endregion

        #region Simulation

        private double desired;
        private int testCase;

        /// <summary>
        /// Sets a single desired value for which four test cases will be generated, attempting to void requirements
        /// </summary>
        /// <param name="desired">The desired value for which four test cases will be computed</param>
        internal void SetTestRunParameters(double desired, int testCase = 1)
        {
            this.desired = desired;
            this.testCase = testCase;
        }

        private object ExecuteSimulationRun()
        {
            if (setupDone)
            {
                ExecutionEngine.PutVariable(prefix + "DesiredValue", desired);
                ExecutionEngine.PutVariable(prefix + "SelectedTestCase", testCase);

                string message = ExecutionEngine.ExecuteCommand("TestRun_AllowedOscillation");

                string searchPattern = "passed=(0|1)";
                Regex regex = new Regex(searchPattern);
                Match match = regex.Match(message);
                bool result = false;

                if (match.Groups.Count == 2)
                {
                    // the system is run using a step desired value signal
                    // this results in the simulation time being double the normally set simulation time
                    // therefore the default duration is half
                    int val = Int32.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture) ;
                    result = Convert.ToBoolean(val);
                }

                return new List<object>() {message, result};
            }
            else throw new InvalidOperationException("Setup not performed");
        }

        private object ExecuteSearchSpaceExploration()
        {
            if (setupDone)
            {
                string message = ExecutionEngine.ExecuteCommand("SearchSpaceExploration_AllowedOscillation");

                return message;
            }
            else throw new InvalidOperationException("Setup not performed");
        }

        #endregion

         private TimeSpan GetSearchSpaceExplorationEstimatedRunningTime()
        {
            // get number of cores, since MATLAB's Parallel Computing Toolbox typically starts the same amount of workers
            int coreCount = 0;
            foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
            {
                coreCount += int.Parse(item["NumberOfCores"].ToString());
            }

            int testCases = (bool)FaultModelConfiguration.GetValue("GenerateSineWaveTestCases") == true ? 6 : 4;
            double num = 2 * SimulationSettings.ModelRunningTime * (Convert.ToDouble(this.SimulationSettings.DesiredVariable.ToValue - this.SimulationSettings.DesiredVariable.FromValue) / (double)this.FaultModelConfiguration.GetValue("DesiredValueStepSize")) * (testCases / (double)coreCount);
            TimeSpan result = new TimeSpan(0, 0, (int)(num));
            return result;
        }
    }
}


text:
ALTER TABLE pipelines ADD COLUMN counter BIGINT;
CREATE INDEX idx_pipelines_name_counter ON pipelines( name, counter );

--//@UNDO

DROP INDEX idx_pipelines_name_counter;
ALTER TABLE pipelines DROP COLUMN counter;


text:
'use strict';

var Event = require('../../models/Event');
var logger = require('../util/logger')(__filename);

module.exports = function (req, res, next) {
    if (!req.user) return res.send(403);

    var eventId = req.params.id;
    if (!eventId) return res.send(404);

    Event.findOne({_id: eventId, author: req.user._id}, function (err, event) {
        if (err) return next(err);
        if (!event) return res.send(404);

        res.render('event/edit', {
                title: 'Редактировать событие',
                event: event
            }
        );
    });
};


text:
libsv - Public domain semantic versioning in c

[![Build Status](https://travis-ci.org/uael/sv.svg?branch=master)](https://travis-ci.org/uael/sv)
[![Build status](https://ci.appveyor.com/api/projects/status/7li44f9agk0u4dxc?svg=true)](https://ci.appveyor.com/project/uael/sv)
[![codecov](https://codecov.io/gh/uael/sv/branch/master/graph/badge.svg)](https://codecov.io/gh/uael/sv)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/b21f7acd11a9437c8fe79b0600dc205e)](https://www.codacy.com/app/lucas.abel/sv?utm_source=github.com&utm_medium=referral&utm_content=uael/sv&utm_campaign=Badge_Grade)

# Topics
- [Introduction](#introduction)
- [License](#license)
- [Install](#install)
  - [xmake](#xmake)
  - [cmake](#cmake)
  - [autotools](#autotools)
- [Usage](#usage)
- [Credits](#credits)
- [Bugs, vulnerabilities and contributions](#bugs-vulnerabilities-and-contributions)
- [Resources](#resources)
- [Badges and static analysis](#badges-and-static-analysis)
  - [Travis CI](#travis-ci)
  - [Clang's Static Analyzer](#clangs-static-analyzer)

## Introduction

This is free and unencumbered software released into the public domain.
This  package  installs  a  C  language  library  implementing  semantic versioning for the C language.

## License

See the [UNLICENSE](https://github.com/uael/sv/blob/master/UNLICENSE) file.

## Install

### xmake

[Install xmake build system (A cross-platform build utility based on Lua)](http://xmake.io)

```bash
$ xmake
$ xmake check
$ xmake install
```

### cmake

```bash
$ mkdir build && cd build
$ cmake ..
$ make
$ make test
$ make install
```

### autotools

To install from a proper release tarball, do this:
```bash
$ cd libsv-3.1
$ mkdir build
$ cd build
$ ../configure
$ make
$ make check
$ make install
```
to inspect the available configuration options:
```bash
$ ../configure --help
```
The Makefile is designed to allow parallel builds, so we can do:
```bash
$ make -j4 all && make -j4 check
```
which,  on  a  4-core  CPU,   should  speed  up  building  and  checking significantly.
The  Makefile supports  the  DESTDIR environment  variable to  install files in a temporary location, example: to see what will happen:
```bash
$ make -n install DESTDIR=/tmp/libsv
```
to really do it:
```bash
$ make install DESTDIR=/tmp/libsv
```
After the installation it is  possible to verify the installed library against the test suite with:
```bash
$ make installcheck
```
From  a repository  checkout or  snapshot  (the ones  from the  Github site): we  must install the  GNU Autotools (GNU Automake,  GNU Autoconf, GNU Libtool),  then we must first  run the script "autogen.sh"  from the top source directory, to generate the needed files:
```bash
$ cd libsv
$ sh autogen.sh
```
notice  that  "autogen.sh"  will   run  the  programs  "autoreconf"  and "libtoolize"; the  latter is  selected through the  environment variable "LIBTOOLIZE",  whose  value  can  be  customised;  for  example  to  run "glibtoolize" rather than "libtoolize" we do:
```bash
$ LIBTOOLIZE=glibtoolize sh autogen.sh
```
After this the  procedure is the same  as the one for  building from a proper release tarball, but we have to enable maintainer mode:
```bash
$ ../configure --enable-maintainer-mode [options]
$ make
$ make check
$ make install
```

## Usage

```c
...
semver_t semver = {0};

semver(&semver, "v1.2.3-alpha.1");

assert(1 == semver.major);
assert(2 == semver.minor);
assert(3 == semver.patch);
assert(0 == memcmp("alpha", semver.prerelease.raw, sizeof("alpha")-1));
assert(0 == memcmp("1", semver.prerelease.next->raw, sizeof("1")-1));
assert(true == semver_rmatch(semver, "1.2.1 || >=1.2.3-alpha <1.2.5"));

semver_dtor(&semver);
...
```

### Versions

A "version" is described by the `v2.0.0` specification found at
<http://semver.org/>.

A leading `"v"` character is stripped off and ignored.

### Ranges

A `version range` is a set of `comparators` which specify versions
that satisfy the range.

A `comparator` is composed of an `operator` and a `version`.  The set
of primitive `operators` is:

* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal.  If no operator is specified, then equality is assumed,
  so this operator is optional, but MAY be included.

For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`.

Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.

A range is composed of one or more comparator sets, joined by `||`.  A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.

For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.

The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.

#### Prerelease Tags

If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.

For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules.  The version
range only accepts prerelease tags on the `1.2.3` version.  The
version `3.4.5` *would* satisfy the range, because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.

The purpose for this behavior is twofold.  First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range matching
semantics.

Second, a user who has opted into using a prerelease version has
clearly indicated the intent to use *that specific* set of
alpha/beta/rc versions.  By including a prerelease tag in the range,
the user is indicating that they are aware of the risk.  However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.

#### Advanced Range Syntax

Advanced range syntax desugars to primitive comparators in
deterministic ways.

Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.

##### Hyphen Ranges `X.Y.Z - A.B.C`

Specifies an inclusive set.

* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`

If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.

* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`

If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.

* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0`

##### X-Ranges `1.2.x` `1.X` `1.2.*` `*`

Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.

* `*` := `>=0.0.0` (Any version satisfies)
* `1.x` := `>=1.0.0 <2.0.0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions)

A partial version range is treated as an X-Range, so the special
character is in fact optional.

* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0`

##### Tilde Ranges `~1.2.3` `~1.2` `~1`

Allows patch-level changes if a minor version is specified on the
comparator.  Allows minor-level changes if not.

* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in
  the `1.2.3` version will be allowed, if they are greater than or
  equal to `beta.2`.  So, `1.2.3-beta.4` would be allowed, but
  `1.2.4-beta.2` would not, because it is a prerelease of a
  different `[major, minor, patch]` tuple.

#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`

Allows changes that do not modify the left-most non-zero digit in the
`[major, minor, patch]` tuple.  In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.

Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.

Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`.  It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.

* `^1.2.3` := `>=1.2.3 <2.0.0`
* `^0.2.3` := `>=0.2.3 <0.3.0`
* `^0.0.3` := `>=0.0.3 <0.0.4`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in
  the `1.2.3` version will be allowed, if they are greater than or
  equal to `beta.2`.  So, `1.2.3-beta.4` would be allowed, but
  `1.2.4-beta.2` would not, because it is a prerelease of a
  different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4`  Note that prereleases in the
  `0.0.3` version *only* will be allowed, if they are greater than or
  equal to `beta`.  So, `0.0.3-pr.2` would be allowed.

When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.

* `^1.2.x` := `>=1.2.0 <2.0.0`
* `^0.0.x` := `>=0.0.0 <0.1.0`
* `^0.0` := `>=0.0.0 <0.1.0`

A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.

* `^1.x` := `>=1.0.0 <2.0.0`
* `^0.x` := `>=0.0.0 <1.0.0`

## Credits

The stuff was written by Lucas Abel <https://github.com/uael> and contributors
- Marco Maggi <https://github.com/marcomaggi>

## Bugs, vulnerabilities and contributions

Bug  and vulnerability  reports are  appreciated, all  the vulnerability reports  are  public; register  them  using  the  Issue Tracker  at  the project's Github  site.  For  contributions and  patches please  use the Pull Requests feature at the project's Github site.

Reports about the original code must be registered at:
<https://github.com/uael/sv/issues>

## Resources

Development of the original projects takes place at:
<https://github.com/uael/sv/>

the GNU Project software can be found here:
<https://www.gnu.org/>

## Badges and static analysis

### Travis CI

Travis CI is  a hosted, distributed continuous  integration service used to build and test software projects  hosted at GitHub.  We can find this project's dashboards at:
<https://travis-ci.org/uael/sv>

Usage of this service is configured through the file ".travis.yml".

### Clang's Static Analyzer

The Clang Static Analyzer is a source code analysis tool that finds bugs in C, C++, and Objective-C programs.  It is distributed along with Clang and we can find it at:
<http://clang-analyzer.llvm.org/>

Usage of this service is implemented with make rules; see the relevant section in the file "Makefile.am".


text:
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.i18nextXHRBackend = factory());
}(this, (function () { 'use strict';

var arr = [];
var each = arr.forEach;
var slice = arr.slice;

function defaults(obj) {
  each.call(slice.call(arguments, 1), function (source) {
    if (source) {
      for (var prop in source) {
        if (obj[prop] === undefined) obj[prop] = source[prop];
      }
    }
  });
  return obj;
}

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

// https://gist.github.com/Xeoncross/7663273
function ajax(url, options, callback, data, cache) {
  // Must encode data
  if (data && (typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') {
    var y = '',
        e = encodeURIComponent;
    for (var m in data) {
      y += '&' + e(m) + '=' + e(data[m]);
    }
    data = y.slice(1) + (!cache ? '&_t=' + new Date() : '');
  }

  try {
    var x = new (XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
    x.open(data ? 'POST' : 'GET', url, 1);
    if (!options.crossDomain) {
      x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    }
    x.withCredentials = !!options.withCredentials;
    if (data) {
      x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    }
    var h = options.customHeaders;
    if (h) {
      for (var i in h) {
        x.setRequestHeader(i, h[i]);
      }
    }
    x.onreadystatechange = function () {
      x.readyState > 3 && callback && callback(x.responseText, x);
    };
    x.send(data);
  } catch (e) {
    console && console.log(e);
  }
}

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function getDefaults() {
  return {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
    addPath: 'locales/add/{{lng}}/{{ns}}',
    allowMultiLoading: false,
    parse: JSON.parse,
    crossDomain: false,
    ajax: ajax
  };
}

var Backend = function () {
  function Backend(services) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    _classCallCheck(this, Backend);

    this.init(services, options);

    this.type = 'backend';
  }

  _createClass(Backend, [{
    key: 'init',
    value: function init(services) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      this.services = services;
      this.options = defaults(options, this.options || {}, getDefaults());
    }
  }, {
    key: 'readMulti',
    value: function readMulti(languages, namespaces, callback) {
      var loadPath = this.options.loadPath;
      if (typeof this.options.loadPath === 'function') {
        loadPath = this.options.loadPath(languages, namespaces);
      }

      var url = this.services.interpolator.interpolate(loadPath, { lng: languages.join('+'), ns: namespaces.join('+') });

      this.loadUrl(url, callback);
    }
  }, {
    key: 'read',
    value: function read(language, namespace, callback) {
      var loadPath = this.options.loadPath;
      if (typeof this.options.loadPath === 'function') {
        loadPath = this.options.loadPath([language], [namespace]);
      }

      var url = this.services.interpolator.interpolate(loadPath, { lng: language, ns: namespace });

      this.loadUrl(url, callback);
    }
  }, {
    key: 'loadUrl',
    value: function loadUrl(url, callback) {
      var _this = this;

      this.options.ajax(url, this.options, function (data, xhr) {
        if (xhr.status >= 500 && xhr.status < 600) return callback('failed loading ' + url, true /* retry */);
        if (xhr.status >= 400 && xhr.status < 500) return callback('failed loading ' + url, false /* no retry */);

        var ret = void 0,
            err = void 0;
        try {
          ret = _this.options.parse(data, url);
        } catch (e) {
          err = 'failed parsing ' + url + ' to json';
        }
        if (err) return callback(err, false);
        callback(null, ret);
      });
    }
  }, {
    key: 'create',
    value: function create(languages, namespace, key, fallbackValue) {
      var _this2 = this;

      if (typeof languages === 'string') languages = [languages];

      var payload = {};
      payload[key] = fallbackValue || '';

      languages.forEach(function (lng) {
        var url = _this2.services.interpolator.interpolate(_this2.options.addPath, { lng: lng, ns: namespace });

        _this2.options.ajax(url, _this2.options, function (data, xhr) {
          //const statusCode = xhr.status.toString();
          // TODO: if statusCode === 4xx do log
        }, payload);
      });
    }
  }]);

  return Backend;
}();

Backend.type = 'backend';

return Backend;

})));


text:
import time
from openerp.report import report_sxw

class all_closed_cashbox_of_the_day(report_sxw.rml_parse):
    #TOFIX: sql injection problem: SQL Request must be pass from sql injection...
    def __init__(self, cr, uid, name, context):
        super(all_closed_cashbox_of_the_day, self).__init__(cr, uid, name, context=context)
        self.localcontext.update({
                'time': time,
                'get_data':self._get_data,
                'get_bal':self._get_bal,
                'get_lines':self._get_lines,
                'get_partner':self._get_partner,
                'get_net_total':self._get_net_total,
                'get_user':self._get_user,
                'get_sub_total':self._get_sub_total,
                'get_net_total_starting':self._get_net_total_starting,
        })

    def _get_user(self, line_ids):
        sql = "select name from res_users where id = %d"%(line_ids['create_uid'])
        self.cr.execute(sql)
        user = self.cr.fetchone()
        return user[0]

    def _get_data(self, user):
        data = {}
        sql = """ SELECT abs.journal_id,abs.id,abs.date,abs.closing_date,abs.name as statement,aj.name as journal,ap.name as period,ru.name as user,rc.name as company,
                       abs.state,abs.balance_end_real FROM account_bank_statement as abs
                       LEFT JOIN account_journal as aj ON aj.id = abs.journal_id
                       LEFT JOIN account_period as ap ON ap.id = abs.period_id
                       LEFT JOIN res_users as ru ON ru.id = abs.user_id
                       LEFT JOIN res_company as rc ON rc.id = abs.company_id
                       WHERE to_char(date_trunc('day',abs.date),'YYYY-MM-DD')::date  = current_date and abs.state IN ('confirm','open') and abs.user_id = %d"""%(user.id)
        self.cr.execute(sql)
        data = self.cr.dictfetchall()
        return data

    def _get_lines(self, statement):
        data = {}
        sql = """ select absl.* from account_bank_statement_line as absl, account_bank_statement as abs
                           where absl.statement_id = abs.id and abs.id = %d"""%(statement['id'])
        self.cr.execute(sql)
        data = self.cr.dictfetchall()
        return data

    def _get_bal(self, data):
        res = {}
        sql =""" select sum(pieces*number) as bal from account_cashbox_line where starting_id = %d """%(data['id'])
        self.cr.execute(sql)
        res = self.cr.dictfetchall()
        if res:
            return res[0]['bal']
        else:
            return 0

    def _get_sub_total(self, user, data, date):
        res={}
        self.cr.execute(""" select sum(absl.amount) from account_bank_statement as abs
                            LEFT JOIN account_bank_statement_line as absl ON abs.id = absl.statement_id
                            WHERE abs.journal_id = %d
                            and abs.state IN ('confirm','open')
                            and abs.date = '%s'
                            and abs.user_id = %d
                            """%(data,date,user.id))
        res = self.cr.fetchall()
        if res[0][0]:
            return res[0][0]
        else:
            return False

    def _get_partner(self, statement):
        res = {}
        if statement['pos_statement_id']:
            sql =""" select rp.name  from account_bank_statement_line as absl,res_partner as rp
                                            where absl.partner_id = rp.id
                                            and absl.pos_statement_id = %d"""%(statement['pos_statement_id'])
            self.cr.execute(sql)
            res = self.cr.dictfetchall() or {}
            return res and res[0]['name']
        else:
            return 0.00

    def _get_net_total_starting(self, user):
        lst = []
        res={}
        total_ending_bal = 0.0
        total_starting_bal = 0.0
        sql = """ SELECT abs.id,abs.balance_end_real as net_total FROM account_bank_statement as abs
                    WHERE to_char(date_trunc('day',abs.date),'YYYY-MM-DD')::date  = current_date
                    and abs.state IN ('confirm','open')
                    and abs.user_id = %d"""%(user.id)
        self.cr.execute(sql)
        res = self.cr.dictfetchall()
        for r in res:
            total_ending_bal += (r['net_total'] or 0.0)
            sql1 =""" select sum(pieces*number) as bal from account_cashbox_line where starting_id = %d"""%(r['id'])
            self.cr.execute(sql1)
            data = self.cr.dictfetchall()
            if data[0]['bal']:
                total_starting_bal += data[0]['bal']
        lst.append(total_ending_bal)
        lst.append(total_starting_bal)
        return lst

    def _get_net_total(self, user):
        res={}
        sql = """select sum(absl.amount) as net_total from account_bank_statement as abs
                    LEFT JOIN account_bank_statement_line as absl ON abs.id = absl.statement_id
                    where abs.state IN ('confirm','open') and abs.user_id = %d
                    and to_char(date_trunc('day',abs.date),'YYYY-MM-DD')::date  = current_date """%(user.id)

        self.cr.execute(sql)
        res = self.cr.dictfetchall()
        return res[0]['net_total'] or 0.0

report_sxw.report_sxw('report.all.closed.cashbox.of.the.day', 'account.bank.statement', 'addons/point_of_sale/report/all_closed_cashbox_of_the_day.rml', parser=all_closed_cashbox_of_the_day,header='internal')

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
<!DOCTYPE html>

<title>Matrix Admin</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/bootstrap-responsive.min.css" />
<link rel="stylesheet" href="css/matrix-style.css" />
<link rel="stylesheet" href="css/matrix-media.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet" />
<link href='http://fonts.useso.com/css?family=Open+Sans:400,700,800' rel='stylesheet' type='text/css'>

Matrix Admin

  Welcome User

 My Profile

 My Tasks

 Log Out

 Messages 5

 new message

 inbox

 outbox

 trash

 Settings

 Logout

  <input type="text" placeholder="Search here..."/>
  <button type="submit" class="tip-bottom" title="Search"></button>

  Widgets

 Dashboard

  Charts & graphs

  Widgets

 Tables

 Full width

  Forms 3

Basic Form

Form with Validation

Form with Wizard

 Buttons & icons

 Eelements

  Addons 5

Dashboard2

Gallery

Calendar

Invoice

Chat option

  Error 4

Error 403

Error 404

Error 405

Error 500

 Monthly Bandwidth Transfer

      77%

21419.94 / 14000 MB

 Disk Space Usage

      87%

604.44 / 4000 MB

  Home Widgets

Widgets

Recent Posts

Edit Publish Delete

                   By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM

This is a much longer one that will go on for a few lines.It has multiple paragraphs and is full of waffle to pad out the comment.

Edit Publish Delete

                   By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM

This is a much longer one that will go on for a few lines.It has multiple paragraphs and is full of waffle to pad out the comment.

Edit Publish Delete

                   By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM

This is a much longer one that will go on for a few lines.Itaffle to pad out the comment.

                <button class="btn btn-warning btn-mini">View All</button>

Accordion option1

 This is opened by default

Accordion closed

 Another is open

Accordion closed

 Another is open

Toggle, Open by default

 This box is opened by default

Toggle, closed by default

 This box is now open

Toggle, closed by default

 This box is now open

News updates

Lorem ipsum dolor sit amet, consectetur adipiscing elit. dolor sit amet, consectetur adipiscing eli

20jan

   Congratulation Maruti, Happy Birthday  many many happy returns of the day  11jan

   Maruti is a Responsive Admin theme But already everything was solved. It will ...  07Jan

   Envato approved Maruti Admin template i am very happy to approved by TF  05jan

   I am alwayse here if you have any question we glad that you choose our template  01jan

To Do List

                  Description
                  Status
                  Opts

                   Making The New Suit
                  in progress

                   Luanch My New Site
                  pending

                   Maruti Excellant Theme
                  done

Tab1

Tab2

Tab3

And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.

 waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.

full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.

Recent Activity

  ThemeforestApproved My college theme 1 user 2 hours ago

  My College is PSD Template  Theme Psd Theme 2months ago

  Lorem ipsum doler set adagagg 2 days ago

  ITs my First Admin so veryexited 2 days ago

  Admin bans 3 users week ago

To Do list

 Luanch This theme on Themeforest Nirav Today

 Manage Pending Orders Alex Today

 MAke your desk clean Admin Tomorrow

 Today we celebrate the great looking theme Admin 08.03.2013

 Manage all the orders Mark 12.03.2013

To Do list

  81% Clicks 567

  72% Uniquie Clicks 507

  53% Impressions 457

  3% Online Users 8

Browesr statistics

                  Browser
                  Visits

                  Chrome
                  8850

                  Firefox
                  5670

                  Internet Explorer
                  4130

                  Opera
                  1574

                  Safari
                  1044

Website statistics

                  Site
                  Visits

                  Themeforest.com
                  12444

                  Themedesigner.in
                  10455

                  Themedesigner.in
                  8455

                  Themedesigner.in
                  4456

                  Themedesigner.in
                  2210

Visited Pages

                  Page
                  Visits

                  Freebies
                  8550

                  Blog
                  7550

                  Work
                  5247

                  site template
                  4880

                  All categories
                  4801

 2013 © Matrix Admin. More Templates 源码之家


text:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "asylo/platform/core/enclave_manager.h"

namespace asylo {
namespace {

// A fake resource object for testing.
struct TestResource {
  // Initializes the resource with a pointer to write if and when the object is
  // destroyed.
  explicit TestResource(bool *alive) : alive(alive) { *alive = true; }
  ~TestResource() { *alive = false; }
  std::string value;
  bool *alive;
};

TEST(EnclaveResourcesTest, ResourceLifeCycle) {
  const SharedName managed_name(kUnspecifiedName, "managed resource");
  const SharedName unmanaged_name(kUnspecifiedName, "unmanaged resource");

  EnclaveManager::Configure(EnclaveManagerOptions());
  SharedResourceManager *resources =
      EnclaveManager::Instance().value()->shared_resources();

  // Installs a resource with a pointer to a value to set in its destructor.
  bool is_managed_resource_alive;
  bool is_unmanaged_resource_alive;
  TestResource unmanaged_resource(&is_unmanaged_resource_alive);
  auto *managed_resource = new TestResource(&is_managed_resource_alive);
  managed_resource->value = "managed resource";
  unmanaged_resource.value = "unmanaged resource";

  // Register a managed and unmanaged resource.
  resources->RegisterManagedResource(managed_name, managed_resource);
  resources->RegisterUnmanagedResource(unmanaged_name, &unmanaged_resource);

  // Ensure neither object has been destroyed.
  EXPECT_TRUE(is_managed_resource_alive);
  EXPECT_TRUE(is_unmanaged_resource_alive);

  // Ensure we can't register the same name twice.
  EXPECT_FALSE(
      resources->RegisterManagedResource(unmanaged_name, &unmanaged_resource)
          .ok());

  // Run up the resources reference counts.
  for (int i = 0; i < 100; i++) {
    TestResource *resource =
        resources->AcquireResource<TestResource>(unmanaged_name);
    EXPECT_EQ(resource->value, "unmanaged resource");
    resource = resources->AcquireResource<TestResource>(managed_name);
    EXPECT_EQ(resource->value, "managed resource");
  }

  // Ensure that we can release the resource as many times as we acquired it.
  for (int i = 0; i < 100; i++) {
    EXPECT_TRUE(resources->ReleaseResource(managed_name));
    EXPECT_TRUE(is_managed_resource_alive);
    EXPECT_TRUE(resources->ReleaseResource(unmanaged_name));
    EXPECT_TRUE(is_unmanaged_resource_alive);
  }

  // Expect that the managed resource has been deleted after its reference count
  // reaches zero.
  resources->ReleaseResource(managed_name);
  EXPECT_FALSE(is_managed_resource_alive);

  // Expect that the unmanaged resource is still alive after its reference count
  // reaches zero.
  resources->ReleaseResource(unmanaged_name);
  EXPECT_TRUE(is_unmanaged_resource_alive);

  // Expect that releasing a deleted resource fails.
  EXPECT_FALSE(resources->ReleaseResource(managed_name));
  EXPECT_FALSE(resources->ReleaseResource(unmanaged_name));

  // Expect that we can reuse a resource name after it's been destroyed.
  EXPECT_TRUE(
      resources->RegisterManagedResource(unmanaged_name, &unmanaged_resource)
          .ok());
}

TEST(EnclaveResourcesTest, CustomDeleter) {
  EnclaveManager::Configure(EnclaveManagerOptions());
  SharedResourceManager *resources =
      EnclaveManager::Instance().value()->shared_resources();

  // A custom cleanup policy to install for a resource.
  struct CustomCleanupStrategy {
    void operator()(std::string *resource) {
      *resource = "custom cleanup strategy was invoked";
    }
  };

  const SharedName name(kUnspecifiedName, "resource name");
  std::string a_string_resource = "I'm not dead!";
  resources->RegisterManagedResource<std::string, CustomCleanupStrategy>(
      name, &a_string_resource);
  resources->ReleaseResource(name);
  EXPECT_EQ(a_string_resource, "custom cleanup strategy was invoked");
}

}  // namespace
}  // namespace asylo


text:
require 'google/apis/dialogflow_v2beta1/service.rb'
require 'google/apis/dialogflow_v2beta1/classes.rb'
require 'google/apis/dialogflow_v2beta1/representations.rb'
require 'google/apis/dialogflow_v2beta1/gem_version.rb'

module Google
  module Apis
    # Dialogflow API
    #
    # Builds conversational interfaces (for example, chatbots, and voice-powered
    # apps and devices).
    #
    # @see https://cloud.google.com/dialogflow/
    module DialogflowV2beta1
      # Version of the Dialogflow API this client connects to.
      # This is NOT the gem version.
      VERSION = 'V2beta1'

      # See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
      AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'

      # View, manage and query your Dialogflow agents
      AUTH_DIALOGFLOW = 'https://www.googleapis.com/auth/dialogflow'
    end
  end
end


text:
package com.diablominer.DiabloMiner.DeviceState;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicLong;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.PointerBuffer;
import org.lwjgl.opencl.CL10;
import org.lwjgl.opencl.CL12;
import org.lwjgl.opencl.CLCommandQueue;
import org.lwjgl.opencl.CLContext;
import org.lwjgl.opencl.CLContextCallback;
import org.lwjgl.opencl.CLDevice;
import org.lwjgl.opencl.CLKernel;
import org.lwjgl.opencl.CLMem;
import org.lwjgl.opencl.CLPlatform;
import org.lwjgl.opencl.CLProgram;

import com.diablominer.DiabloMiner.DiabloMiner;
import com.diablominer.DiabloMiner.DiabloMinerFatalException;
import com.diablominer.DiabloMiner.NetworkState.WorkState;

public class GPUDeviceState extends DeviceState {
	final static int OUTPUTS = 16;

	final PlatformVersion platform_version;
	final CLDevice device;
	final CLContext context;
	final CLKernel kernel;

	AtomicLong workSize = new AtomicLong(0);
	long workSizeBase;
	boolean hwcheck;

	final PointerBuffer localWorkSize = BufferUtils.createPointerBuffer(1);

	final ExecutionState executions[];

	AtomicLong runs = new AtomicLong(0);
	long lastRuns = 0;
	long startTime = 0;
	long lastTime = 0;

	GPUHardwareType hardwareType;

	GPUDeviceState(GPUHardwareType hardwareType, String deviceName, CLPlatform platform, PlatformVersion platform_version, CLDevice device) throws DiabloMinerFatalException {
		this.platform_version = platform_version;
		this.hardwareType = hardwareType;
		this.diabloMiner = hardwareType.getDiabloMiner();
		this.deviceName = deviceName;

		this.resetNetworkState = DiabloMiner.now();

		this.executions = new ExecutionState[GPUHardwareType.EXECUTION_TOTAL];

		boolean hasBitAlign;
		boolean hasBFI_INT = false;
		CLProgram program;

		this.device = device;

		PointerBuffer properties = BufferUtils.createPointerBuffer(3);
		properties.put(CL10.CL_CONTEXT_PLATFORM).put(platform.getPointer()).put(0).flip();
		int err = 0;

		int deviceCU = device.getInfoInt(CL10.CL_DEVICE_MAX_COMPUTE_UNITS);
		long deviceWorkSize;

		int forceWorkSize = diabloMiner.getGPUForceWorkSize();

		if(forceWorkSize > 0)
			deviceWorkSize = forceWorkSize;
		else if(LWJGLUtil.getPlatform() != LWJGLUtil.PLATFORM_MACOSX)
			deviceWorkSize = device.getInfoSize(CL10.CL_DEVICE_MAX_WORK_GROUP_SIZE);
		else
			deviceWorkSize = 64;

		context = CL10.clCreateContext(properties, device, new CLContextCallback() {
			protected void handleMessage(String errinfo, ByteBuffer private_info) {
				diabloMiner.error(errinfo);
			}
		}, null);

		ByteBuffer extb = BufferUtils.createByteBuffer(1024);
		CL10.clGetDeviceInfo(device, CL10.CL_DEVICE_EXTENSIONS, extb, null);
		byte[] exta = new byte[1024];
		extb.get(exta);

		if(new String(exta).contains("cl_amd_media_ops"))
			hasBitAlign = true;
		else
			hasBitAlign = false;

		if(hasBitAlign) {
			if(deviceName.contains("Cedar") || deviceName.contains("Redwood") || deviceName.contains("Juniper") || deviceName.contains("Cypress") || deviceName.contains("Hemlock") || deviceName.contains("Caicos") || deviceName.contains("Turks") || deviceName.contains("Barts") || deviceName.contains("Cayman") || deviceName.contains("Antilles") || deviceName.contains("Palm") || deviceName.contains("Sumo") || deviceName.contains("Wrestler") || deviceName.contains("WinterPark") || deviceName.contains("BeaverCreek"))
				hasBFI_INT = true;
		}

		// String compileOptions =
		// "-save-temps="+(device.getInfoString(CL10.CL_DEVICE_NAME).trim());
		String compileOptions = "";

		compileOptions += " -D WORKSIZE=" + deviceWorkSize;

		if(hasBitAlign)
			compileOptions += " -D BITALIGN";

		if(hasBFI_INT)
			compileOptions += " -D BFIINT";

		program = CL10.clCreateProgramWithSource(context, hardwareType.getSource(), null);

		err = CL10.clBuildProgram(program, device, compileOptions, null);
		if(err != CL10.CL_SUCCESS) {
			ByteBuffer logBuffer = BufferUtils.createByteBuffer(1024);
			byte[] log = new byte[1024];

			CL10.clGetProgramBuildInfo(program, device, CL10.CL_PROGRAM_BUILD_LOG, logBuffer, null);

			logBuffer.get(log);

			System.out.println(new String(log));

			throw new DiabloMinerFatalException(diabloMiner, "Failed to build program on " + deviceName);
		}

		if(hasBFI_INT) {
			diabloMiner.info("BFI_INT patching enabled, disabling hardware check errors");
			hwcheck = false;

			int binarySize = (int) program.getInfoSizeArray(CL10.CL_PROGRAM_BINARY_SIZES)[0];

			ByteBuffer binary = BufferUtils.createByteBuffer(binarySize);
			program.getInfoBinaries(binary);

			for(int pos = 0; pos < binarySize - 4; pos++) {
				if((long) (0xFFFFFFFF & binary.getInt(pos)) == 0x464C457FL && (long) (0xFFFFFFFF & binary.getInt(pos + 4)) == 0x64010101L) {
					boolean firstText = true;

					int offset = binary.getInt(pos + 32);
					short entrySize = binary.getShort(pos + 46);
					short entryCount = binary.getShort(pos + 48);
					short index = binary.getShort(pos + 50);

					int header = pos + offset;

					int nameTableOffset = binary.getInt(header + index * entrySize + 16);
					int size = binary.getInt(header + index * entrySize + 20);

					int entry = header;

					for(int section = 0; section < entryCount; section++) {
						int nameIndex = binary.getInt(entry);
						offset = binary.getInt(entry + 16);
						size = binary.getInt(entry + 20);

						int name = pos + nameTableOffset + nameIndex;

						if((long) (0xFFFFFFFF & binary.getInt(name)) == 0x7865742E) {
							if(firstText) {
								firstText = false;
							} else {
								int sectionStart = pos + offset;
								for(int i = 0; i < size / 8; i++) {
									long instruction1 = (long) (0xFFFFFFFF & binary.getInt(sectionStart + i * 8));
									long instruction2 = (long) (0xFFFFFFFF & binary.getInt(sectionStart + i * 8 + 4));

									if((instruction1 & 0x02001000L) == 0x00000000L && (instruction2 & 0x9003F000L) == 0x0001A000L) {
										instruction2 ^= (0x0001A000L ^ 0x0000C000L);

										binary.putInt(sectionStart + i * 8 + 4, (int) instruction2);
									}
								}
							}
						}

						entry += entrySize;
					}

					break;
				}
			}

			IntBuffer binaryErr = BufferUtils.createIntBuffer(1);

			CL10.clReleaseProgram(program);
			program = CL10.clCreateProgramWithBinary(context, device, binary, binaryErr, null);

			err = CL10.clBuildProgram(program, device, compileOptions, null);

			if(err != CL10.CL_SUCCESS) {
				throw new DiabloMinerFatalException(diabloMiner, "Failed to BFI_INT patch kernel on " + deviceName);
			}
		}

		kernel = CL10.clCreateKernel(program, "search", null);
		if(kernel == null) {
			throw new DiabloMinerFatalException(diabloMiner, "Failed to create kernel on " + deviceName);

		}

		if(forceWorkSize == 0) {
			ByteBuffer rkwgs = BufferUtils.createByteBuffer(8);

			err = CL10.clGetKernelWorkGroupInfo(kernel, device, CL10.CL_KERNEL_WORK_GROUP_SIZE, rkwgs, null);

			localWorkSize.put(0, rkwgs.getLong(0));

			if(!(err == CL10.CL_SUCCESS) || localWorkSize.get(0) == 0)
				localWorkSize.put(0, deviceWorkSize);
		} else {
			localWorkSize.put(0, forceWorkSize);
		}

		diabloMiner.info("Added " + deviceName + " (" + deviceCU + " CU, local work size of " + localWorkSize.get(0) + ")");

		workSizeBase = 64 * 512;

		workSize.set(workSizeBase * 16);

		for(int i = 0; i < GPUHardwareType.EXECUTION_TOTAL; i++) {
			String executorName = deviceName + "/" + i;
			executions[i] = this.new GPUExecutionState(executorName);
			Thread thread = new Thread(executions[i], "DiabloMiner Executor (" + executorName + ")");
			thread.start();
			diabloMiner.addThread(thread);
		}
	}

	public void checkDevice() {
		long now = DiabloMiner.now();
		long elapsed = now - lastTime;
		long currentRuns = runs.get();
		double targetFPSBasis = hardwareType.getTargetFPSBasis();
		int totalVectors = hardwareType.getTotalVectors();
		long ws = workSize.get();

		if(now > startTime + DiabloMiner.TIME_OFFSET * 2 && currentRuns > lastRuns + diabloMiner.getGPUTargetFPS()) {
			basis = (double) elapsed / (double) (currentRuns - lastRuns);

			if(basis < targetFPSBasis / 4)
				ws += workSizeBase * 16;
			else if(basis < targetFPSBasis / 2)
				ws += workSizeBase * 4;
			else if(basis < targetFPSBasis)
				ws += workSizeBase;
			else if(basis > targetFPSBasis * 4)
				ws -= workSizeBase * 16;
			else if(basis > targetFPSBasis * 2)
				ws -= workSizeBase * 4;
			else if(basis > targetFPSBasis)
				ws -= workSizeBase;

			if(ws < workSizeBase)
				ws = workSizeBase;
			else if(ws > DiabloMiner.TWO32 / totalVectors - 1)
				ws = DiabloMiner.TWO32 / totalVectors - 1;

			lastRuns = currentRuns;
			lastTime = now;

			workSize.set(ws);
		}
	}

	public class GPUExecutionState extends ExecutionState {
		final CLCommandQueue queue;

		final CLMem output[] = new CLMem[2];
		final CLMem blank;
		ByteBuffer outputBuffer;
		int outputIndex = 0;

		final PointerBuffer workBaseBuffer = BufferUtils.createPointerBuffer(1);
		final PointerBuffer workSizeBuffer = BufferUtils.createPointerBuffer(1);

		final IntBuffer errBuffer = BufferUtils.createIntBuffer(1);
		int err;

		WorkState workState;
		boolean requestedNewWork;

		final int[] midstate2 = new int[16];
		final MessageDigest digestInside;
		final MessageDigest digestOutside;
		final ByteBuffer digestInput = ByteBuffer.allocate(80);
		byte[] digestOutput;

		public GPUExecutionState(String executionName) throws DiabloMinerFatalException {
			super(executionName);

			try {
				digestInside = MessageDigest.getInstance("SHA-256");
				digestOutside = MessageDigest.getInstance("SHA-256");
			} catch(NoSuchAlgorithmException e) {
				throw new DiabloMinerFatalException(diabloMiner, "Your Java implementation does not have a MessageDigest for SHA-256");
			}

			queue = CL10.clCreateCommandQueue(context, device, 0, errBuffer);

			if(queue == null || errBuffer.get(0) != CL10.CL_SUCCESS) {
				throw new DiabloMinerFatalException(diabloMiner, "Failed to allocate queue");
			}

			IntBuffer blankinit = BufferUtils.createIntBuffer(OUTPUTS * 4);

			for(int i = 0; i < OUTPUTS; i++)
				blankinit.put(0);

			blankinit.rewind();

			if(platform_version == PlatformVersion.V1_1)
				blank = CL10.clCreateBuffer(context, CL10.CL_MEM_COPY_HOST_PTR | CL10.CL_MEM_READ_ONLY, blankinit, errBuffer);
			else
				blank = CL10.clCreateBuffer(context, CL10.CL_MEM_COPY_HOST_PTR | CL10.CL_MEM_READ_ONLY | CL12.CL_MEM_HOST_NO_ACCESS, blankinit, errBuffer);

			if(blank == null || errBuffer.get(0) != CL10.CL_SUCCESS)
				throw new DiabloMinerFatalException(diabloMiner, "Failed to allocate blank buffer");

			blankinit.rewind();

			for(int i = 0; i < 2; i++) {
				if(platform_version == PlatformVersion.V1_1)
					output[i] = CL10.clCreateBuffer(context, CL10.CL_MEM_COPY_HOST_PTR | CL10.CL_MEM_WRITE_ONLY, blankinit, errBuffer);
				else
					output[i] = CL10.clCreateBuffer(context, CL10.CL_MEM_COPY_HOST_PTR | CL10.CL_MEM_WRITE_ONLY | CL12.CL_MEM_HOST_READ_ONLY, blankinit, errBuffer);

				blankinit.rewind();

				if(output[i] == null || errBuffer.get(0) != CL10.CL_SUCCESS) {
					throw new DiabloMinerFatalException(diabloMiner, "Failed to allocate output buffer");
				}
			}

			outputBuffer = CL10.clEnqueueMapBuffer(queue, output[outputIndex], 1, CL10.CL_MAP_READ, 0, OUTPUTS * 4, null, null, null);

			diabloMiner.getNetworkStateHead().addGetQueue(this);
			requestedNewWork = true;
		}

		public void run() {
			boolean submittedBlock;
			boolean resetBuffer;
			boolean hwError;
			boolean skipProcessing;
			boolean skipUnmap = false;

			while(diabloMiner.getRunning()) {
				submittedBlock = false;
				resetBuffer = false;
				hwError = false;
				skipProcessing = false;

				WorkState workIncoming = null;

				if(requestedNewWork) {
					try {
						workIncoming = incomingQueue.take();
					} catch(InterruptedException f) {
						continue;
					}
				} else {
					workIncoming = incomingQueue.poll();
				}

				if(workIncoming != null) {
					workState = workIncoming;
					requestedNewWork = false;
					resetBuffer = true;
					skipProcessing = true;
				}

				if(!skipProcessing | !skipUnmap) {
					for(int z = 0; z < OUTPUTS; z++) {
						int nonce = outputBuffer.getInt(z * 4);

						if(nonce != 0) {
							for(int j = 0; j < 19; j++)
								digestInput.putInt(j * 4, workState.getData(j));

							digestInput.putInt(19 * 4, nonce);

							digestOutput = digestOutside.digest(digestInside.digest(digestInput.array()));

							long G = ((long) (0xFF & digestOutput[27]) << 24) | ((long) (0xFF & digestOutput[26]) << 16) | ((long) (0xFF & digestOutput[25]) << 8) | ((long) (0xFF & digestOutput[24]));

							long H = ((long) (0xFF & digestOutput[31]) << 24) | ((long) (0xFF & digestOutput[30]) << 16) | ((long) (0xFF & digestOutput[29]) << 8) | ((long) (0xFF & digestOutput[28]));

							if(H == 0) {
								diabloMiner.debug("Attempt " + diabloMiner.incrementAttempts() + " from " + executionName);

								if(workState.getTarget(7) != 0 || G <= workState.getTarget(6)) {
									workState.submitNonce(nonce);
									submittedBlock = true;
								}
							} else {
								hwError = true;
							}

							resetBuffer = true;
						}
					}

					if(hwError && submittedBlock == false) {
						if(hwcheck && !diabloMiner.getDebug())
							diabloMiner.error("Invalid solution " + diabloMiner.incrementHWErrors() + " from " + deviceName + ", possible driver or hardware issue");
						else
							diabloMiner.debug("Invalid solution " + diabloMiner.incrementHWErrors() + " from " + executionName + ", possible driver or hardware issue");
					}
				}

				if(resetBuffer)
					CL10.clEnqueueCopyBuffer(queue, blank, output[outputIndex], 0, 0, OUTPUTS * 4, null, null);

				if(!skipUnmap) {
					CL10.clEnqueueUnmapMemObject(queue, output[outputIndex], outputBuffer, null, null);

					outputIndex = (outputIndex == 0) ? 1 : 0;
				}

				long workBase = workState.getBase();
				long increment = workSize.get();

				if(DiabloMiner.now() - 3600000 > resetNetworkState) {
					resetNetworkState = DiabloMiner.now();

					diabloMiner.getNetworkStateHead().addGetQueue(this);
					requestedNewWork = skipUnmap = true;
				} else {
					requestedNewWork = skipUnmap = workState.update(increment);
				}

				if(!requestedNewWork) {
					diabloMiner.addAndGetHashCount(increment);
					deviceHashCount.addAndGet(increment);
					runs.incrementAndGet();

					workSizeBuffer.put(0, increment);
					workBaseBuffer.put(0, workBase);

					System.arraycopy(workState.getMidstate(), 0, midstate2, 0, 8);

					DiabloMiner.sharound(midstate2, 0, 1, 2, 3, 4, 5, 6, 7, workState.getData(16), 0x428A2F98);
					DiabloMiner.sharound(midstate2, 7, 0, 1, 2, 3, 4, 5, 6, workState.getData(17), 0x71374491);
					DiabloMiner.sharound(midstate2, 6, 7, 0, 1, 2, 3, 4, 5, workState.getData(18), 0xB5C0FBCF);

					int W16 = workState.getData(16) + (DiabloMiner.rot(workState.getData(17), 7) ^ DiabloMiner.rot(workState.getData(17), 18) ^ (workState.getData(17) >>> 3));
					int W17 = workState.getData(17) + (DiabloMiner.rot(workState.getData(18), 7) ^ DiabloMiner.rot(workState.getData(18), 18) ^ (workState.getData(18) >>> 3)) + 0x01100000;
					int W18 = workState.getData(18) + (DiabloMiner.rot(W16, 17) ^ DiabloMiner.rot(W16, 19) ^ (W16 >>> 10));
					int W19 = 0x11002000 + (DiabloMiner.rot(W17, 17) ^ DiabloMiner.rot(W17, 19) ^ (W17 >>> 10));
					int W31 = 0x00000280 + (DiabloMiner.rot(W16, 7) ^ DiabloMiner.rot(W16, 18) ^ (W16 >>> 3));
					int W32 = W16 + (DiabloMiner.rot(W17, 7) ^ DiabloMiner.rot(W17, 18) ^ (W17 >>> 3));

					int PreVal4 = workState.getMidstate(4) + (DiabloMiner.rot(midstate2[1], 6) ^ DiabloMiner.rot(midstate2[1], 11) ^ DiabloMiner.rot(midstate2[1], 25)) + (midstate2[3] ^ (midstate2[1] & (midstate2[2] ^ midstate2[3]))) + 0xe9b5dba5;
					int T1 = (DiabloMiner.rot(midstate2[5], 2) ^ DiabloMiner.rot(midstate2[5], 13) ^ DiabloMiner.rot(midstate2[5], 22)) + ((midstate2[5] & midstate2[6]) | (midstate2[7] & (midstate2[5] | midstate2[6])));

					int PreVal4_state0 = PreVal4 + workState.getMidstate(0);
					int PreVal4_state0_k7 = (int) (PreVal4_state0 + 0xAB1C5ED5L);
					int PreVal4_T1 = PreVal4 + T1;
					int B1_plus_K6 = (int) (midstate2[1] + 0x923f82a4L);
					int C1_plus_K5 = (int) (midstate2[2] + 0x59f111f1L);
					int W16_plus_K16 = (int) (W16 + 0xe49b69c1L);
					int W17_plus_K17 = (int) (W17 + 0xefbe4786L);

					kernel.setArg(0, PreVal4_state0).setArg(1, PreVal4_state0_k7).setArg(2, PreVal4_T1).setArg(3, W18).setArg(4, W19).setArg(5, W16).setArg(6, W17).setArg(7, W16_plus_K16).setArg(8, W17_plus_K17).setArg(9, W31).setArg(10, W32).setArg(11, (int) (midstate2[3] + 0xB956c25bL)).setArg(12, midstate2[1]).setArg(13, midstate2[2]).setArg(14, midstate2[7]).setArg(15, midstate2[5]).setArg(16, midstate2[6]).setArg(17, C1_plus_K5).setArg(18, B1_plus_K6).setArg(19, workState.getMidstate(0)).setArg(20, workState.getMidstate(1)).setArg(21, workState.getMidstate(2)).setArg(22, workState.getMidstate(3)).setArg(23, workState.getMidstate(4)).setArg(24, workState.getMidstate(5)).setArg(25, workState.getMidstate(6)).setArg(26, workState.getMidstate(7)).setArg(27, output[outputIndex]);

					err = CL10.clEnqueueNDRangeKernel(queue, kernel, 1, workBaseBuffer, workSizeBuffer, localWorkSize, null, null);

					if(err != CL10.CL_SUCCESS && err != CL10.CL_INVALID_KERNEL_ARGS && err != CL10.CL_INVALID_GLOBAL_OFFSET) {
						try {
							throw new DiabloMinerFatalException(diabloMiner, "Failed to queue kernel, error " + err);
						} catch(DiabloMinerFatalException e) {
						}
					} else {
						if(err == CL10.CL_INVALID_KERNEL_ARGS) {
							diabloMiner.debug("Spurious CL_INVALID_KERNEL_ARGS error, ignoring");
							skipUnmap = true;
						} else if(err == CL10.CL_INVALID_GLOBAL_OFFSET) {
							diabloMiner.error("Spurious CL_INVALID_GLOBAL_OFFSET error, offset: " + workBase + ", work size: " + increment);
							skipUnmap = true;
						} else {
							outputBuffer = CL10.clEnqueueMapBuffer(queue, output[outputIndex], 1, CL10.CL_MAP_READ, 0, OUTPUTS * 4, null, null, null);
						}
					}
				}
			}
		}
	}
}


text:
import { Template } from 'meteor/templating';
import { Stuff } from '../../api/stuff/stuff.js';

Template.List_Invites_Page.helpers({

  /**
   * @returns {*} All of the Stuff documents.
   */
  stuffList() {
    return Stuff.find();
  },
});


text:
<?xml version="1.0" encoding="UTF-8"?>
	<!--
		Licensed to the Apache Software Foundation (ASF) under one or more
		contributor license agreements. See the NOTICE file distributed with
		this work for additional information regarding copyright ownership.
		The ASF licenses this file to You 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">

	<modelVersion>4.0.0</modelVersion>

        <parent>
              <groupId>org.apache.aries.tutorials.blueprint</groupId>
              <artifactId>blueprint</artifactId>
              <version>0.4-SNAPSHOT</version>
        </parent>

	<groupId>org.apache.aries.tutorials.blueprint</groupId>
	<artifactId>tutorial-assembly</artifactId>
	<name>Greeter Tutorial Assembly</name>
	<packaging>pom</packaging>

	<dependencies>

                <!-- External (platform) dependencies -->

		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.fileinstall</artifactId>
		</dependency>

		<dependency>
			<groupId>org.eclipse</groupId>
			<artifactId>osgi</artifactId>
		</dependency>

		<dependency>
			<groupId>org.eclipse.equinox</groupId>
			<artifactId>cm</artifactId>
		</dependency>

		<dependency>
			<groupId>org.eclipse.osgi</groupId>
			<artifactId>services</artifactId>
		</dependency>

		<dependency>
			<groupId>org.ops4j.pax.logging</groupId>
			<artifactId>pax-logging-api</artifactId>
		</dependency>

		<dependency>
			<groupId>org.ops4j.pax.logging</groupId>
			<artifactId>pax-logging-service</artifactId>
		</dependency>

                <!-- Internal (Aries) dependencies -->

		<dependency>
			<groupId>org.apache.aries.blueprint</groupId>
			<artifactId>org.apache.aries.blueprint</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.aries</groupId>
			<artifactId>org.apache.aries.util</artifactId>
		</dependency>

                <!-- Sample application dependencies -->

		<dependency>
			<groupId>org.apache.aries.tutorials.blueprint</groupId>
			<artifactId>org.apache.aries.tutorials.blueprint.greeter.api</artifactId>
                        <version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.aries.tutorials.blueprint</groupId>
			<artifactId>org.apache.aries.tutorials.blueprint.greeter.client.blueprint</artifactId>
                        <version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.aries.tutorials.blueprint</groupId>
			<artifactId>org.apache.aries.tutorials.blueprint.greeter.client.osgi</artifactId>
                        <version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.aries.tutorials.blueprint</groupId>
			<artifactId>org.apache.aries.tutorials.blueprint.greeter.server.blueprint</artifactId>
                        <version>${project.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.aries.tutorials.blueprint</groupId>
			<artifactId>org.apache.aries.tutorials.blueprint.greeter.server.osgi</artifactId>
                        <version>${project.version}</version>
		</dependency>

	</dependencies>

	<modules>
		<module>../tutorial-modules/greeter-api</module>
		<module>../tutorial-modules/greeter-client-blueprint</module>
		<module>../tutorial-modules/greeter-client-osgi</module>
		<module>../tutorial-modules/greeter-server-blueprint</module>
		<module>../tutorial-modules/greeter-server-osgi</module>
	</modules>

	<build>
		<plugins>
			<plugin>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-resources-plugin</artifactId>
                                <configuration>
                                        <outputDirectory>${project.build.directory}</outputDirectory>
                                </configuration>
                                <executions>
                                        <execution>
                                                <id>filter</id>
                                                <phase>generate-resources</phase>
                                                <goals>
                                                        <goal>resources</goal>
                                                </goals>
                                        </execution>
                                </executions>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.2-beta-5</version>
				<configuration>
					<descriptors>
						<descriptor>src/main/assemblies/tutorial-assembly.xml</descriptor>
					</descriptors>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;
using BungieNetPlatform.Enums;

namespace BungieNetPlatform {

	[DataContract]
	public class IgnoreStatus {

		[DataMember]
		public bool Ignored;

		[DataMember]
		public IgnoreFlags Flags;

		public IgnoreStatus(JObject j) {
			Ignored = j["isIgnored"].Value<bool>();
			Flags = (IgnoreFlags)j["ignoreFlags"].Value<int>();
		}

	}
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.packaging;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.python.packaging.pipenv.PyPipEnvPackageManagementService;
import com.jetbrains.python.packaging.pipenv.PyPipEnvPackageManager;
import com.jetbrains.python.packaging.ui.PyCondaManagementService;
import com.jetbrains.python.packaging.ui.PyPackageManagementService;
import com.jetbrains.python.sdk.PythonSdkType;
import com.jetbrains.python.sdk.PythonSdkUtil;
import com.jetbrains.python.sdk.pipenv.PipenvKt;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yole
 */
public class PyPackageManagersImpl extends PyPackageManagers {
  // TODO: Introduce a Python SDK provider EP that is capable of providing a custom package manager and a package management service

  private final Map<String, PyPackageManager> myInstances = new HashMap<>();

  @Override
  @NotNull
  public synchronized PyPackageManager forSdk(@NotNull final Sdk sdk) {
    final String key = PythonSdkType.getSdkKey(sdk);
    PyPackageManager manager = myInstances.get(key);
    if (manager == null) {
      final VirtualFile homeDirectory = sdk.getHomeDirectory();
      PyPackageManager customPackageManager = PyCustomPackageManagers.tryCreateCustomPackageManager(sdk);
      if (customPackageManager != null) {
        manager = customPackageManager;
      }
      else if (PythonSdkUtil.isRemote(sdk)) {
        manager = new PyUnsupportedPackageManager(sdk);
      }
      else if (PipenvKt.isPipEnv(sdk)) {
        manager = new PyPipEnvPackageManager(sdk);
      }
      else if (PythonSdkUtil.isConda(sdk) &&
               homeDirectory != null &&
               PyCondaPackageService.getCondaExecutable(sdk.getHomePath()) != null) {
        manager = new PyCondaPackageManagerImpl(sdk);
      }
      else {
        manager = new PyPackageManagerImpl(sdk);
      }
      myInstances.put(key, manager);
    }
    return manager;
  }

  @Override
  public PyPackageManagementService getManagementService(Project project, Sdk sdk) {
    if (PythonSdkUtil.isConda(sdk)) {
      return new PyCondaManagementService(project, sdk);
    }
    else if (PipenvKt.isPipEnv(sdk)) {
      return new PyPipEnvPackageManagementService(project, sdk);
    }
    return new PyPackageManagementService(project, sdk);
  }

  @Override
  public void clearCache(@NotNull Sdk sdk) {
    final String key = PythonSdkType.getSdkKey(sdk);
    myInstances.remove(key);
  }
}


text:
<?php
/**
 * Template Name: Map
 *
 * This is the template that displays the map, which is built
 * with the Google Maps JavaScript API.
 *
 * @link https://codex.wordpress.org/Template_Hierarchy
 *
 * @package corona
 */

get_header(); ?>

	<?php tha_content_before(); ?>

		<?php tha_content_top(); ?>

			<?php $markers = get_posts( array(
				'post_type'        => array( 'event', 'outcome' ),
				'posts_per_page'   => 500,
				'suppress_filters' => false,
				'fields'           => 'ids',
				'meta_query'       => array(
					'relation'    => 'OR',
					array(
						'key'     => 'exclude_from_map',
						'compare' => '!=',
						'value'   => '1'
					),
					array(
						'key'     => 'exclude_from_map',
						'compare' => 'NOT EXISTS'
					)
				)
			) );
			foreach( $markers as $marker ) { ?>
				<a class="element-invisible map-tab" id="map-tab-<?php echo (int) $marker; ?>" data-id="<?php echo (int) $marker; ?>" href="#marker-<?php echo (int) $marker; ?>"><?php echo esc_html( get_the_title( $marker ) ); ?>
			<?php } ?>

					<img src="<?php echo esc_url( get_stylesheet_directory_uri() ); ?>/images/marker-techcamp.svg" alt="Blue TechCamp Marker" />

<?php echo esc_html( techcamp_get_setting( 'map_legend_techcamps' ) ); ?>

					<img src="<?php echo esc_url( get_stylesheet_directory_uri() ); ?>/images/marker-outcome.svg" alt="Green Outcome Marker" />

<?php echo esc_html( techcamp_get_setting( 'map_legend_outcomes' ) ); ?>

					Dark Blue

<?php echo esc_html( techcamp_get_setting( 'map_legend_regions' ) ); ?>

					Light Blue

<?php echo esc_html( techcamp_get_setting( 'map_legend_participators' ) ); ?>

		<?php the_post(); ?>

<?php the_title(); ?>

			<?php the_content(); ?>

			Countries include dependencies and areas of special sovereignty.

		<?php tha_content_bottom(); ?>

	<?php tha_content_after(); ?>

<?php get_footer();


text:
class SiphonGenerator < Rails::Generators::NamedBase
  source_root File.expand_path("../templates", __FILE__)

  def create_search_file
    template "search.rb", File.join('app/siphon', class_path, "#{file_name}_search.rb")
  end

  def create_controller
    template "controller.rb", File.join('app/controllers', class_path, "#{file_name.pluralize}_controller.rb")
  end

  def create_view
    template "view.rb", File.join('app/views', class_path, "#{file_name.pluralize}", "_search.html.haml")
  end

  def class_mate
    classy = begin
       Object.const_get(class_name) ||
       Object.const_get( file_name.classify)
    rescue
    end
  end

end


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Club = mongoose.model('Club'),
	_ = require('lodash');

/**
 * Create a Club
 */
exports.create = function(req, res) {
	var club = new Club(req.body);
	club.user = req.user;

	club.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(club);
		}
	});
};

/**
 * Show the current Club
 */
exports.read = function(req, res) {
	res.jsonp(req.club);
};

/**
 * Update a Club
 */
exports.update = function(req, res) {
	var club = req.club ;

	club = _.extend(club , req.body);

	club.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(club);
		}
	});
};

/**
 * Delete an Club
 */
exports.delete = function(req, res) {
	var club = req.club ;

	club.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(club);
		}
	});
};

/**
 * List of Clubs
 */
exports.list = function(req, res) {
	Club.find().sort('-created').populate('user', 'displayName').exec(function(err, clubs) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(clubs);
		}
	});
};

/**
 * Club middleware
 */
exports.clubByID = function(req, res, next, id) {
	Club.findById(id).populate('user', 'displayName').exec(function(err, club) {
		if (err) return next(err);
		if (! club) return next(new Error('Failed to load Club ' + id));
		req.club = club ;
		next();
	});
};

/**
 * Club authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {

	if (req.club.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}

	next();
};


text:
Warp-drive is a self-hosted image hosting service. It was born out of the need
to store images for [our blog](http://kir-dev.sch.bme.hu). Storing a lot of
images in a git repo is not a lot of fun.

## Overview

It stores images in the file system, while metadata is in a database. We are
using postgres. There is a simple page for uploading and searching images. Every
image can be linked by its unique url and an optional width can be provided. If
a width is provided then the image will be resized and the aspect ratio will be
kept. If the width is greater than the original with then the original size will
be used.

## Main features

* Upload and store images
* Easily link to images

    URL structure:

        //example.com/<hash-of-image>/[width]

* Resize images on the fly
* Search among the uploaded images

## Install

1. Download the [latest release](https://github.com/kir-dev/warp-drive/releases/latest).
2. Extract the archive
3. Create or upgrade the database
    * for a clean install follow the instructions [here](#setting-up-the-database).
    * for an upgrade use the `config/upgrade.sql` if any.
4. start your application:

        $ ./warp
        # for more information on the command-line arguments
        $ ./warp --help

Using it with a reverse HTTP proxy is probably the easiest way to provide SSL
support. (Currently the application only support HTTP.)

## Development

### Prerequisites

1. install the latest [PostgreSQL](http://www.postgresql.org/download/)
2. install [go1.2+](http://golang.org/doc/install#download)

### Setting up the database

Assuming a running and functional postgresql server.

    $ sudo su - postgres
    $ createuser -l -E -P -R -S -D warp
    $ createdb -O warp -E utf8 warp
    $ psql -U warp -d warp -h localhost -f /path/to/warp/scripts/sql/schema.sql

### Setting up your go environment

Assuming you have go installed, create your workspace.

    $ mkdir -p /path/to/your/workspace/src
    $ export GOPATH=$GOPATH:/path/to/your/workspace

The src folder at the end is mandatory.

### Get the code

    $ cd /path/to/your/workspace/src
    $ git clone https://github.com/kir-dev/warp-drive.git warp-drive

### Setup your config file

    $ cp config/config.json.dist config/config.json
    $ vim config/config.json

For detailed information about the configuration look at the
[configuration](#configuration) section.

### Build & run

We are using [godep](https://github.com/tools/godep) for managing dependencies,
so you must have `godep` installed in your `PATH`.

To build the bot itself just run

    $ make

It creates a new executable named `warp`. To run it simply:

    $ ./warp

Open http://localhost:8080 in your browser.

### Modifying the database schema

When modifying the database schema create a new `.sql` file in `scripts/sql`
directory. The name should contain the date and the purpose of the modification.
Eg: `2014-04-09-created-users-table.sql`.

**DO NOT** forget to add the the modifications to the `schema.sql` file as well.
The schema file should always contain the full schema for a clean install.

## Configuration

Rename or create a copy of the `config.json.dist`. `config/config.json` is
recognized by default, use the `-config` option to provide an alternate config
file.

Currently the config file contains the following options:

* `uploadPath`: base directory for image uploads
* `serverAddress`: the host (including port if necessary)
* `user`, `password`: the user name and password for uploading images
* `db`: connection information for the database
* `sessionSecret`: a random key for signing the session cookies
* `clientId`: OAuth (auth.sch) client id
* `clientSecret`: OAuth (auth.sch) client secret
* `secure`: set it to true and session cookies are only transmitted via https
* `groupId`: restric upload access to members of a specific group. Set it to `0` for no restriction.

### OAuth configuration

For development register a new application at [auth.sch.bme.hu][3] and use the provided
credentials. For the redirect address give something like `http://localhost:8080/auth`.

## Contributing

1. Fork it.
2. Create a branch (`git checkout -b my_awesome_path`)
3. Commit your changes (`git commit -am "Awesome stuff added"`)
4. Push to the branch (`git push origin my_awesome_path`)
5. Open a [Pull Request][1]
6. Enjoy a refreshing Diet Coke and wait

When committing go code **always** use the `go fmt` tool first. Possibly one could
set up a pre-commit git-hook to automate this.

Or you can do it manually:

    $ go fmt ./...
    # or
    $ make fmt

## Adding a new dependency

We are using [godep](https://github.com/tools/godep) for managing dependencies,
so you must have `godep` installed in your `PATH`.

Use the [godep workflow](https://github.com/tools/godep#add-or-update-a-dependency)
and use the `-copy=false` option on save.

## Releasing

For versioning we try to follow the rules of [semver](http://semver.org/). This
means that every release has a `MAJOR.MINOR.PATCH` versioning scheme.

1. Create a new distribution archive

        $ ./scripts/dist.sh MAJOR.MINOR.PATCH

2. Tag the new release

        $ git tag -a vMAJOR.MINOR.PATCH

    In the tag message describe the new release briefly.

3. Prepare a new [github release][2]. Describe the new release in detail and
upload the distribution archive for the release.

[1]: https://github.com/kir-dev/warp-drive/pulls
[2]: https://github.com/blog/1547-release-your-software
[3]: https://auth.sch.bme.hu/console/index


text:
package com.faceyspacies.RandomCrate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;

public final class RandomCrateListener implements Listener {

	private JavaPlugin plugin;

	public RandomCrateListener(JavaPlugin plugin) {
		this.plugin = plugin;
	}

	@SuppressWarnings("deprecation")
	@EventHandler(priority = EventPriority.HIGHEST)
	public void onPlayerInteractBlock(PlayerInteractEvent event) {

		Player player = event.getPlayer();
		ItemStack handItem = player.getItemInHand();

		if(handItem == null)
			return;

		if(handItem.getItemMeta() != null) {
			if(handItem.getItemMeta().getDisplayName() == null)
				return;
		} else {
			return;
		}

		if(handItem.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("random-crate-name")))) {

			player.sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("random-crate-open-msg")));

	   		PlayerInventory inventory = player.getInventory();
			ItemStack item = new ItemStack(Material.CHEST, 1);
			ItemMeta meta = item.getItemMeta();
			List<String> lore = new ArrayList<String>();

			lore.add(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("random-crate-lore")));
			meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("random-crate-name")));
			meta.setLore(lore);
			item.setItemMeta(meta);

			HashMap<Integer, ItemStack> result = inventory.removeItem(item); // removes block
			if(result.size() > 0) {
				event.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', plugin.getConfig().getString("random-crate-dont-have-msg")));
				return;
			}

			inventory.addItem(getRandomItem());
			player.updateInventory();

			event.setCancelled(true); // doesn't do an action with it
	    }
    }

	private ItemStack getRandomItem() {
		int randomNum = (int)((Math.random()) * 100);
		char type = RandomCrate.distributionList[randomNum];
		// item starts in the itemList starts at 0
		if(type == 'c') {
			randomNum = (int)((Math.random()) * 100);
			return RandomCrate.commonItemList.get(randomNum);
		}
		else if (type== 'v') {
			randomNum = (int)((Math.random()) * 100);
			return RandomCrate.vrareItemList.get(randomNum);
		}
		else {
			randomNum = (int)((Math.random()) * 100);
			return RandomCrate.rareItemList.get(randomNum);
		}
	}
}