text:
package edu.kit.dama.staging.interfaces;

import edu.kit.dama.commons.types.DigitalObjectId;
import edu.kit.dama.mdm.dataorganization.entity.core.IFileTree;
import edu.kit.dama.staging.entities.download.DownloadInformation;
import edu.kit.dama.staging.exceptions.TransferPreparationException;
import java.util.List;
import java.util.Map;

/**
 *
 * @author jejkal
 * @param <C> An implementation of IAuthorizationContext.
 */
public interface IDownloadInformationService<C> {

  /**
   * Get information about one specific download identified by a unique
   * DownloadID.
   *
   * @param pDownloadId The ID of the download to find.
   * @param pSecurityContext The security context which is used to authorize the
   * access.
   *
   * @return The download information entity associated with pDownloadId.
   */
  DownloadInformation getDownloadInformationById(Long pDownloadId, C pSecurityContext);

  /**
   * Get all download informations associated with a specific digital object id.
   * For a normal user a single entity should be returned, for administrator
   * access multiple entities might be returned.
   *
   * @param pDigitalObjectId The digital object id.
   * @param pFirstIndex The first index returned.
   * @param pResults The max. number of results.
   * @param pSecurityContext The security context which is used to filter the
   * list of downloads.
   *
   * @return All download informations associated with pDigitalObjectId.
   */
  List<DownloadInformation> getDownloadInformationByDigitalObjectId(DigitalObjectId pDigitalObjectId, int pFirstIndex, int pResults, C pSecurityContext);

  /**
   * Get the number of download informations associated with a specific digital
   * object id. For a normal user 0 or 1 should be returned, for an
   * administrator values largen than 1 might be returned.
   *
   * @param pDigitalObjectId The digital object id.
   * @param pSecurityContext The security context which is used to filter the
   * list of downloads.
   *
   * @return The number of download informations associated with
   * pDigitalObjectId.
   */
  Number getDownloadInformationCountByDigitalObjectId(DigitalObjectId pDigitalObjectId, C pSecurityContext);

  /**
   * Get a list of download information associated with a specific user.
   *
   * @param pOwner The owner.
   * @param pFirstIndex The first index the query will start with.
   * @param pResults The maximum number of results returned.
   * @param pSecurityContext The security context which is used to filter the
   * list of downloads.
   *
   * @return All download informations accessible using pSecurityContext.
   */
  List<DownloadInformation> getDownloadInformationByOwner(String pOwner, int pFirstIndex, int pResults, C pSecurityContext);

  /**
   * Get the number of downloads for the provided owner.
   *
   * @param pOwner The owner.
   * @param pSecurityContext The security context which is used to filter the
   * list of downloads.
   *
   * @return The number of downloads for pOwner.
   */
  Integer getDownloadInformationCountByOwner(String pOwner, C pSecurityContext);

  /**
   * Get all download informations associated with the current security context.
   * For a standard user all downloads owned by the user will be returned, for
   * an admistrator all downloads will be returned.
   *
   * @param pFirstIndex The first index the query will start with.
   * @param pResults The maximum number of results returned.
   * @param pSecurityContext The security context which is used to filter the
   * list of downloads.
   *
   * @return All download informations accessible using pSecurityContext.
   */
  List<DownloadInformation> getAllDownloadInformation(int pFirstIndex, int pResults, C pSecurityContext);

  /**
   * Get the number of all download informations associated with the current
   * security context.
   *
   * @param pSecurityContext The security context which is used to filter the
   * list of downloads.
   *
   * @return The number of accessible download entities.
   */
  Integer getAllDownloadInformationCount(C pSecurityContext);

  /**
   * Get a list of download information associated with pSecurityContext having
   * the status pStatus. For a user all downloads will be returned that were
   * initiated by her/him.
   *
   * @param pStatusCode The status code used to query for download information.
   * Here we use Integer instead of DOWNLOAD_STATUS enum to be able to implement
   * this interface for remote services accessible by other programming
   * languages.
   * @param pFirstIndex The first index the query will start with.
   * @param pResults The maximum number of results returned.
   * @param pSecurityContext The security context which is used to authorize the
   * access.
   *
   * @return All downloads having status pStatus.
   */
  List<DownloadInformation> getDownloadInformationByStatus(Integer pStatusCode, int pFirstIndex, int pResults, C pSecurityContext);

  /**
   * Get the number of downloads for the provided status.
   *
   * @param pStatusCode The status.
   * @param pSecurityContext The security context which is used to filter the
   * list of downloads.
   *
   * @return The number of ingests with pStatusCode.
   */
  Integer getDownloadInformationCountByStatus(Integer pStatusCode, C pSecurityContext);

  /**
   * Get a list of expired download information entities.
   *
   * @param pFirstIndex The first index the query will start with.
   * @param pResults The maximum number of results returned.
   * @param pSecurityContext The security context which is used to authorize the
   * access.
   *
   * @return All expired download entites accessible via pSecurityContext.
   */
  List<DownloadInformation> getExpiredDownloadInformation(int pFirstIndex, int pResults, C pSecurityContext);

  /**
   * Get the number of expired download information entities.
   *
   * @param pSecurityContext The security context which is used to authorize the
   * access.
   *
   * @return The number expired download information entities accessible via
   * pSecurityContext.
   */
  Integer getExpiredDownloadInformationCount(C pSecurityContext);

  /**
   * Schedules a download. Scheduling consists of the following steps:

   *
Check if pSecurityContext is allowed to download data

Create a
   * new download entity and write it into the data backend

If there is
   * already an entity for the provided object id check for the status. In case
   * of a previous error allow modification, in all other cases throw an
   * exception

Perform all necessary steps to allow asynchronous
   * download preparation.

   *
   * @param pDigitalObjectId The digital object ID.
   * @param pFileTree The tree of data organisation objects which will be
   * downloaded.
   * @param pProperties Properties used to configure the access to the download.
   * This map contains download specific arguments provided by the access layer,
   * e.g. how the download will be performed using which protocol.
   * @param pSecurityContext The security context.
   *
   *
   * @return The created download information entity.
   *
   * @throws TransferPreparationException If the transfer could not be prepared.
   */
  DownloadInformation scheduleDownload(DigitalObjectId pDigitalObjectId, IFileTree pFileTree, Map<String, String> pProperties, C pSecurityContext) throws TransferPreparationException;

  /**
   * Update the status for the entity with the provided id to pStatus and the
   * error message to pErrorMessage. If pErrorMessage is null, the message will
   * remain unchanged.
   *
   * @param pId The id of the entity to update.
   * @param pStatus The new status in its integer representation.
   * @param pErrorMessage The new error message.
   * @param pSecurityContext The authorization context.
   *
   * @return Then umber of affected rows.
   */
  Integer updateStatus(Long pId, Integer pStatus, String pErrorMessage, C pSecurityContext);

  /**
   * Update the client access URL for the entity with the provided id to
   * pAccessURL.
   *
   * @param pId The id of the entity to update.
   * @param pAccessURL The client access URL.
   * @param pSecurityContext The authorization context.
   *
   * @return The number of affected rows.
   */
  Integer updateClientAccessUrl(Long pId, String pAccessURL, C pSecurityContext);

  /**
   * Update the staging URL for the entity with the provided id to pStagingURL.
   *
   * @param pId The id of the entity to update.
   * @param pStagingURL The staging URL.
   * @param pSecurityContext The authorization context.
   *
   * @return The result which contains the number of affected rows.
   */
  Number updateStagingUrl(Long pId, String pStagingURL, C pSecurityContext);

  /**
   * Update the storage URL for the entity with the provided id to pStorageURL.
   *
   * @param pId The id of the entity to update.
   * @param pStorageURL The storage URL.
   * @param pSecurityContext The authorization context.
   *
   * @return The number of affected rows.
   */
  Integer updateStorageUrl(Long pId, String pStorageURL, C pSecurityContext);

  /**
   * Remove the entity with the provided id.
   *
   * @param pId The id of the entity to update.
   * @param pSecurityContext The authorization context.
   *
   * @return The number of affected rows.
   */
  Integer removeEntity(Long pId, C pSecurityContext);
}


text:
module CoreHelpers
  def mustache(template, options = {})
    @view_folder = File.expand_path(Apollo.config[:sinatra][:views])
    # serialize active records
    def serialize_active_records(scope_attributes)
      scope_attributes.each do |key, value|
        if value.respond_to?("any?") && value.is_a?(ActiveRecord::Relation)
          scope_attributes[key] = value.map do |record|
            record.serializable_hash
          end
        end
      end
      scope_attributes
    end
    @template = template
    def mustache_yield
      yield_file = File.read("#{@view_folder}/#{@template}.mustache")
      Mustache.render(yield_file, serialize_active_records(attributes))
    end
    @yield = mustache_yield
    def mustache_components
      files = Dir.entries("#{@view_folder}/components")
      components_out = {}
      files.each do |f|
        if f != "." && f != ".."
          component_file = File.read("#{@view_folder}/components/#{f}")
          component = Mustache.render(component_file, serialize_active_records(attributes))
          components_out[f.gsub(/\..+\Z/,"")] = component
        end
      end
      components_out
    end
    @components = mustache_components
    if options[:layout]
      layout = "#{@view_folder}/#{options[:layout]}.mustache"
    else
      layout = "#{@view_folder}/layout.mustache"
    end
    layout_file = File.read(layout)
    Mustache.render(layout_file, serialize_active_records(attributes))
  end
end

redpajama_set_name: RedPajamaGithub


text:
    #define kParseAPIClientAppId kParseAPIClientDevelopmentAppId
    #define kParseAPIClientClienKey kParseAPIClientDevelopmentClientKey

#else

    #define kParseAPIClientAppId kParseAPIClientProductionAppId
    #define kParseAPIClientClienKey kParseAPIClientProductionClientKey

#endif


text:
{% extends "admin/base_site.html" %}
{% load i18n %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% load adminmedia %}{% admin_media_prefix %}css/dashboard.css" />{% endblock %}

{% block coltype %}colMS{% endblock %}

{% block bodyclass %}dashboard{% endblock %}

{% block breadcrumbs %}{% endblock %}

{% block content %}

                Room Reservations Manager

                Configuration

                Room Setup

                Room Cancellation Log

                Authentication

                Users

{% endblock %}


text:
Commands that help you maintain control over a compromised system.

  * [General Commands](general.md) - Commands your could/should use to maintain your hold on the compromised system.


text:
NSString *kIsPausedKey = @"IsPaused Key";
NSString *kRemainingTimeIntervalKey = @"RemainingTimeInterval Key";

@implementation NSTimer (Pausing)

- (NSMutableDictionary *)pauseDictionary {
    static NSMutableDictionary *globalDictionary = nil;

    if(!globalDictionary)
        globalDictionary = [[NSMutableDictionary alloc] init];

    if(![globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]]) {
        NSMutableDictionary *localDictionary = [[NSMutableDictionary alloc] init];
        [globalDictionary setObject:localDictionary forKey:[NSNumber numberWithInt:(int)self]];
    }

    return [globalDictionary objectForKey:[NSNumber numberWithInt:(int)self]];
}

- (void)pause {
    if(![self isValid])
        return;

    NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];
    if(isPausedNumber && YES == [isPausedNumber boolValue])
        return;

    NSDate *now = [NSDate date];
    NSDate *then = [self fireDate];
    NSTimeInterval remainingTimeInterval = [then timeIntervalSinceDate:now];

    [[self pauseDictionary] setObject:[NSNumber numberWithDouble:remainingTimeInterval] forKey:kRemainingTimeIntervalKey];

    [self setFireDate:[NSDate distantFuture]];
    [[self pauseDictionary] setObject:[NSNumber numberWithBool:YES] forKey:kIsPausedKey];
}

- (void)resume {
    if(![self isValid])
        return;

    NSNumber *isPausedNumber = [[self pauseDictionary] objectForKey:kIsPausedKey];
    if(!isPausedNumber || NO == [isPausedNumber boolValue])
        return;

    NSTimeInterval remainingTimeInterval = [[[self pauseDictionary] objectForKey:kRemainingTimeIntervalKey] doubleValue];

    NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:remainingTimeInterval];

    [self setFireDate:fireDate];
    [[self pauseDictionary] setObject:[NSNumber numberWithBool:NO] forKey:kIsPausedKey];
}

@end


text:
package com.heliosapm.utils.xa;

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

/**
 *
Title: XAExceptionCode

 *
Description: Decodes for {@link javax.transaction.xa.XAException} codes

 *
Company: Helios Development Group LLC

 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 *
com.heliosapm.utils.xa.XAExceptionCode

 */

public enum XAExceptionCode {
	/** XAException Code for XA_RBBASE */
	XA_RBBASE(100, "The inclusive lower bound of the rollback codes."),
	/** XAException Code for XA_RBROLLBACK */
	XA_RBROLLBACK(100, "Indicates that the rollback was caused by an unspecified reason."),
	/** XAException Code for XA_RBCOMMFAIL */
	XA_RBCOMMFAIL(101, "Indicates that the rollback was caused by a communication failure."),
	/** XAException Code for XA_RBDEADLOCK */
	XA_RBDEADLOCK(102, "A deadlock was detected."),
	/** XAException Code for XA_RBINTEGRITY */
	XA_RBINTEGRITY(103, "A condition that violates the integrity of the resource was detected."),
	/** XAException Code for XA_RBOTHER */
	XA_RBOTHER(104, "The resource manager rolled back the transaction branch for a reason not on this list."),
	/** XAException Code for XA_RBPROTO */
	XA_RBPROTO(105, "A protocol error occurred in the resource manager."),
	/** XAException Code for XA_RBTIMEOUT */
	XA_RBTIMEOUT(106, "A transaction branch took too long."),
	/** XAException Code for XA_RBTRANSIENT */
	XA_RBTRANSIENT(107, "May retry the transaction branch."),
	/** XAException Code for XA_RBEND */
	XA_RBEND(107, "The inclusive upper bound of the rollback error code."),
	/** XAException Code for XA_NOMIGRATE */
	XA_NOMIGRATE(9, "Resumption must occur where the suspension occurred."),
	/** XAException Code for XA_HEURHAZ */
	XA_HEURHAZ(8, "The transaction branch may have been heuristically completed."),
	/** XAException Code for XA_HEURCOM */
	XA_HEURCOM(7, "The transaction branch has been heuristically committed."),
	/** XAException Code for XA_HEURRB */
	XA_HEURRB(6, "The transaction branch has been heuristically rolled back."),
	/** XAException Code for XA_HEURMIX */
	XA_HEURMIX(5, "The transaction branch has been heuristically committed and rolled back."),
	/** XAException Code for XA_RETRY */
	XA_RETRY(4, "Routine returned with no effect and may be reissued."),
	/** XAException Code for XA_RDONLY */
	XA_RDONLY(3, "The transaction branch was read-only and has been committed."),
	/** XAException Code for XAER_ASYNC */
	XAER_ASYNC(-2, "There is an asynchronous operation already outstanding."),
	/** XAException Code for XAER_RMERR */
	XAER_RMERR(-3, "A resource manager error has occurred in the transaction branch."),
	/** XAException Code for XAER_NOTA */
	XAER_NOTA(-4, "The XID is not valid."),
	/** XAException Code for XAER_INVAL */
	XAER_INVAL(-5, "Invalid arguments were given."),
	/** XAException Code for XAER_PROTO */
	XAER_PROTO(-6, "Routine was invoked in an improper context."),
	/** XAException Code for XAER_RMFAIL */
	XAER_RMFAIL(-7, "Resource manager is unavailable."),
	/** XAException Code for XAER_DUPID */
	XAER_DUPID(-8, "The XID already exists."),
	/** XAException Code for XAER_OUTSIDE */
	XAER_OUTSIDE(-9, "The resource manager is doing work outside a global transaction."),
	/** XAException Code for an invalid code */
	XA_INVALID(-999, "Invalid XAException code.");

	private XAExceptionCode(final int code, final String description) {
		this.code = code;
		this.description = description;
	}

	public static final Map<Integer, XAExceptionCode> CODE2ENUM;

	static {
		final XAExceptionCode[] values = values();
		Map<Integer, XAExceptionCode> tmp = new HashMap<Integer, XAExceptionCode>(values.length);
		for(XAExceptionCode xar: values) {
			tmp.put(xar.code, xar);
		}
		CODE2ENUM = Collections.unmodifiableMap(tmp);
	}

	/** The XAResource code */
	public final int code;
	/** The code description */
	public final String description;

	/**
	 * Returns the XAExceptionCode decode for the passed code.
	 * @param c The code to decode
	 * @return The decoded XAExceptionCode or {@link #XA_INVALID}
	 * if the passed code could not be decoded.
	 */
	public static XAExceptionCode decode(final int c) {
		final XAExceptionCode xar = CODE2ENUM.get(c);
		return xar==null ? XA_INVALID : xar;
	}

/*
ORA 3113

XAException.XAER_RMFAIL

ORA 3114

XAException.XAER_RMFAIL

ORA 24756

XAException.XAER_NOTA

ORA 24764

XAException.XA_HEURCOM

ORA 24765

XAException.XA_HEURRB

ORA 24766

XAException.XA_HEURMIX

ORA 24767

XAException.XA_RDONLY

ORA 25351

XAException.XA_RETRY

all other ORA errors

XAException.XAER_RMERR

 */
}


text:
DEFINE_string(detector, "fast", "Detector type.");

using namespace libmv;
using namespace std;

void usage() {
  LOG(ERROR) << " interest_points ImageNameIn.pgm ImageNameOut.pgm " <<std::endl
    << " ImageNameIn.pgm  : the input image on which surf features will be extrated, " << std::endl
    << " ImageNameOut.pgm : the surf keypoints will be displayed on it. " << std::endl
    << " INFO : work with pgm image only." << std::endl;
}
void DrawSurfFeatures( FloatImage & im, const libmv::vector<libmv::SurfFeature> & feat);

int main(int argc, char **argv) {
  libmv::Init("Extract surf feature from an image", &argc, &argv);

  if (argc != 3 || !(GetFormat(argv[1])==Pnm && GetFormat(argv[2])==Pnm)) {
    usage();
    LOG(ERROR) << "Missing parameters or errors in the command line.";
    return 1;
  }

  // Parse input parameter
  const string sImageIn = argv[1];
  const string sImageOut = argv[2];

  Array3Du imageIn;
  if (!ReadPnm(sImageIn.c_str(), &imageIn)) {
    LOG(FATAL) << "Failed loading image: " << sImageIn;
    return 0;
  }

  Array3Df image;
  ByteArrayToScaledFloatArray(imageIn, &image);
  // TODO(pmoulon) Assert that the image value is within [0.f;255.f]
  for(int j=0; j < image.Height(); ++j)
  for(int i=0; i < image.Width(); ++i)
    image(j,i) *=255;

  libmv::vector<libmv::SurfFeature> features;
  libmv::SurfFeatures(image, 4, 4, &features);

  DrawSurfFeatures(image, features);
  if (!WritePnm(image, sImageOut.c_str())) {
    LOG(FATAL) << "Failed saving output image: " << sImageOut;
  }

  return 0;
}

void DrawSurfFeatures( FloatImage & im, const libmv::vector<libmv::SurfFeature> & feat)
{
  std::cout << feat.size() << " Detected points " <<std::endl;
  for (int i = 0; i < feat.size(); ++i)
  {
    const libmv::SurfFeature & feature = feat[i];
    const int x = feature.x();
    const int y = feature.y();
    const float scale = 2*feature.scale;
    //std::cout << i << " " << x << " " << y << " " << feature.getScale() <<std::endl;

    DrawCircle(x, y, scale, (unsigned char)255, &im);
    const float angle = feature.orientation;
    DrawLine(x, y, x + scale * cos(angle), y + scale*sin(angle),
             (unsigned char) 255, &im);
  }
}


text:
[Firebase Custom Login](https://www.firebase.com/docs/web/guide/simple-login/custom.html)
gives you complete control over user authentication by allowing you to authenticate users
with secure JSON Web Tokens (JWTs). The auth payload stored in those tokens is available
for use in your Firebase [security rules](https://www.firebase.com/docs/security/api/rule/).
This is a token generator library for PHP which allows you to easily create those JWTs.

## Dependencies

The Firebase PHP token generator library depends on [PHP-JWT](https://github.com/firebase/php-jwt).

## A Note About Security

**IMPORTANT:** Because token generation requires your Firebase Secret, you should only generate
tokens on *trusted servers*. Never embed your Firebase Secret directly into your application and
never share your Firebase Secret with a connected client.

## Installation

Using composer:

```
composer require firebase/token-generator
```

## Generating Tokens

To generate tokens, you'll need your Firebase Secret which you can find by entering your Firebase
URL into a browser and clicking the "Secrets" tab on the left-hand navigation menu.

Once you've downloaded the library and grabbed your Firebase Secret, you can generate a token with
this snippet of PHP code:

```php
use Firebase\Token\TokenException;
use Firebase\Token\TokenGenerator;

try {
    $generator = new TokenGenerator('<YOUR_FIREBASE_SECRET>');
    $token = $generator
        ->setData(array('uid' => 'exampleID'))
        ->create();
} catch (TokenException $e) {
    echo "Error: ".$e->getMessage();
}

echo $token;
```

The payload passed to `setData()` is made available for use within your
security rules via the [`auth` variable](https://www.firebase.com/docs/security/api/rule/auth.html).
This is how you pass trusted authentication details (e.g. the client's user ID)
to your Firebase security rules. The payload can contain any data of your
choosing, however it must contain a "uid" key, which must be a string of less
than 256 characters. The generated token must be less than 1024 characters in
total.

## Token Options

Token options can be set to modify how Firebase treats the token. Available options are:

* **expires** (number or DateTime) - A timestamp (as number of seconds since the epoch) or a `DateTime`
denoting the time after which this token should no longer be valid.

* **notBefore** (number or DateTime) - A timestamp (as number of seconds since the epoch) or a `DateTime`
denoting the time before which this token should be rejected by the server.

* **admin** (boolean) - Set to `True` if you want to disable all security rules for this client.
This will provide the client with read and write access to your entire Firebase database.

* **debug** (boolean) - Set to `True` to enable debug output from your security rules. You should
generally *not* leave this set to `True` in production (as it slows down the rules implementation
and gives your users visibility into your rules), but it can be helpful for debugging.

Here is an example of how to set options:

```php
use Firebase\Token\TokenGenerator;

$generator = new TokenGenerator('<YOUR_FIREBASE_SECRET>');

// Using setOption()
$token = $generator
    ->setOption('admin', true)
    ->setOption('debug', true)
    ->setData(array('uid' => 'exampleID'))
    ->create();

// Using setOptions()
$token = $generator
    ->setOptions(array(
        'admin' => true,
        'debug' => true
    ))
    ->setData(array('uid' => 'exampleID'))
    ->create();
```

## Changelog

#### 3.0.0 - 2015-11-18
- Update PHP-JWT to >= 3.0
- Remove deprecated `Services_FirebaseTokenGenerator` and update tests
- Thanks to [@jeromegamez](https://github.com/jeromegamez) for the above contributions!

#### 2.1.0 - 2015-06-22
- Update the minimum required PHP version to >= 5.4.
- [Major package overhaul including API improvements](https://github.com/firebase/firebase-token-generator-php/pull/18)
thanks to [@jeromegamez](https://github.com/jeromegamez)!

#### 2.0.1 - 2015-04-02
- Specifying the PHP-JWT version more specifically.

#### 2.0.0 - 2014-09-15
- Additional validation to ensure tokens contain a "uid" field unless they have
the "admin" option set to `true`.

#### 1.0.0 - 2014-09-04
- Initial release


text:
// Provides control sap.ui.commons.ColorPicker.
sap.ui.define(['./library', 'sap/ui/unified/ColorPicker', "sap/base/Log"],
	function(library, UnifiedColorPicker, Log) {
	"use strict";

	/**
	 * Constructor for a new ColorPicker.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * This control gives the user the opportunity to choose a color. The color can be defined using HEX-, RGB- or HSV-values or a CSS colorname.
	 * @extends sap.ui.unified.ColorPicker
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @deprecated as of version 1.38, replaced by {@link sap.ui.unified.ColorPicker}
	 * @alias sap.ui.commons.ColorPicker
	 */
	var ColorPicker = UnifiedColorPicker.extend("sap.ui.commons.ColorPicker", /** @lends sap.ui.commons.ColorPicker.prototype */ {
		metadata : {
			deprecated : true,
			library : "sap.ui.commons"
		},
		renderer : "sap.ui.unified.ColorPickerRenderer"
	});

	try {
		sap.ui.getCore().loadLibrary("sap.ui.unified");
	} catch (e) {
		Log.error("The control 'sap.ui.commons.ColorPicker' needs library 'sap.ui.unified'.");
		throw (e);
	}

	return ColorPicker;

});


text:
'use strict';

var bcrypt = require('bcrypt-nodejs');

module.exports = function(app) {

	app.get('/login', function(req, res, next) {

		if (req.isAuthenticated()) {
			res.redirect('/');
		} else {
			res.render('login');
		}
	});

	app.post('/login', function(req, res) {

		// the following variables take the
		// data username and password from the form
		var usernameReq = req.body.username;
		var passwordReq = req.body.password;
		// knex compares the information from the form
		// with the information in the user table
		// and login the user if it is right
		app.db('users')
			.where({username: usernameReq })
				.select('password')
				.then(function(result) {
					if (!result || !result[0]) { // not found
						res.send('Wrong username!');
					}
					var hash = result[0].password;
					if (bcrypt.compareSync(passwordReq, hash)) {
						// Correct username+password.
						// Generate a new session and store their user information in the session data.
						req.session.regenerate(function() {

							req.session.user = {username: usernameReq};
							res.redirect('/')
						})
					} else {
						// Wrong username/password.
						res.send('Wrong username/password!');
					}
				}).catch(function(error) {
					console.log(error);
				}); // closing then(
	});
};


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright (C) 2014.
  ~
  ~ BaasBox - info@baasbox.com
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and limitations under the License.
  -->
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/in_comment"
        android:lines="2"
        android:hint="Comment"
        android:gravity="top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <RatingBar
        android:id="@+id/rating_comment"
        android:layout_below="@id/in_comment"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:max="5"
        style="@style/AppTheme.RatingBar"
        android:numStars="5"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin"/>
    <ImageButton
        android:padding="2dp"
        android:scaleType="centerInside"
        android:src="@drawable/ic_send"
        style="?android:actionButtonStyle"
        android:id="@+id/btn_submit_comment"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@id/btn_submit_comment"
        android:layout_below="@id/in_comment"
        android:layout_marginTop="4dp"
        android:text="Comment"
        android:textStyle="bold"
        android:layout_width="@dimen/button_size"
        android:layout_height="48dp" />

</RelativeLayout>
</merge>


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

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="zicht_admin.menu" class="Knp\Menu\MenuItem">
            <factory service="knp_menu.factory"
                     method="createItem"
            />
            <argument type="string">zicht_admin.root</argument>

            <tag name="knp_menu.menu" alias="zicht_admin"/>
        </service>

        <prototype namespace="Zicht\Bundle\AdminBundle\Controller\" resource="../../Controller/" exclude="../../Controller/RcController.php" autowire="true" public="true">
            <tag name="controller.service_arguments" />
            <tag name="container.service_subscriber" />
            <call method="setContainer">
                <argument type="service" id="Psr\Container\ContainerInterface" />
            </call>
        </prototype>

        <service id="zicht_admin.event_subscriber" class="Zicht\Bundle\AdminBundle\Event\Subscriber">
            <argument type="service" id="zicht_admin.menu"/>
            <argument type="service" id="knp_menu.factory"/>
            <tag name="kernel.event_subscriber"/>
        </service>
        <service id="zicht_admin.event_propagator" class="Zicht\Bundle\AdminBundle\Event\Propagator">
        </service>
        <service id="zicht_admin.twig_extension" class="Zicht\Bundle\AdminBundle\Twig\Extension">
            <tag name="twig.extension"/>
            <argument type="service" id="sonata.admin.pool"/>
            <argument type="service" id="doctrine"/>
        </service>
        <service id="zicht_admin.form.tinymce" class="Zicht\Bundle\AdminBundle\Form\TinymceType">
            <tag name="form.type" alias="tinymce"/>
        </service>

        <service id="zicht_admin.security.authorization.voter.admin_voter"
                 class="Zicht\Bundle\AdminBundle\Security\Voter\AdminVoter"
                 public="false">
            <argument type="collection"/><!-- replaced by extension -->
            <argument type="service" id="sonata.admin.pool"/>
            <argument type="service" id="security.access.decision_manager"/>
            <argument type="service" id="sonata.admin.security.handler"/>
            <tag name="security.voter"/>
        </service>
        <service id="zicht_admin.form.date_picker" class="Zicht\Bundle\AdminBundle\Form\DatePickerType">
            <tag name="form.type" alias="zicht_date_picker"/>
        </service>
        <service id="zicht_admin.form.override_object" class="Zicht\Bundle\AdminBundle\Form\OverrideObjectType">
            <tag name="form.type" alias="zicht_override_object"/>
        </service>
        <service id="zicht_admin.form.buttons" class="Zicht\Bundle\AdminBundle\Form\ButtonsType">
            <tag name="form.type" alias="zicht_buttons"/>
        </service>

        <service id="Zicht\Bundle\AdminBundle\AdminMenu\EventPropagationBuilder">
            <argument type="service" id="request_stack"/>
            <argument/> <!-- added by Extension -->
            <argument type="service" id="event_dispatcher"/>
            <tag name="zicht_admin.event_propagation" event="zicht_page.view"/>
        </service>

        <service id="Zicht\Bundle\AdminBundle\Command\DumpRoleHierarchyCommand">
            <tag name="console.command"/>
            <argument type="service" id="sonata.admin.pool"/>
            <argument type="service" id="sonata.admin.security.handler"/>
        </service>

    </services>
</container>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Trichothecium fuligineum Spreng.

### Remarks
null


text:
package com.impossibl.postgres.system.procs;

import com.impossibl.postgres.system.Context;
import com.impossibl.postgres.types.PrimitiveType;
import com.impossibl.postgres.types.Type;

import java.io.IOException;
import java.sql.SQLException;

import org.postgis.PGbox2d;

/** Optional adapter for postgis box2d datatypes. Requires postgis-jdbc jar */
public class PostgisBox2ds extends SimpleProcProvider implements OptionalProcProvider {

  public PostgisBox2ds() {
    super(new TxtEncoder(), new TxtDecoder(), null, null, "box2d_");
  }

  static class TxtEncoder extends TextEncoder {

    @Override
    public Class<?> getInputType() {
      return PGbox2d.class;
    }

    @Override
    public PrimitiveType getOutputPrimitiveType() {
      return PrimitiveType.Binary;
    }

    @Override
    public void encode(Type type, StringBuilder buffer, Object val, Context context) throws IOException {
      PGbox2d g = (PGbox2d) val;
      buffer.append(g.getValue());
    }

  }

  static class TxtDecoder extends TextDecoder {

    @Override
    public PrimitiveType getInputPrimitiveType() {
      return PrimitiveType.Binary;
    }

    @Override
    public Class<?> getOutputType() {
      return PGbox2d.class;
    }

    @Override
    protected Object decode(Type type, Short typeLength, Integer typeModifier, CharSequence buffer, Context context) throws IOException {
      try {
        return new PGbox2d(buffer.toString());
      }
      catch (SQLException e) {
        /*
         * dependency on SQLException in PGgeometry class. Not generated by driver, but used for communicating
         * validation errors by postgis library
         */
        throw new IOException("Exception thrown by postgis library", e);
      }

    }
  }

}


text:
namespace MBox
{
    namespace ShimsApi
    {
        namespace WFP
        {
            //
            // Engine Manager
            //

            ShimsApi$CompileTime$DeclareApi$5$Macro(
                FwpmEngineOpen0, NTSTATUS, __stdcall,
                const wchar_t*, aServerName,
                UINT32, aAuthnService,
                SEC_WINNT_AUTH_IDENTITY_W*, aAuthIdentity,
                const FWPM_SESSION0*, aSession,
                HANDLE*, aEngineHandle);

            ShimsApi$CompileTime$DeclareApi$1$Macro(
                FwpmEngineClose0, NTSTATUS, __stdcall,
                HANDLE, aEngineHandle);

        }
    }
}


text:
<div id="{{ stars_id}}" class="stars-wrapper {{ extra_class }}">
  <select name="selrate">
    {% for score in scores %}
      <option value="{{ score }}" {% ifequal rating score %}selected="selected"{% endifequal %} >{{ score }}</option>
    {% endfor %}
  </select>
</div>
<script type="text/javascript">
$(function() {

  $("#{{ stars_id }}").initialStars('select',
				'{% url rate object_id=object.id,field_name=field_name,score='score',content_type_id=content_type_id %}',
      			{% if disabled %}true{% else %}''{% endif %},
      			{{ starWidth }}
      			{% if extra_success %},{{ extra_success|safe }}{% endif %}
      			);

});
</script>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace BotwTrainer.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("")]
        public string IpAddress {
            get {
                return ((string)(this["IpAddress"]));
            }
            set {
                this["IpAddress"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("https://raw.githubusercontent.com/joffnerd/botw-trainer/master/")]
        public string VersionUrl {
            get {
                return ((string)(this["VersionUrl"]));
            }
            set {
                this["VersionUrl"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("3.7.1")]
        public string CurrentVersion {
            get {
                return ((string)(this["CurrentVersion"]));
            }
            set {
                this["CurrentVersion"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("0")]
        public int Warning {
            get {
                return ((int)(this["Warning"]));
            }
            set {
                this["Warning"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("Pro")]
        public string Controller {
            get {
                return ((string)(this["Controller"]));
            }
            set {
                this["Controller"] = value;
            }
        }
    }
}


text:
package com.cloud.test;

import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.UUID;
import java.util.Vector;

import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.net.NetUtils;

public class IPRangeConfig {

    public static void main(String[] args) {
        IPRangeConfig config = ComponentContext.inject(IPRangeConfig.class);
        config.run(args);
        System.exit(0);
    }

    private String usage() {
        return "Usage: ./change_ip_range.sh [add|delete] [public zone | private pod zone] startIP endIP";
    }

    public void run(String[] args) {
        if (args.length < 2) {
            printError(usage());
        }

        String op = args[0];
        String type = args[1];

        if (type.equals("public")) {
            if (args.length != 4 && args.length != 5) {
                printError(usage());
            }
            String zone = args[2];
            String startIP = args[3];
            String endIP = null;
            if (args.length == 5) {
                endIP = args[4];
            }

            String result = checkErrors(type, op, null, zone, startIP, endIP);
            if (!result.equals("success")) {
                printError(result);
            }

            long zoneId = PodZoneConfig.getZoneId(zone);
            result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, -1);
            result = result.replaceAll("
", "/n");
            System.out.println(result);
        } else if (type.equals("private")) {
            if (args.length != 5 && args.length != 6) {
                printError(usage());
            }
            String pod = args[2];
            String zone = args[3];
            ;
            String startIP = args[4];
            String endIP = null;
            if (args.length == 6) {
                endIP = args[5];
            }

            String result = checkErrors(type, op, pod, zone, startIP, endIP);
            if (!result.equals("success")) {
                printError(result);
            }

            long podId = PodZoneConfig.getPodId(pod, zone);
            long zoneId = PodZoneConfig.getZoneId(zone);
            result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1);
            result = result.replaceAll("
", "/n");
            System.out.println(result);
        } else {
            printError(usage());
        }
    }

    public List<String> changePublicIPRangeGUI(String op, String zone, String startIP, String endIP, long physicalNetworkId) {
        String result = checkErrors("public", op, null, zone, startIP, endIP);
        if (!result.equals("success")) {
            return DatabaseConfig.genReturnList("false", result);
        }

        long zoneId = PodZoneConfig.getZoneId(zone);
        result = changeRange(op, "public", -1, zoneId, startIP, endIP, null, physicalNetworkId);

        return DatabaseConfig.genReturnList("true", result);
    }

    public List<String> changePrivateIPRangeGUI(String op, String pod, String zone, String startIP, String endIP) {
        String result = checkErrors("private", op, pod, zone, startIP, endIP);
        if (!result.equals("success")) {
            return DatabaseConfig.genReturnList("false", result);
        }

        long podId = PodZoneConfig.getPodId(pod, zone);
        long zoneId = PodZoneConfig.getZoneId(zone);
        result = changeRange(op, "private", podId, zoneId, startIP, endIP, null, -1);

        return DatabaseConfig.genReturnList("true", result);
    }

    private String checkErrors(String type, String op, String pod, String zone, String startIP, String endIP) {
        if (!op.equals("add") && !op.equals("delete")) {
            return usage();
        }

        if (type.equals("public")) {
            // Check that the zone is valid
            if (!PodZoneConfig.validZone(zone)) {
                return "Please specify a valid zone.";
            }
        } else if (type.equals("private")) {
            // Check that the pod and zone are valid
            if (!PodZoneConfig.validZone(zone)) {
                return "Please specify a valid zone.";
            }
            if (!PodZoneConfig.validPod(pod, zone)) {
                return "Please specify a valid pod.";
            }
        }

        if (!validIP(startIP)) {
            return "Please specify a valid start IP";
        }

        if (!validOrBlankIP(endIP)) {
            return "Please specify a valid end IP";
        }

        // Check that the IPs that are being added are compatible with either the zone's public netmask, or the pod's CIDR
        if (type.equals("public")) {
            // String publicNetmask = getPublicNetmask(zone);
            // String publicGateway = getPublicGateway(zone);

            // if (publicNetmask == null) return "Please ensure that your zone's public net mask is specified";
            // if (!sameSubnet(startIP, endIP, publicNetmask)) return "Please ensure that your start IP and end IP are in the same subnet, as per the zone's netmask.";
            // if (!sameSubnet(startIP, publicGateway, publicNetmask)) return "Please ensure that your start IP is in the same subnet as your zone's gateway, as per the zone's netmask.";
            // if (!sameSubnet(endIP, publicGateway, publicNetmask)) return "Please ensure that your end IP is in the same subnet as your zone's gateway, as per the zone's netmask.";
        } else if (type.equals("private")) {
            String cidrAddress = getCidrAddress(pod, zone);
            long cidrSize = getCidrSize(pod, zone);

            if (!sameSubnetCIDR(startIP, endIP, cidrSize)) {
                return "Please ensure that your start IP and end IP are in the same subnet, as per the pod's CIDR size.";
            }
            if (!sameSubnetCIDR(startIP, cidrAddress, cidrSize)) {
                return "Please ensure that your start IP is in the same subnet as the pod's CIDR address.";
            }
            if (!sameSubnetCIDR(endIP, cidrAddress, cidrSize)) {
                return "Please ensure that your end IP is in the same subnet as the pod's CIDR address.";
            }
        }

        if (!validIPRange(startIP, endIP)) {
            return "Please specify a valid IP range.";
        }

        return "success";
    }

    private String genChangeRangeSuccessString(List<String> problemIPs, String op) {
        if (problemIPs == null) {
            return "";
        }

        if (problemIPs.size() == 0) {
            if (op.equals("add")) {
                return "Successfully added all IPs in the specified range.";
            } else if (op.equals("delete")) {
                return "Successfully deleted all IPs in the specified range.";
            } else {
                return "";
            }
        } else {
            String successString = "";
            if (op.equals("add")) {
                successString += "Failed to add the following IPs, because they are already in the database:

";
            } else if (op.equals("delete")) {
                successString += "Failed to delete the following IPs, because they are in use:

";
            }

            for (int i = 0; i < problemIPs.size(); i++) {
                successString += problemIPs.get(i);
                if (i != (problemIPs.size() - 1)) {
                    successString += ", ";
                }
            }

            successString += "

";

            if (op.equals("add")) {
                successString += "Successfully added all other IPs in the specified range.";
            } else if (op.equals("delete")) {
                successString += "Successfully deleted all other IPs in the specified range.";
            }

            return successString;
        }
    }

    private String changeRange(String op, String type, long podId, long zoneId, String startIP, String endIP, Long networkId, long physicalNetworkId) {

        // Go through all the IPs and add or delete them
        List<String> problemIPs = null;
        if (op.equals("add")) {
            problemIPs = saveIPRange(type, podId, zoneId, 1, startIP, endIP, networkId, physicalNetworkId);
        } else if (op.equals("delete")) {
            problemIPs = deleteIPRange(type, podId, zoneId, 1, startIP, endIP);
        }

        if (problemIPs == null) {
            return null;
        } else {
            return genChangeRangeSuccessString(problemIPs, op);
        }
    }

    private String genSuccessString(Vector<String> problemIPs, String op) {
        if (problemIPs == null) {
            return "";
        }

        if (problemIPs.size() == 0) {
            if (op.equals("add")) {
                return "Successfully added all IPs in the specified range.";
            } else if (op.equals("delete")) {
                return "Successfully deleted all IPs in the specified range.";
            } else {
                return "";
            }
        } else {
            String successString = "";
            if (op.equals("add")) {
                successString += "Failed to add the following IPs, because they are already in the database:

";
            } else if (op.equals("delete")) {
                successString += "Failed to delete the following IPs, because they are in use:

";
            }

            for (int i = 0; i < problemIPs.size(); i++) {
                successString += problemIPs.elementAt(i);
                if (i != (problemIPs.size() - 1)) {
                    successString += ", ";
                }
            }

            successString += "

";

            if (op.equals("add")) {
                successString += "Successfully added all other IPs in the specified range.";
            } else if (op.equals("delete")) {
                successString += "Successfully deleted all other IPs in the specified range.";
            }

            return successString;
        }
    }

    public static String getCidrAddress(String pod, String zone) {
        long dcId = PodZoneConfig.getZoneId(zone);
        String selectSql = "SELECT * FROM `cloud`.`host_pod_ref` WHERE name = \"" + pod + "\" AND data_center_id = \"" + dcId + "\"";
        String errorMsg = "Could not read CIDR address for pod/zone: " + pod + "/" + zone + " from database. Please contact Cloud Support.";
        return DatabaseConfig.getDatabaseValueString(selectSql, "cidr_address", errorMsg);
    }

    public static long getCidrSize(String pod, String zone) {
        long dcId = PodZoneConfig.getZoneId(zone);
        String selectSql = "SELECT * FROM `cloud`.`host_pod_ref` WHERE name = \"" + pod + "\" AND data_center_id = \"" + dcId + "\"";
        String errorMsg = "Could not read CIDR address for pod/zone: " + pod + "/" + zone + " from database. Please contact Cloud Support.";
        return DatabaseConfig.getDatabaseValueLong(selectSql, "cidr_size", errorMsg);
    }

    @DB
    protected Vector<String> deleteIPRange(String type, long podId, long zoneId, long vlanDbId, String startIP, String endIP) {
        long startIPLong = NetUtils.ip2Long(startIP);
        long endIPLong = startIPLong;
        if (endIP != null) {
            endIPLong = NetUtils.ip2Long(endIP);
        }

        TransactionLegacy txn = TransactionLegacy.currentTxn();
        Vector<String> problemIPs = null;
        if (type.equals("public")) {
            problemIPs = deletePublicIPRange(txn, startIPLong, endIPLong, vlanDbId);
        } else if (type.equals("private")) {
            problemIPs = deletePrivateIPRange(txn, startIPLong, endIPLong, podId, zoneId);
        }

        return problemIPs;
    }

    private Vector<String> deletePublicIPRange(TransactionLegacy txn, long startIP, long endIP, long vlanDbId) {
        String deleteSql = "DELETE FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_id = ?";
        String isPublicIPAllocatedSelectSql = "SELECT * FROM `cloud`.`user_ip_address` WHERE public_ip_address = ? AND vlan_id = ?";

        Vector<String> problemIPs = new Vector<String>();
        Connection conn = null;
        try {
            conn = txn.getConnection();
        }
        catch (SQLException e) {
            System.out.println("deletePublicIPRange. Exception: " +e.getMessage());
            return null;
        }
        try(PreparedStatement stmt = conn.prepareStatement(deleteSql);
            PreparedStatement isAllocatedStmt = conn.prepareStatement(isPublicIPAllocatedSelectSql);) {
            while (startIP <= endIP) {
                if (!isPublicIPAllocated(startIP, vlanDbId, isAllocatedStmt)) {
                        stmt.clearParameters();
                        stmt.setLong(1, startIP);
                        stmt.setLong(2, vlanDbId);
                        stmt.executeUpdate();
                    }
                else {
                    problemIPs.add(NetUtils.long2Ip(startIP));
                }
                startIP += 1;
            }
        }catch (Exception ex) {
           System.out.println("deletePublicIPRange. Exception: " +ex.getMessage());
           return null;
        }

        return problemIPs;
    }

    private Vector<String> deletePrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
        String deleteSql = "DELETE FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND pod_id = ? AND data_center_id = ?";
        String isPrivateIPAllocatedSelectSql = "SELECT * FROM `cloud`.`op_dc_ip_address_alloc` WHERE ip_address = ? AND data_center_id = ? AND pod_id = ?";
        Vector<String> problemIPs = new Vector<String>();
        try {
            Connection conn = txn.getConnection();
            try (PreparedStatement stmt = conn.prepareStatement(deleteSql);
                 PreparedStatement isAllocatedStmt = conn.prepareStatement(isPrivateIPAllocatedSelectSql);) {
                while (startIP <= endIP) {
                    if (!isPrivateIPAllocated(NetUtils.long2Ip(startIP), podId, zoneId, isAllocatedStmt)) {
                        stmt.clearParameters();
                        stmt.setString(1, NetUtils.long2Ip(startIP));
                        stmt.setLong(2, podId);
                        stmt.setLong(3, zoneId);
                        stmt.executeUpdate();
                    } else {
                        problemIPs.add(NetUtils.long2Ip(startIP));
                    }
                    startIP += 1;
                }
            } catch (SQLException e) {
                System.out.println("deletePrivateIPRange. Exception: " + e.getMessage());
                printError("deletePrivateIPRange. Exception: " + e.getMessage());
            }
        }catch (SQLException e) {
            System.out.println("deletePrivateIPRange. Exception: " + e.getMessage());
            printError("deletePrivateIPRange. Exception: " + e.getMessage());
        }
        return problemIPs;
    }

    private boolean isPublicIPAllocated(long ip, long vlanDbId, PreparedStatement stmt) {
        try(ResultSet rs = stmt.executeQuery();) {
            stmt.clearParameters();
            stmt.setLong(1, ip);
            stmt.setLong(2, vlanDbId);
            if (rs.next()) {
                return (rs.getString("allocated") != null);
            } else {
                return false;
            }
        }
        catch (SQLException ex) {
            System.out.println(ex.getMessage());
            return true;
        }
    }

    private boolean isPrivateIPAllocated(String ip, long podId, long zoneId, PreparedStatement stmt) {
        try {
            stmt.clearParameters();
            stmt.setString(1, ip);
            stmt.setLong(2, zoneId);
            stmt.setLong(3, podId);
            try(ResultSet rs = stmt.executeQuery();) {
                if (rs.next()) {
                    return (rs.getString("taken") != null);
                } else {
                    return false;
                }
            }
            catch (Exception ex) {
                System.out.println(ex.getMessage());
                return true;
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
            return true;
        }
    }

    @DB
    public List<String> saveIPRange(String type, long podId, long zoneId, long vlanDbId, String startIP, String endIP, Long sourceNetworkId, long physicalNetworkId) {
        long startIPLong = NetUtils.ip2Long(startIP);
        long endIPLong = startIPLong;
        if (endIP != null) {
            endIPLong = NetUtils.ip2Long(endIP);
        }

        TransactionLegacy txn = TransactionLegacy.currentTxn();
        List<String> problemIPs = null;

        if (type.equals("public")) {
            problemIPs = savePublicIPRange(txn, startIPLong, endIPLong, zoneId, vlanDbId, sourceNetworkId, physicalNetworkId, false);
        } else if (type.equals("private")) {
            problemIPs = savePrivateIPRange(txn, startIPLong, endIPLong, podId, zoneId);
        }

        String[] linkLocalIps = NetUtils.getLinkLocalIPRange(10);
        long startLinkLocalIp = NetUtils.ip2Long(linkLocalIps[0]);
        long endLinkLocalIp = NetUtils.ip2Long(linkLocalIps[1]);

        saveLinkLocalPrivateIPRange(txn, startLinkLocalIp, endLinkLocalIp, podId, zoneId);

        return problemIPs;
    }

    public Vector<String> savePublicIPRange(TransactionLegacy txn, long startIP, long endIP, long zoneId, long vlanDbId, Long sourceNetworkId, long physicalNetworkId, boolean forSystemVms) {
        String insertSql =
            "INSERT INTO `cloud`.`user_ip_address` (public_ip_address, data_center_id, vlan_db_id, mac_address, source_network_id, physical_network_id, uuid, forsystemvms) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?, ?, ?, ?)";
        String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
        Vector<String> problemIPs = new Vector<String>();

        Connection conn = null;
        try {
            conn = txn.getConnection();
        } catch (SQLException e) {
            return null;
        }
        while (startIP <= endIP) {
            try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql);
            PreparedStatement update_stmt = conn.prepareStatement(updateSql);
            ){
                insert_stmt.setString(1, NetUtils.long2Ip(startIP));
                insert_stmt.setLong(2, zoneId);
                insert_stmt.setLong(3, vlanDbId);
                insert_stmt.setLong(4, zoneId);
                insert_stmt.setLong(5, sourceNetworkId);
                insert_stmt.setLong(6, physicalNetworkId);
                insert_stmt.setString(7, UUID.randomUUID().toString());
                insert_stmt.setBoolean(8, forSystemVms);
                insert_stmt.executeUpdate();
                update_stmt.setLong(1, zoneId);
                update_stmt.executeUpdate();
            } catch (Exception ex) {
                problemIPs.add(NetUtils.long2Ip(startIP));
            }
            startIP++;
        }

        return problemIPs;
    }

    public List<String> savePrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
        String insertSql =
            "INSERT INTO `cloud`.`op_dc_ip_address_alloc` (ip_address, data_center_id, pod_id, mac_address) VALUES (?, ?, ?, (select mac_address from `cloud`.`data_center` where id=?))";
        String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
        Vector<String> problemIPs = new Vector<String>();

        try {
            Connection conn = txn.getConnection();
            while (startIP <= endIP) {
                try (PreparedStatement insert_stmt = conn.prepareStatement(insertSql);
                     PreparedStatement update_stmt = conn.prepareStatement(updateSql);
                )
                {
                    insert_stmt.setString(1, NetUtils.long2Ip(startIP));
                    insert_stmt.setLong(2, zoneId);
                    insert_stmt.setLong(3, podId);
                    insert_stmt.setLong(4, zoneId);
                    insert_stmt.executeUpdate();
                    update_stmt.setLong(1, zoneId);
                    update_stmt.executeUpdate();
                } catch (Exception e) {
                    problemIPs.add(NetUtils.long2Ip(startIP));
                }
                startIP++;
            }
        } catch (Exception ex) {
            System.out.print(ex.getMessage());
            ex.printStackTrace();
        }

        return problemIPs;
    }

    private Vector<String> saveLinkLocalPrivateIPRange(TransactionLegacy txn, long startIP, long endIP, long podId, long zoneId) {
        String insertSql = "INSERT INTO `cloud`.`op_dc_link_local_ip_address_alloc` (ip_address, data_center_id, pod_id) VALUES (?, ?, ?)";
        Vector<String> problemIPs = new Vector<String>();

        Connection conn = null;
        try {
            conn = txn.getConnection();
        } catch (SQLException e) {
            System.out.println("Exception: " + e.getMessage());
            printError("Unable to start DB connection to save private IPs. Please contact Cloud Support.");
        }
        long start = startIP;

        try(PreparedStatement stmt = conn.prepareStatement(insertSql);)
        {
            while (startIP <= endIP) {
                stmt.setString(1, NetUtils.long2Ip(startIP++));
                stmt.setLong(2, zoneId);
                stmt.setLong(3, podId);
                stmt.addBatch();
            }
            int[] results = stmt.executeBatch();
            for (int i = 0; i < results.length; i += 2) {
                if (results[i] == Statement.EXECUTE_FAILED) {
                    problemIPs.add(NetUtils.long2Ip(start + (i / 2)));
                }
            }
        } catch (Exception ex) {
            System.out.println("saveLinkLocalPrivateIPRange. Exception: " + ex.getMessage());
        }
        return problemIPs;
    }

    public static String getPublicNetmask(String zone) {
        return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE name = \"" + zone + "\"", "netmask",
            "Unable to start DB connection to read public netmask. Please contact Cloud Support.");
    }

    public static String getPublicGateway(String zone) {
        return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE name = \"" + zone + "\"", "gateway",
            "Unable to start DB connection to read public gateway. Please contact Cloud Support.");
    }

    public static String getGuestNetworkCidr(Long zoneId) {
        return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE id = \"" + zoneId + "\"", "guest_network_cidr",
            "Unable to start DB connection to read guest cidr network. Please contact Cloud Support.");
    }

    public static boolean validCIDR(final String cidr) {
        if (cidr == null || cidr.isEmpty()) {
            return false;
        }
        String[] cidrPair = cidr.split("\\/");
        if (cidrPair.length != 2) {
            return false;
        }
        String cidrAddress = cidrPair[0];
        String cidrSize = cidrPair[1];
        if (!validIP(cidrAddress)) {
            return false;
        }
        int cidrSizeNum = -1;

        try {
            cidrSizeNum = Integer.parseInt(cidrSize);
        } catch (Exception e) {
            return false;
        }

        if (cidrSizeNum < 1 || cidrSizeNum > 32) {
            return false;
        }

        return true;
    }

    public static boolean validOrBlankIP(final String ip) {
        if (ip == null || ip.isEmpty()) {
            return true;
        }
        return validIP(ip);
    }

    public static boolean validIP(final String ip) {
        final String[] ipAsList = ip.split("\\.");

        // The IP address must have four octets
        if (Array.getLength(ipAsList) != 4) {
            return false;
        }

        for (int i = 0; i < 4; i++) {
            // Each octet must be an integer
            final String octetString = ipAsList[i];
            int octet;
            try {
                octet = Integer.parseInt(octetString);
            } catch (final Exception e) {
                return false;
            }
            // Each octet must be between 0 and 255, inclusive
            if (octet < 0 || octet > 255) {
                return false;
            }

            // Each octetString must have between 1 and 3 characters
            if (octetString.length() < 1 || octetString.length() > 3) {
                return false;
            }

        }

        // IP is good, return true
        return true;
    }

    public static boolean validIPRange(String startIP, String endIP) {
        if (endIP == null || endIP.isEmpty()) {
            return true;
        }

        long startIPLong = NetUtils.ip2Long(startIP);
        long endIPLong = NetUtils.ip2Long(endIP);
        return (startIPLong < endIPLong);
    }

    public static boolean sameSubnet(final String ip1, final String ip2, final String netmask) {
        if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
            return true;
        }
        String subnet1 = NetUtils.getSubNet(ip1, netmask);
        String subnet2 = NetUtils.getSubNet(ip2, netmask);

        return (subnet1.equals(subnet2));
    }

    public static boolean sameSubnetCIDR(final String ip1, final String ip2, final long cidrSize) {
        if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
            return true;
        }
        String subnet1 = NetUtils.getCidrSubNet(ip1, cidrSize);
        String subnet2 = NetUtils.getCidrSubNet(ip2, cidrSize);

        return (subnet1.equals(subnet2));
    }

    private static void printError(String message) {
        DatabaseConfig.printError(message);
    }

}


text:
package me.bayes.sitemap.util;

import me.bayes.sitemap.exception.ExceptionCode;
import me.bayes.sitemap.exception.SystemException;
import me.bayes.sitemap.model.SiteUrl;
import me.bayes.sitemap.repository.SiteMapRepository;
import me.bayes.sitemap.xsd.sitemap.TChangeFreq;
import me.bayes.sitemap.xsd.sitemap.TUrl;
import me.bayes.sitemap.xsd.sitemap.Urlset;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static me.bayes.sitemap.util.JaxbUtil.SiteMap.factory;
import static me.bayes.sitemap.vertx.SitemapMod.Context.log;

/**
 * Created by kevinbayes on 2014/12/01.
 */
public class UrlSetBuilder {

    public static UrlSetBuilder instance(SiteMapRepository repository) {
        return new UrlSetBuilder(repository);
    }

    private List<SiteUrl> urls = new ArrayList<>();
    private SiteMapRepository repository;

    private UrlSetBuilder(SiteMapRepository repository) {
        this.repository = repository;
    }

    public UrlSetBuilder with(SiteUrl siteUrl) {
        urls.add(siteUrl);
        return this;
    }

    public void write() {
        repository.update(urls);
    }
}


text:
package edu.usc.ict.superglu.util.tokenformat;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.json.simple.DeserializationException;
import org.json.simple.JsonArray;
import org.json.simple.JsonObject;
import org.json.simple.Jsoner;

import edu.usc.ict.superglu.util.StorageToken;

/**
 * This will convert a storageToken into standard JSON
 *
 * @author auerbach
 *
 */

public class JSONStandardRWFormat extends TokenRWFormat {

	private static Map<String, Class<?>> NAME_MAPPING = new HashMap<>();

	private static Map<Class<?>, String> TYPE_MAPPING = new HashMap<>();

	static {
		NAME_MAPPING.put("bool", Boolean.class);
		NAME_MAPPING.put("unicode", String.class);
		NAME_MAPPING.put("float", Float.class);
		NAME_MAPPING.put("int", Integer.class);
		NAME_MAPPING.put("tuple", List.class);
		NAME_MAPPING.put("long", Long.class);

		TYPE_MAPPING.put(Boolean.class, "bool");
		TYPE_MAPPING.put(String.class, "unicode");
		TYPE_MAPPING.put(Float.class, "float");
		TYPE_MAPPING.put(BigDecimal.class, "float");
		TYPE_MAPPING.put(Double.class, "float");
		TYPE_MAPPING.put(Short.class, "int");
		TYPE_MAPPING.put(Integer.class, "int");
		TYPE_MAPPING.put(Long.class, "long");

	}

	// """ Parse a string into Storage Tokens """
	public static StorageToken parse(String input) {
		try {
			Object rawParseResults = Jsoner.deserialize(input);
			Object nativeObject = makeNative(rawParseResults);

			StorageToken result;
			if (nativeObject instanceof StorageToken)
				result = (StorageToken) nativeObject;
			else if (nativeObject instanceof Map<?, ?>) // TODO: what should the
														// classID be?
				result = new StorageToken((Map<String, Object>) nativeObject, null, null);
			else {
				Map<String, Object> data = new HashMap<>();
				data.put("data", nativeObject);
				result = new StorageToken(data, null, null);
			}
			return result;
		} catch (DeserializationException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	// """ Serialize Storage Token objects into a string form """
	public static String serialize(StorageToken data) {
		Object processedObject = makeSerializable(data);
		Map<?, ?> processedObjectAsMap = (Map<?, ?>) processedObject;
		String result = Jsoner.serialize(processedObjectAsMap);
		return result;
	}

	private static Object makeSerializable(Object data) {
		if (data == null)
			return data;

		Class<?> clazz = data.getClass();

		if (VALID_ATOMIC_VALUE_TYPES.contains(clazz))
			return data;

		if (VALID_SEQUENCE_TYPES.contains(clazz)) {
			Collection<Object> dataAsCollection = (Collection<Object>) data;

			List<Object> sequenceData = new ArrayList<>();

			for (Object o : dataAsCollection)
				sequenceData.add(makeSerializable(o));

			return sequenceData;

		}
		if (VALID_MAPPING_TYPES.contains(clazz)) {
			Map<Object, Object> dataAsMap = (Map<Object, Object>) data;
			Map<Object, Object> processedMap = new HashMap<>();

			for (Entry<Object, Object> entry : dataAsMap.entrySet()) {
				processedMap.put(makeSerializable(entry.getKey()), makeSerializable(entry.getValue()));
			}

			processedMap.put("isMap", true);

			return processedMap;
		}
		if (clazz.equals(StorageToken.class)) {
			StorageToken dataAsStorageToken = (StorageToken) data;

			Map<String, Map<String, Object>> processedStorageToken = new HashMap<>();
			Map<String, Object> storageTokenChildren = new HashMap<>();

			for (String key : dataAsStorageToken) {
				Object value = dataAsStorageToken.getItem(key);
				storageTokenChildren.put(key, makeSerializable(value));
			}

//			if (dataAsStorageToken.getClassId() != null) {
//				processedStorageToken.put(dataAsStorageToken.getClassId(), storageTokenChildren);
//				return processedStorageToken;
	//		} else {
				return storageTokenChildren;
		//	}
		}

		throw new RuntimeException("Tried to serialize unserializeable object of type " + clazz.toString());
	}

	// remember to check for null values. Python code didn't have to explicitly
	// do so.
	private static Object makeNative(Object input) {
		if (isNullOrPrimitive(input))
			return input;

		if (input instanceof JsonArray) {
			List<Object> result = new ArrayList<>();

			for (Object currentElement : (JsonArray) input) {
				result.add(makeNative(currentElement));
			}

			return result;
		}

		else if (input instanceof JsonObject) {
			JsonObject inputAsJsonObject = (JsonObject) input;

			// corner case if object is empty
			if (inputAsJsonObject.isEmpty())
				return new HashMap<String, Object>();

			String datatypeName = inputAsJsonObject.keySet().iterator().next();

			Class<?> dataType = NAME_MAPPING.getOrDefault(datatypeName, StorageToken.class);

			if (!((JsonObject) input).containsKey("isMap")) {// We are deserializing an
														// object

				Map<String, Object> nativizedData = new HashMap<>();
				for (String key : inputAsJsonObject.keySet()) {
					Object value = inputAsJsonObject.get(key);

					if (isNullOrPrimitive(value)) {
						nativizedData.put(key, value);
					} else {

						if (value instanceof JsonObject) {
							Object nativeValue = makeNative(value);

							nativizedData.put(key, nativeValue);

						} else if (value instanceof JsonArray) {

							Object nativizedValue = makeNative(value);

							nativizedData.put(key, nativizedValue);
						}
					}
				}

				StorageToken result = new StorageToken(nativizedData, null, (String) nativizedData.get(StorageToken.CLASS_ID_KEY));
				return result;
			}

			else {// We are deserializing a Map

				Map<Object, Object> result = new HashMap<>();

				for (Object key : inputAsJsonObject.keySet()) {
					if(!key.equals("isMap"))
					{
						Object value = inputAsJsonObject.get(key);

						Object nativizedKey = makeNative(key);
						Object nativizedValue = makeNative(value);
						result.put(nativizedKey, nativizedValue);
					}
				}

				return result;
			}
		}

		// should never reach here
		return null;
	}
}


text:
**Markdown** es una curiosa herramienta para darle mucho _estilo_ a nuestros documentos
con ella podemos hacer listas personalizadas:

* como esto
* y esto
* y tambien esto.

y tambien listas con numeros ! **(Damn!)**:

1. Esto es bool
2. Esto tambien
3. y finalmente esto!

Tambien podemos citar (Eso era , citar):
> _"Aqui va la frase que desee citar"_

y hasta podemos poner imagenes!:

![aliencliffjav](https://avatars2.githubusercontent.com/u/12130544?v=3&s=460)

Tambien es ~~Cool~~ Bool Subrayar

y explicar comandos , tambien esta bool:

```javascript

 alert(omg esto si esta bien raro!);

```
Algunos cuadros tampoco estan mal

Esto no esta mal | ni esto tampoco
-----------------|----------------
mucho menos esto | ni esto

**_si quieres puedes pasarte por mi [perfil](https://github.com/cliffjav)_**

Es una herramienta bool (_hay que admitirlo_) y muy facil de manejar :3

##**_Escrito por: Javier Collazos (cliffjav)_**


text:
namespace Application.DataAccessFramework
{
    using System;
    using System.Collections.Generic;

    public partial class Product
    {
        public Product()
        {
            this.SalesOrderDetails = new HashSet<SalesOrderDetail>();
        }

        public int ProductID { get; set; }
        public string Name { get; set; }
        public string ProductNumber { get; set; }
        public string Color { get; set; }
        public decimal StandardCost { get; set; }
        public decimal ListPrice { get; set; }
        public string Size { get; set; }
        public Nullable<decimal> Weight { get; set; }
        public Nullable<int> ProductCategoryID { get; set; }
        public Nullable<int> ProductModelID { get; set; }
        public System.DateTime SellStartDate { get; set; }
        public Nullable<System.DateTime> SellEndDate { get; set; }
        public Nullable<System.DateTime> DiscontinuedDate { get; set; }
        public byte[] ThumbNailPhoto { get; set; }
        public string ThumbnailPhotoFileName { get; set; }
        public System.Guid rowguid { get; set; }
        public System.DateTime ModifiedDate { get; set; }

        public virtual ProductCategory ProductCategory { get; set; }
        public virtual ProductModel ProductModel { get; set; }
        public virtual ICollection<SalesOrderDetail> SalesOrderDetails { get; set; }
    }
}


text:
Danger, Will Robinson!

Hmmm...something went wrong:

      Error <?php echo $_SESSION['error_code']; ?>: <?php echo  $_SESSION['error_message'];?>

        <a href="<?php echo $cfg_url_base; ?>" class="btn btn-primary btn-lg">Lets retry this!

      Reach out to kiu Nakamura if this problem persists for a longer time.

<?php sdestroy(); ?>


text:
require File.dirname(__FILE__) + '/../../test_helper'

class NilClassTest < Test::Unit::TestCase

  context "An instance of NilClass" do

    should "return an empty string as a slug" do
      assert_equal '', nil.sluggify
    end

  end

end


text:
package application_gateway

import (
	"encoding/json"
	"regexp"
	"strconv"

	"github.com/kyma-project/kyma/components/application-operator/pkg/apis/applicationconnector/v1alpha1"
	"github.com/pkg/errors"

	test_api "github.com/kyma-project/kyma/tests/components/application-connector/internal/testkit/test-api"
)

func getExpectedHTTPCode(service v1alpha1.Service) (int, error) {
	re := regexp.MustCompile(`\d+`)
	if codeStr := re.FindString(service.Description); len(codeStr) > 0 {
		return strconv.Atoi(codeStr)
	}
	return 0, errors.New("Bad configuration")
}

func gatewayURL(app, service string) string {
	return "http://central-application-gateway.kyma-system:8080/" + app + "/" + service
}

func unmarshalBody(body []byte) (test_api.EchoResponse, error) {
	res := test_api.EchoResponse{}
	err := json.Unmarshal(body, &res)
	return res, err
}


text:
@interface ImageCellNode : ASCellNode

- (instancetype)initWithImage:(UIImage *)image;

@end


text:
using System;

class Program
{
        static void Main()
        {
            int age;
            Console.Write("Enter Your age:");
            while(!int.TryParse(Console.ReadLine(),out age) || (age < 0))
            {
                Console.Write("Error!!! Incorrect entry. You should input a whole positive integer as your age.\nEnter your age:");
            }
            Console.WriteLine("After ten years your age will be {0}.",age+10);
        }
}


text:
This plugin for the CakePHP Framework allows you to use the Twig Templating Language.

Apart from enabling you to use most of Twig's features the plugin is tightly integrated with
the CakePHP view renderer giving you full access to helpers, objects and elements.

## Installation

Download the repository, create a folder called ```twig_view``` in your plugins folder. Extract.
Alternatively: Just clone the repository directly into your app.

    $ cd app/plugins
    $ git clone git://github.com/m3nt0r/cakephp-twig-view.git twig_view

### Vendor Files

Download the [Twig Library](http://www.twig-project.org/) and move ```(archive)/*``` to ```plugins/twig_view/vendors/Twig```.
Alternatively: Just init the submodules of this repository. This will grab the latest version.

    $ git submodule init
    $ git submodule update

### Cache Permissions

Make the default view-cache folder writeable.

    APP/plugins/twig_view/tmp/views

Alternatively: Set where you want cache files to be stored.

    define('TWIG_VIEW_CACHE', APP . 'tmp');

## Using the View Class

To make CakePHP aware of TwigView edit your ```app_controller.php``` file and add the following:

    class AppController extends Controller
    {
        public $view = 'TwigView.Twig';
    }

Now start creating view files using the ```.tpl``` extension.

## Default Layouts

This plugin comes with all default layouts converted to Twig. Examples can be found in:

     plugins/twig_view/examples

## Themes

The plugin has support for themes and works just like the "Theme" view. Simply add the ```$theme```
property to your controller and you're set.

    class AppController extends Controller
    {
        public $view = 'TwigView.Twig';
        public $theme = 'rockstar';
    }

This will cause the view to also look in the "themed" folder for templates. In the above example
templates in the following directory are favored over their non-themed version.

    app/views/themed/rockstar/

If you, for example, want to overwrite the 'layouts/default.tpl' file in the 'rockstar' theme,
then create this file:

    app/views/themed/rockstar/layouts/default.tpl

## Using Helpers inside Templates

All helper objects are available inside a view and can be used like any other variable inside Twig.

    {{ time.nice(user.created) }}

... where ...

    {{ time.nice(user.created) }}
        ^    ^    ^    ^____key
        |    |    |____array (from $this->set() or loop)
        |    |_____ method
        |______ helper

Which is the equivalent of writing:

    <?php echo $this->Time->nice($user['created']); ?>

A more complex example, FormHelper inputs:

    {{
     form.input('message', {
       'label': 'Your message',
       'error': {
         'notempty': 'Please enter a message'
        }
      })
    }}

## Referencing View Elements

Elements must be ```.tpl``` files and are parsed as Twig templates. Using ```.ctp``` is not possible.
In exchange for this limitation you can import elements as easy as this:

    {{ element 'sidebar/about' }}

## Translating Strings

The ```trans``` filter can be used on any string and simply takes the preceeding string and
passes it through the ```__()``` function.

    {{
      form.input('email', {
        'label': 'Your E-Mail Address'| trans
      })
    }}

This is the equivalent of writing:

    <?php echo $this->Form->input('email', array(
       'label' => __("Your E-Mail Address", true)
    )); ?>

## Translating multiple lines

The trans-block element will help you with that. This is especially useful when writing email
templates using Twig.

    {% trans %}
    Hello!

    This is my mail body and i can translate it in X languages now.
    We love it!
    {% endtrans %}

## TwigView Custom Filters

This plugin comes with a couple of handy filters, just like 'trans', piping some core CakePHP
functions into Twig templates.

### ago

Shortcut to TimeHelper::timeAgoInWords

    {{ user.created|ago }}

### low

Convert a string to lower case

    {{ 'FOO'|low }}

### up

Convert a string to upper case

    {{ 'foo'|up }}

### debug

Display the debug (pre+print_r) output

    {{ user|debug }}

### pr

Display just the print_r output

    {{ user|pr }}

### env

Display the value from a environment variable

    {{ 'HTTP_HOST'|env }}

### size

Convert byte integer to a humand readable size

    {{ '3535839525'|size }}    //=> 3.29 GB

### p

Formats a number with a level of precision.

    {{ '0.555'|p(2) }}    //=> 0.56

### curr

Display floating point value as currency value. USD, GBP and EUR only

    {{ '5999'|curr }}         // default, $5,999.00
    {{ '5999'|curr('GBP') }}  // £5,999.00
    {{ '5999'|curr('EUR') }}  // €5.999,00

### pct

Formats a number into a percentage string.

    {{ '2.3'|pct }}    //=> 2.30%

## Twig Built-In Filters

For a list of available filters please refer to the Twig Manual
http://www.twig-project.org/doc/templates.html#list-of-built-in-filters

## Accessing View Instance

In some cases it is useful to access ```$this```, for example to build a DOM id from
the current controller and action name.

The object is accessible through ```_view```.

    <div class="default" id="{{ _view.name|lower ~ '_' ~ _view.action|lower }}">


text:
User.instance_eval do

  has_one :wholesaler

  scope :wholesale, lambda { includes(:roles).where("roles.name" => "wholesaler") }

end

User.class_eval do

  def wholesaler?
    has_role?("wholesaler") && !wholesaler.nil?
  end

end


text:
from __future__ import absolute_import

from sentry.plugins import Plugin2

class ReleaseTrackingPlugin(Plugin2):
    def get_plugin_type(self):
        return 'release-tracking'

    def get_release_doc_html(self, hook_url):
        raise NotImplementedError


text: require "chromium_remote_debugging/types/remote_object"


text:
using System;
using System.Linq;
using System.Web.Mvc;
using Nop.Admin.Extensions;
using Nop.Admin.Models.Polls;
using Nop.Core.Domain.Polls;
using Nop.Services.Helpers;
using Nop.Services.Localization;
using Nop.Services.Polls;
using Nop.Services.Security;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using Nop.Web.Framework.Mvc;

namespace Nop.Admin.Controllers
{
    public partial class PollController : BaseAdminController
	{
		#region Fields

        private readonly IPollService _pollService;
        private readonly ILanguageService _languageService;
        private readonly IDateTimeHelper _dateTimeHelper;
        private readonly ILocalizationService _localizationService;
        private readonly IPermissionService _permissionService;

		#endregion

		#region Constructors

        public PollController(IPollService pollService, ILanguageService languageService,
            IDateTimeHelper dateTimeHelper, ILocalizationService localizationService,
            IPermissionService permissionService)
        {
            this._pollService = pollService;
            this._languageService = languageService;
            this._dateTimeHelper = dateTimeHelper;
            this._localizationService = localizationService;
            this._permissionService = permissionService;
		}

		#endregion

        #region Polls

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            return View();
        }

        [HttpPost]
        public ActionResult List(DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            var polls = _pollService.GetPolls(0, false, command.Page - 1, command.PageSize, true);
            var gridModel = new DataSourceResult
            {
                Data = polls.Select(x =>
                {
                    var m = x.ToModel();
                    if (x.StartDateUtc.HasValue)
                        m.StartDate = _dateTimeHelper.ConvertToUserTime(x.StartDateUtc.Value, DateTimeKind.Utc);
                    if (x.EndDateUtc.HasValue)
                        m.EndDate = _dateTimeHelper.ConvertToUserTime(x.EndDateUtc.Value, DateTimeKind.Utc);
                    m.LanguageName = x.Language.Name;
                    return m;
                }),
                Total = polls.TotalCount
            };

            return Json(gridModel);
        }

        public ActionResult Create()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            var model = new PollModel();
            //default values
            model.Published = true;
            model.ShowOnHomePage = true;
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Create(PollModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            if (ModelState.IsValid)
            {
                var poll = model.ToEntity();
                poll.StartDateUtc = model.StartDate;
                poll.EndDateUtc = model.EndDate;
                _pollService.InsertPoll(poll);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Polls.Added"));
                return continueEditing ? RedirectToAction("Edit", new { id = poll.Id }) : RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            var poll = _pollService.GetPollById(id);
            if (poll == null)
                //No poll found with the specified id
                return RedirectToAction("List");

            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            var model = poll.ToModel();
            model.StartDate = poll.StartDateUtc;
            model.EndDate = poll.EndDateUtc;
            return View(model);
        }

        [HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
        public ActionResult Edit(PollModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            var poll = _pollService.GetPollById(model.Id);
            if (poll == null)
                //No poll found with the specified id
                return RedirectToAction("List");

            if (ModelState.IsValid)
            {
                poll = model.ToEntity(poll);
                poll.StartDateUtc = model.StartDate;
                poll.EndDateUtc = model.EndDate;
                _pollService.UpdatePoll(poll);

                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Polls.Updated"));

                if (continueEditing)
                {
                    //selected tab
                    SaveSelectedTabIndex();

                    return RedirectToAction("Edit", new { id = poll.Id });
                }
                return RedirectToAction("List");
            }

            //If we got this far, something failed, redisplay form
            ViewBag.AllLanguages = _languageService.GetAllLanguages(true);
            return View(model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            var poll = _pollService.GetPollById(id);
            if (poll == null)
                //No poll found with the specified id
                return RedirectToAction("List");

            _pollService.DeletePoll(poll);

            SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.Polls.Deleted"));
            return RedirectToAction("List");
        }

        #endregion

        #region Poll answer

        [HttpPost]
        public ActionResult PollAnswers(int pollId, DataSourceRequest command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            var poll = _pollService.GetPollById(pollId);
            if (poll == null)
                throw new ArgumentException("No poll found with the specified id", "pollId");

            var answers = poll.PollAnswers.OrderBy(x=>x.DisplayOrder).ToList();

            var gridModel = new DataSourceResult
            {
                Data = answers.Select(x =>  new PollAnswerModel
                {
                    Id = x.Id,
                    PollId = x.PollId,
                    Name = x.Name,
                    NumberOfVotes = x.NumberOfVotes,
                    DisplayOrder = x.DisplayOrder
                }),
                Total = answers.Count
            };

            return Json(gridModel);
        }

        [HttpPost]
        public ActionResult PollAnswerUpdate(PollAnswerModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            if (!ModelState.IsValid)
            {
                return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
            }

            var pollAnswer = _pollService.GetPollAnswerById(model.Id);
            if (pollAnswer == null)
                throw new ArgumentException("No poll answer found with the specified id");

            pollAnswer.Name = model.Name;
            pollAnswer.DisplayOrder = model.DisplayOrder;
            _pollService.UpdatePoll(pollAnswer.Poll);

            return new NullJsonResult();
        }

        [HttpPost]
        public ActionResult PollAnswerAdd(int pollId, [Bind(Exclude = "Id")] PollAnswerModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            if (!ModelState.IsValid)
            {
                return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
            }

            var poll = _pollService.GetPollById(pollId);
            if (poll == null)
                throw new ArgumentException("No poll found with the specified id", "pollId");

            poll.PollAnswers.Add(new PollAnswer
            {
                Name = model.Name,
                DisplayOrder = model.DisplayOrder
            });
            _pollService.UpdatePoll(poll);

            return new NullJsonResult();
        }

        [HttpPost]
        public ActionResult PollAnswerDelete(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManagePolls))
                return AccessDeniedView();

            var pollAnswer = _pollService.GetPollAnswerById(id);
            if (pollAnswer == null)
                throw new ArgumentException("No poll answer found with the specified id", "id");

            //int pollId = pollAnswer.PollId;
            _pollService.DeletePollAnswer(pollAnswer);

            return new NullJsonResult();
        }

        #endregion
    }
}


text:
mongo-php
=========

upload files vía php to mongodb


text:
package org.encos.flydown.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExceptionRates {

    ExceptionRate[] value();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using SPR.Blog.Data;

namespace SPR.Blog.Pages.Account.Manage
{
    public class ResetAuthenticatorModel : PageModel
    {
        UserManager<ApplicationUser> _userManager;
        ILogger<ResetAuthenticatorModel> _logger;

        public ResetAuthenticatorModel(
            UserManager<ApplicationUser> userManager,
            ILogger<ResetAuthenticatorModel> logger)
        {
            _userManager = userManager;
            _logger = logger;
        }
        public async Task<IActionResult> OnGet()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound();
            }

            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound();
            }

            await _userManager.SetTwoFactorEnabledAsync(user, false);
            await _userManager.ResetAuthenticatorKeyAsync(user);
            _logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id);

            return RedirectToPage("./EnableAuthenticator");
        }
    }
}


text:
Fork [minio-java upstream](https://github.com/minio/minio-js/fork) source repository to your own personal repository.

Minio Javascript library uses gulp for its dependency management http://gulpjs.com/
```sh
$ git clone https://github.com/$USER_ID/minio-js
$ cd minio-js
$ npm install
$ gulp
...
```

###  Developer Guidelines

``minio-js`` welcomes your contribution. To make the process as seamless as possible, we ask for the following:

* Go ahead and fork the project and make your changes. We encourage pull requests to discuss code changes.
    - Fork it
    - Create your feature branch (git checkout -b my-new-feature)
    - Commit your changes (git commit -am 'Add some feature')
    - Push to the branch (git push origin my-new-feature)
    - Create new Pull Request


text:
package net.voxelindustry.brokkgui.style.event;

import net.voxelindustry.brokkgui.style.ICascadeStyleable;
import net.voxelindustry.hermod.EventType;
import net.voxelindustry.hermod.HermodEvent;
import net.voxelindustry.hermod.IEventEmitter;

public class StyleRefreshEvent extends HermodEvent
{
    public static final EventType<StyleRefreshEvent> ANY = new EventType<>("STYLE_REFRESH_EVENT");

    public static final EventType<BeforeEvent> BEFORE = new EventType<>("BEFORE_STYLE_REFRESH_EVENT");
    public static final EventType<AfterEvent> AFTER = new EventType<>("AFTER_STYLE_REFRESH_EVENT");

    public StyleRefreshEvent(ICascadeStyleable source)
    {
        super(source);
    }

    @Override
    public HermodEvent copy(IEventEmitter source)
    {
        return new StyleRefreshEvent((ICascadeStyleable) source);
    }

    public static class BeforeEvent extends StyleRefreshEvent
    {
        public BeforeEvent(ICascadeStyleable source)
        {
            super(source);
        }

        @Override
        public HermodEvent copy(IEventEmitter source)
        {
            return new BeforeEvent((ICascadeStyleable) source);
        }
    }

    public static class AfterEvent extends StyleRefreshEvent
    {
        public AfterEvent(ICascadeStyleable source)
        {
            super(source);
        }

        @Override
        public HermodEvent copy(IEventEmitter source)
        {
            return new AfterEvent((ICascadeStyleable) source);
        }
    }
}


text:
import Orthographic from './cameras.orthographic';

/**
 * @module cameras
 */
export default {
  Orthographic,
};


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class Users extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        if (!Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('username',25)->nullable();
                $table->string('fullname',25)->nullable();
                $table->string('email',100);
                $table->string('password',100);
                $table->string('remember_token',100);
                $table->string('avatar_path',100)->nullable();
                $table->string('avatar_coordinates',100)->nullable();
                $table->integer('mobile')->nullable();
                $table->date('birthday')->nullable();
                $table->tinyInteger('sex')->default(0);
                $table->tinyInteger('status')->default(0);
                $table->tinyInteger('is_actived')->default(0);
                $table->string('activation_code', 100)->nullable();
                $table->dateTime('actived_at')->nullable();
                $table->timestamps();
                $table->softDeletes();
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::drop('users');
    }
}