text:
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DlibDotNet.Native.Tests
{

    [TestClass]
    public class DlibTest
    {

        private const string VersionKey = "DLIBDOTNET_VERSION";

        private const string GuiSupportKey = "DLIBDOTNET_GUI_SUPPORT";

        [TestMethod]
        public void CheckDlibDotNetNativeVersion()
        {
            var values = Environment.GetEnvironmentVariables();
            if (!values.Contains(VersionKey))
                Assert.Fail($"{VersionKey} is not found.");

            Console.WriteLine($"{VersionKey}: {values[VersionKey]}");
            Assert.AreEqual(values[VersionKey], DlibDotNet.Dlib.GetNativeVersion());
        }

        [TestMethod]
        public void CheckDlibDotNetNativeDnnVersion()
        {
            var values = Environment.GetEnvironmentVariables();
            if (!values.Contains(VersionKey))
                Assert.Fail($"{VersionKey} is not found.");

            Console.WriteLine($"{VersionKey}: {values[VersionKey]}");
            Assert.AreEqual(values[VersionKey], DlibDotNet.Dlib.GetNativeDnnVersion());
        }

        [TestMethod]
        public void GetFrontalFaceDetector()
        {
            using(var faceDetector = DlibDotNet.Dlib.GetFrontalFaceDetector())
            using(var image = DlibDotNet.Dlib.LoadImage<RgbPixel>("Lenna.png"))
            {
                var dets = faceDetector.Operator(image);
                Assert.AreEqual(1, dets.Length);
            }
        }

        [TestMethod]
        public void LossMmod()
        {
            using(var loss = DlibDotNet.Dnn.LossMmod.Deserialize("mmod_human_face_detector.dat"))
            using(var matrix = DlibDotNet.Dlib.LoadImageAsMatrix<RgbPixel>("Lenna.png"))
            {
                var dets = loss.Operator(matrix).First().ToArray();
                Assert.AreEqual(1, dets.Length);
            }
        }

        [TestMethod]
        public void CheckIsSupoortGui()
        {
            var values = Environment.GetEnvironmentVariables();
            if (!values.Contains(GuiSupportKey))
                Assert.Fail($"{GuiSupportKey} is not found.");

            Console.WriteLine($"{GuiSupportKey}: {values[GuiSupportKey]}");
            Assert.AreEqual((string)values[GuiSupportKey] != "0", DlibDotNet.Dlib.IsSupportGui);
        }

        [TestMethod]
        public void CheckIsDnnSupoortGui()
        {
            var values = Environment.GetEnvironmentVariables();
            if (!values.Contains(GuiSupportKey))
                Assert.Fail($"{GuiSupportKey} is not found.");

            Console.WriteLine($"{GuiSupportKey}: {values[GuiSupportKey]}");
            Assert.AreEqual((string)values[GuiSupportKey] != "0", DlibDotNet.Dlib.IsDnnSupportGui);
        }

    }

}


text:
#import <Cocoa/Cocoa.h>

NS_ASSUME_NONNULL_BEGIN

@interface FRSystemProfile : NSObject

// Introspects the system for:
// 1) macOS version
// 2) Mac model
// 3) RAM amount
// 4) CPU type
// 5) CPU speed
// 6) number of CPUs
// 7) number of active CPUs
// 8) if CPU is 64-Bit
// 9) preferred language
// 10) network host name
// 11) thermal state
// and returns an array of dictionaries with that information.
+ (NSArray *) discover;

@end

NS_ASSUME_NONNULL_END

redpajama_set_name: RedPajamaGithub


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.analyticsadmin.v1alpha.model;

/**
 * The filter for strings.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Google Analytics Admin API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleAnalyticsAdminV1alphaAccessStringFilter extends com.google.api.client.json.GenericJson {

  /**
   * If true, the string value is case sensitive.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean caseSensitive;

  /**
   * The match type for this filter.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String matchType;

  /**
   * The string value used for the matching.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String value;

  /**
   * If true, the string value is case sensitive.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getCaseSensitive() {
    return caseSensitive;
  }

  /**
   * If true, the string value is case sensitive.
   * @param caseSensitive caseSensitive or {@code null} for none
   */
  public GoogleAnalyticsAdminV1alphaAccessStringFilter setCaseSensitive(java.lang.Boolean caseSensitive) {
    this.caseSensitive = caseSensitive;
    return this;
  }

  /**
   * The match type for this filter.
   * @return value or {@code null} for none
   */
  public java.lang.String getMatchType() {
    return matchType;
  }

  /**
   * The match type for this filter.
   * @param matchType matchType or {@code null} for none
   */
  public GoogleAnalyticsAdminV1alphaAccessStringFilter setMatchType(java.lang.String matchType) {
    this.matchType = matchType;
    return this;
  }

  /**
   * The string value used for the matching.
   * @return value or {@code null} for none
   */
  public java.lang.String getValue() {
    return value;
  }

  /**
   * The string value used for the matching.
   * @param value value or {@code null} for none
   */
  public GoogleAnalyticsAdminV1alphaAccessStringFilter setValue(java.lang.String value) {
    this.value = value;
    return this;
  }

  @Override
  public GoogleAnalyticsAdminV1alphaAccessStringFilter set(String fieldName, Object value) {
    return (GoogleAnalyticsAdminV1alphaAccessStringFilter) super.set(fieldName, value);
  }

  @Override
  public GoogleAnalyticsAdminV1alphaAccessStringFilter clone() {
    return (GoogleAnalyticsAdminV1alphaAccessStringFilter) super.clone();
  }

}


text:
package org.mifos.framework.struts.tags;

import static org.mifos.framework.TestUtils.assertWellFormedFragment;
import junit.framework.Assert;
import junit.framework.TestCase;

import org.dom4j.DocumentException;

public class MifosNumberTextTagTest extends TestCase {

    public void testrenderInputsForhidden() throws DocumentException {
        MifosNumberTextTag mifosNumberTextTag = new MifosNumberTextTag();
        StringBuilder inputsForhidden = new StringBuilder();
        inputsForhidden.append("<script src=" + "\"pages/framework/js/func.js\"" + ">");
        inputsForhidden.append("</script>");
        inputsForhidden.append("<script src=" + "\"pages/framework/js/func_test.js\"" + ">");
        inputsForhidden.append("</script>");
       Assert.assertEquals(inputsForhidden.toString(), mifosNumberTextTag.render("test"));
        assertWellFormedFragment(mifosNumberTextTag.render("test"));
    }
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
from requests import Response
from io import BytesIO
try:
    from werkzeug.exceptions import Unauthorized
except ImportError:
    Unauthorized = Exception
from . import utils

class Provider(object):
    """Base provider class for different types of OAuth 2.0 providers."""

    def _handle_exception(self, exc):
        """Handle an internal exception that was caught and suppressed.

        :param exc: Exception to process.
        :type exc: Exception
        """
        logger = logging.getLogger(__name__)
        logger.exception(exc)

    def _make_response(self, body='', headers=None, status_code=200):
        """Return a response object from the given parameters.

        :param body: Buffer/string containing the response body.
        :type body: str
        :param headers: Dict of headers to include in the requests.
        :type headers: dict
        :param status_code: HTTP status code.
        :type status_code: int
        :rtype: requests.Response
        """
        res = Response()
        res.status_code = status_code
        if headers is not None:
            res.headers.update(headers)
        res.raw = BytesIO(bytes(body, 'utf-8'))
        return res

    def _make_redirect_error_response(self, redirect_uri, err):
        """Return a HTTP 302 redirect response object containing the error.

        :param redirect_uri: Client redirect URI.
        :type redirect_uri: str
        :param err: OAuth error message.
        :type err: str
        :rtype: requests.Response
        """
        params = {
            'error': err,
            'response_type': None,
            'client_id': None,
            'redirect_uri': None
        }
        redirect = utils.build_url(redirect_uri, params)
        return self._make_response(headers={'Location': redirect},
                                   status_code=302)

    def _make_json_response(self, data, headers=None, status_code=200):
        """Return a response object from the given JSON data.

        :param data: Data to JSON-encode.
        :type data: mixed
        :param headers: Dict of headers to include in the requests.
        :type headers: dict
        :param status_code: HTTP status code.
        :type status_code: int
        :rtype: requests.Response
        """
        response_headers = {}
        if headers is not None:
            response_headers.update(headers)
        response_headers['Content-Type'] = 'application/json'
        response_headers['Cache-Control'] = 'no-store'
        response_headers['Pragma'] = 'no-cache'
        return self._make_response(json.dumps(data),
                                   response_headers,
                                   status_code)

    def _make_json_error_response(self, err):
        """Return a JSON-encoded response object representing the error.

        :param err: OAuth error message.
        :type err: str
        :rtype: requests.Response
        """
        return self._make_json_response({'error': err}, status_code=400)

    def _invalid_redirect_uri_response(self):
        """What to return when the redirect_uri parameter is missing.

        :rtype: requests.Response
        """
        return self._make_json_error_response('invalid_request')

class AuthorizationProvider(Provider):
    """OAuth 2.0 authorization provider. This class manages authorization
    codes and access tokens. Certain methods MUST be overridden in a
    subclass, thus this class cannot be directly used as a provider.

    These are the methods that must be implemented in a subclass:

        validate_client_id(self, client_id)
            # Return True or False

        validate_client_secret(self, client_id, client_secret)
            # Return True or False

        validate_scope(self, client_id, scope)
            # Return True or False

        validate_redirect_uri(self, client_id, redirect_uri)
            # Return True or False

        validate_access(self)  # Use this to validate your app session user
            # Return True or False

        from_authorization_code(self, client_id, code, scope)
            # Return mixed data or None on invalid

        from_refresh_token(self, client_id, refresh_token, scope)
            # Return mixed data or None on invalid

        persist_authorization_code(self, client_id, code, scope)
            # Return value ignored

        persist_token_information(self, client_id, scope, access_token,
                                  token_type, expires_in, refresh_token,
                                  data)
            # Return value ignored

        discard_authorization_code(self, client_id, code)
            # Return value ignored

        discard_refresh_token(self, client_id, refresh_token)
            # Return value ignored

    Optionally, the following may be overridden to acheive desired behavior:

        @property
        token_length(self)

        @property
        token_type(self)

        @property
        token_expires_in(self)

        generate_authorization_code(self)

        generate_access_token(self)

        generate_refresh_token(self)

    """

    @property
    def token_length(self):
        """Property method to get the length used to generate tokens.

        :rtype: int
        """
        return 40

    @property
    def token_type(self):
        """Property method to get the access token type.

        :rtype: str
        """
        return 'Bearer'

    @property
    def token_expires_in(self):
        """Property method to get the token expiration time in seconds.

        :rtype: int
        """
        return 3600

    def generate_authorization_code(self):
        """Generate a random authorization code.

        :rtype: str
        """
        return utils.random_ascii_string(self.token_length)

    def generate_access_token(self):
        """Generate a random access token.

        :rtype: str
        """
        return utils.random_ascii_string(self.token_length)

    def generate_refresh_token(self):
        """Generate a random refresh token.

        :rtype: str
        """
        return utils.random_ascii_string(self.token_length)

    def get_authorization_code(self,
                               response_type,
                               client_id,
                               redirect_uri,
                               **params):
        """Generate authorization code HTTP response.

        :param response_type: Desired response type. Must be exactly "code".
        :type response_type: str
        :param client_id: Client ID.
        :type client_id: str
        :param redirect_uri: Client redirect URI.
        :type redirect_uri: str
        :rtype: requests.Response
        """

        # Ensure proper response_type
        if response_type != 'code':
            err = 'unsupported_response_type'
            return self._make_redirect_error_response(redirect_uri, err)

        # Check redirect URI
        is_valid_redirect_uri = self.validate_redirect_uri(client_id,
                                                           redirect_uri)
        if not is_valid_redirect_uri:
            return self._invalid_redirect_uri_response()

        # Check conditions
        is_valid_client_id = self.validate_client_id(client_id)
        is_valid_access = self.validate_access()
        scope = params.get('scope', '')
        is_valid_scope = self.validate_scope(client_id, scope)

        # Return proper error responses on invalid conditions
        if not is_valid_client_id:
            err = 'unauthorized_client'
            return self._make_redirect_error_response(redirect_uri, err)

        if not is_valid_access:
            err = 'access_denied'
            return self._make_redirect_error_response(redirect_uri, err)

        if not is_valid_scope:
            err = 'invalid_scope'
            return self._make_redirect_error_response(redirect_uri, err)

        # Generate authorization code
        code = self.generate_authorization_code()

        # Save information to be used to validate later requests
        self.persist_authorization_code(client_id=client_id,
                                        code=code,
                                        scope=scope)

        # Return redirection response
        params.update({
            'code': code,
            'response_type': None,
            'client_id': None,
            'redirect_uri': None
        })
        redirect = utils.build_url(redirect_uri, params)
        return self._make_response(headers={'Location': redirect},
                                   status_code=302)

    def refresh_token(self,
                      grant_type,
                      client_id,
                      client_secret,
                      refresh_token,
                      **params):
        """Generate access token HTTP response from a refresh token.

        :param grant_type: Desired grant type. Must be "refresh_token".
        :type grant_type: str
        :param client_id: Client ID.
        :type client_id: str
        :param client_secret: Client secret.
        :type client_secret: str
        :param refresh_token: Refresh token.
        :type refresh_token: str
        :rtype: requests.Response
        """

        # Ensure proper grant_type
        if grant_type != 'refresh_token':
            return self._make_json_error_response('unsupported_grant_type')

        # Check conditions
        is_valid_client_id = self.validate_client_id(client_id)
        is_valid_client_secret = self.validate_client_secret(client_id,
                                                             client_secret)
        scope = params.get('scope', '')
        is_valid_scope = self.validate_scope(client_id, scope)
        data = self.from_refresh_token(client_id, refresh_token, scope)
        is_valid_refresh_token = data is not None

        # Return proper error responses on invalid conditions
        if not (is_valid_client_id and is_valid_client_secret):
            return self._make_json_error_response('invalid_client')

        if not is_valid_scope:
            return self._make_json_error_response('invalid_scope')

        if not is_valid_refresh_token:
            return self._make_json_error_response('invalid_grant')

        # Discard original refresh token
        self.discard_refresh_token(client_id, refresh_token)

        # Generate access tokens once all conditions have been met
        access_token = self.generate_access_token()
        token_type = self.token_type
        expires_in = self.token_expires_in
        refresh_token = self.generate_refresh_token()

        # Save information to be used to validate later requests
        self.persist_token_information(client_id=client_id,
                                       scope=scope,
                                       access_token=access_token,
                                       token_type=token_type,
                                       expires_in=expires_in,
                                       refresh_token=refresh_token,
                                       data=data)

        # Return json response
        return self._make_json_response({
            'access_token': access_token,
            'token_type': token_type,
            'expires_in': expires_in,
            'refresh_token': refresh_token,
            'user_id': data['user_id']
        })

    def get_token_for_authorization_code(self,
                  client_id,
                  client_secret,
                  redirect_uri,
                  code,
                  **params):
        """Generate access token HTTP response.

        :param client_id: Client ID.
        :type client_id: str
        :param client_secret: Client secret.
        :type client_secret: str
        :param redirect_uri: Client redirect URI.
        :type redirect_uri: str
        :param code: Authorization code.
        :type code: str
        :rtype: requests.Response
        """

        # Check conditions
        is_valid_client_id = self.validate_client_id(client_id)
        is_valid_client_secret = self.validate_client_secret(client_id,
                                                             client_secret)
        is_valid_redirect_uri = self.validate_redirect_uri(client_id,
                                                           redirect_uri)

        scope = params.get('scope', '')
        is_valid_scope = self.validate_scope(client_id, scope)
        data = self.from_authorization_code(client_id, code, scope)
        is_valid_grant = data is not None

        # Return proper error responses on invalid conditions
        if not (is_valid_client_id and is_valid_client_secret):
            return self._make_json_error_response('invalid_client')

        if not is_valid_grant or not is_valid_redirect_uri:
            return self._make_json_error_response('invalid_grant')

        if not is_valid_scope:
            return self._make_json_error_response('invalid_scope')

        # Discard original authorization code
        self.discard_authorization_code(client_id, code)

        # Generate access tokens once all conditions have been met
        access_token = self.generate_access_token()
        token_type = self.token_type
        expires_in = self.token_expires_in
        refresh_token = self.generate_refresh_token()

        # Save information to be used to validate later requests
        self.persist_token_information(client_id=client_id,
                                       scope=scope,
                                       access_token=access_token,
                                       token_type=token_type,
                                       expires_in=expires_in,
                                       refresh_token=refresh_token,
                                       data=data)

        # Return json response
        return self._make_json_response({
            'access_token': access_token,
            'token_type': token_type,
            'expires_in': expires_in,
            'refresh_token': refresh_token,
            'user_id': data['user_id']
        })

    def get_token_for_password(self, client_id,
                  username,
                  password,
                  **params):
        """Generate access token HTTP response.

        :param username: Username.
        :type username: str
        :param password: password
        :type password: str
        :rtype: requests.Response
        """

        scope = params.get('scope', '')
        is_valid_scope = self.validate_scope(client_id, scope)

        data = self.from_user_credentials(client_id, username, password, scope)

        # If user isn't found, then claim invalid grant.
        if not data:
            return self._make_json_error_response('invalid_grant')

        if not is_valid_scope:
            return self._make_json_error_response('invalid_scope')

        # Generate access tokens once all conditions have been met
        access_token = self.generate_access_token()
        token_type = self.token_type
        expires_in = self.token_expires_in
        refresh_token = self.generate_refresh_token()

        # Save information to be used to validate later requests
        self.persist_token_information(client_id=client_id,
                                       scope=scope,
                                       access_token=access_token,
                                       token_type=token_type,
                                       expires_in=expires_in,
                                       refresh_token=refresh_token,
                                       data=data)

        # Return json response
        return self._make_json_response({
            'access_token': access_token,
            'token_type': token_type,
            'expires_in': expires_in,
            'refresh_token': refresh_token,
            'user_id': data['user_id']
        })

    def get_token_for_anonymous(self, client_id,
                  **params):
        """Generate access token HTTP response.

        :param username: Username.
        :type username: str
        :param password: password
        :type password: str
        :rtype: requests.Response
        """

        scope = params.get('scope', '')
        is_valid_scope = self.validate_scope(client_id, scope)

        data = self.for_anonymous(client_id, scope)

        # If user isn't found, then claim invalid grant.
        if not data:
            return self._make_json_error_response('invalid_grant')

        if not is_valid_scope:
            return self._make_json_error_response('invalid_scope')

        # Generate access tokens once all conditions have been met
        access_token = self.generate_access_token()
        token_type = self.token_type
        expires_in = self.token_expires_in
        refresh_token = self.generate_refresh_token()

        # Save information to be used to validate later requests
        self.persist_token_information(client_id=client_id,
                                       scope=scope,
                                       access_token=access_token,
                                       token_type=token_type,
                                       expires_in=expires_in,
                                       refresh_token=refresh_token,
                                       data=data)

        # Return json response
        return self._make_json_response({
            'access_token': access_token,
            'token_type': token_type,
            'expires_in': expires_in,
            'refresh_token': refresh_token
        })

    def get_token_for_facebook_access_token(self, client_id, facebook_user_id, facebook_access_token, **params):
        """Generate access token HTTP response.

        'facebook_user_id', 'facebook_access_token', 'client_id'

        :param username: Username.
        :type username: str
        :param password: password
        :type password: str
        :rtype: requests.Response
        """

        scope = params.get('scope', '')
        is_valid_scope = self.validate_scope(client_id, scope)

        data = self.from_facebook_access_token(client_id, facebook_user_id, facebook_access_token, scope)

        # If user isn't found, then claim invalid grant.
        if not data:
            return self._make_json_error_response('invalid_grant')

        if not is_valid_scope:
            return self._make_json_error_response('invalid_scope')

        # Generate access tokens once all conditions have been met
        access_token = self.generate_access_token()
        token_type = self.token_type
        expires_in = self.token_expires_in
        refresh_token = self.generate_refresh_token()

        # Save information to be used to validate later requests
        self.persist_token_information(client_id=client_id,
                                       scope=scope,
                                       access_token=access_token,
                                       token_type=token_type,
                                       expires_in=expires_in,
                                       refresh_token=refresh_token,
                                       data=data)

        # Return json response
        return self._make_json_response({
            'access_token': access_token,
            'token_type': token_type,
            'expires_in': expires_in,
            'refresh_token': refresh_token
        })

    def get_token_for_refresh_token(self, client_id, client_secret,
                  refresh_token,
                  **params):
        """Generate access token HTTP response.

        :param client_id: Client ID.
        :type client_id: str
        :param client_secret: Client secret.
        :type client_secret: str
        :param redirect_uri: Client redirect URI.
        :type redirect_uri: str
        :param code: Authorization code.
        :type code: str
        :rtype: requests.Response
        """

        # Check conditions
        # Return proper error responses on invalid conditions
        client_app = self.validate_client_secret(client_id, client_secret)
        if not client_app:
            return self._make_json_error_response('invalid_client')

        scope = params.get('scope', '')
        is_valid_scope = self.validate_scope(client_id, scope)

        data = self.from_refresh_token(client_id, refresh_token, scope)
        is_valid_grant = data is not None

        if not is_valid_grant:
            return self._make_json_error_response('invalid_grant')

        if not is_valid_scope:
            return self._make_json_error_response('invalid_scope')

        # Discard original authorization code
        self.discard_refresh_token(client_id, refresh_token)

        # Generate access tokens once all conditions have been met
        access_token = self.generate_access_token()
        token_type = self.token_type
        expires_in = self.token_expires_in
        refresh_token = self.generate_refresh_token()

        # Save information to be used to validate later requests
        self.persist_token_information(client_id=client_id,
                                       scope=scope,
                                       access_token=access_token,
                                       token_type=token_type,
                                       expires_in=expires_in,
                                       refresh_token=refresh_token,
                                       data=data)

        # Return json response
        return self._make_json_response({
            'access_token': access_token,
            'token_type': token_type,
            'expires_in': expires_in,
            'refresh_token': refresh_token
        })

    def get_authorization_code_from_uri(self, uri):
        """Get authorization code response from a URI. This method will
        ignore the domain and path of the request, instead
        automatically parsing the query string parameters.

        :param uri: URI to parse for authorization information.
        :type uri: str
        :rtype: requests.Response
        """
        params = utils.url_query_params(uri)
        try:
            if 'response_type' not in params:
                raise TypeError('Missing parameter response_type in URL query')

            if 'client_id' not in params:
                raise TypeError('Missing parameter client_id in URL query')

            if 'redirect_uri' not in params:
                raise TypeError('Missing parameter redirect_uri in URL query')

            return self.get_authorization_code(**params)
        except TypeError as exc:
            self._handle_exception(exc)

            # Catch missing parameters in request
            err = 'invalid_request'
            if 'redirect_uri' in params:
                u = params['redirect_uri']
                return self._make_redirect_error_response(u, err)
            else:
                return self._invalid_redirect_uri_response()
        except Exception as exc:
            self._handle_exception(exc)

            # Catch all other server errors
            err = 'server_error'
            u = params['redirect_uri']
            return self._make_redirect_error_response(u, err)

    def get_token_from_post_data(self, data):
        """Get a token response from POST data.

        :param data: POST data containing authorization information.
        :type data: dict
        :rtype: requests.Response
        """
        try:

            grant_type = data.get('grant_type')

            if not grant_type:
                raise TypeError('Missing required OAuth 2.0 POST param: grant_type')

            if grant_type == 'authorization_code':

                # Verify OAuth 2.0 Parameters
                for x in ['client_id', 'client_secret', 'redirect_uri']:
                    if x not in data:
                        raise TypeError("Missing required OAuth 2.0 POST param: {0}".format(x))
                return self.get_token_for_authorization_code(**data)

            if grant_type == 'refresh_token':
                # Verify OAuth 2.0 Parameters
                for x in ['client_id', 'refresh_token']:
                    if x not in data:
                        raise TypeError("Missing required OAuth 2.0 POST param: {0}".format(x))
                return self.get_token_for_refresh_token(**data)

            if grant_type == 'password':
                for x in ('username', 'password', 'client_id'):
                    if x not in data:
                        raise TypeError("Missing required OAuth 2.0 POST param: {0}".format(x))
                return self.get_token_for_password(**data)

            if grant_type == 'facebook':
                for x in ('facebook_user_id', 'facebook_access_token', 'client_id'):
                    if x not in data:
                        raise TypeError("Missing required param: {0}".format(x))
                return self.get_token_for_facebook_access_token(**data)

            if grant_type == 'anonymous':
                return self.get_token_for_anonymous(**data)

            return self._make_json_error_response('unsupported_grant_type')

        except TypeError as exc:
            self._handle_exception(exc)

            # Catch missing parameters in request
            return self._make_json_error_response('invalid_request')
        except Exception as exc:
            self._handle_exception(exc)

            # Catch all other server errors
            return self._make_json_error_response('server_error')

    def validate_client_id(self, client_id):
        raise NotImplementedError('Subclasses must implement ' \
                                  'validate_client_id.')

    def validate_client_secret(self, client_id, client_secret):
        raise NotImplementedError('Subclasses must implement ' \
                                  'validate_client_secret.')

    def validate_redirect_uri(self, client_id, redirect_uri):
        raise NotImplementedError('Subclasses must implement ' \
                                  'validate_redirect_uri.')

    def validate_scope(self, client_id, scope):
        raise NotImplementedError('Subclasses must implement ' \
                                  'validate_scope.')

    def validate_access(self):
        raise NotImplementedError('Subclasses must implement ' \
                                  'validate_access.')

    def from_authorization_code(self, client_id, code, scope):
        raise NotImplementedError('Subclasses must implement ' \
                                  'from_authorization_code.')

    def from_refresh_token(self, client_id, refresh_token, scope):
        raise NotImplementedError('Subclasses must implement ' \
                                  'from_refresh_token.')

    def persist_authorization_code(self, client_id, code, scope):
        raise NotImplementedError('Subclasses must implement ' \
                                  'persist_authorization_code.')

    def from_user_credentials(self, client_id, username, password, scope):
        raise NotImplementedError('Subclasses must implement ' \
                                  'from_user_credentials.')

    def for_anonymous(self, client_id, scope):
        raise NotImplementedError('Subclasses must implement ' \
                                  'from_anonymous.')

    def from_facebook_access_token(self, client_id, facebook_user_id, facebook_access_token, scope):
        raise NotImplementedError('Subclasses must implement ' \
                                  'from_facebook_access_token.')

    def persist_token_information(self, client_id, scope, access_token,
                                  token_type, expires_in, refresh_token,
                                  data):
        raise NotImplementedError('Subclasses must implement ' \
                                  'persist_token_information.')

    def discard_authorization_code(self, client_id, code):
        raise NotImplementedError('Subclasses must implement ' \
                                  'discard_authorization_code.')

    def discard_refresh_token(self, client_id, refresh_token):
        raise NotImplementedError('Subclasses must implement ' \
                                  'discard_refresh_token.')

class OAuthError(Unauthorized):
    """OAuth error, including the OAuth error reason."""
    def __init__(self, reason, *args, **kwargs):
        self.reason = reason
        super(OAuthError, self).__init__(*args, **kwargs)

class ResourceAuthorization(object):
    """A class containing an OAuth 2.0 authorization."""
    is_oauth = False
    is_valid = None
    token = None
    client_id = None
    expires_in = None
    error = None

    def raise_error_if_invalid(self):
        if not self.is_valid:
            raise OAuthError(self.error, 'OAuth authorization error')

class ResourceProvider(Provider):
    """OAuth 2.0 resource provider. This class provides an interface
    to validate an incoming request and authenticate resource access.
    Certain methods MUST be overridden in a subclass, thus this
    class cannot be directly used as a resource provider.

    These are the methods that must be implemented in a subclass:

        get_authorization_header(self)
            # Return header string for key "Authorization" or None

        validate_access_token(self, access_token, authorization)
            # Set is_valid=True, client_id, and expires_in attributes
            #   on authorization if authorization was successful.
            # Return value is ignored
    """

    @property
    def authorization_class(self):
        return ResourceAuthorization

    def get_authorization(self):
        """Get authorization object representing status of authentication."""
        auth = self.authorization_class()
        header = self.get_authorization_header()
        if not header or not header.split:
            return auth
        header = header.split()
        if len(header) > 1 and header[0] == 'Bearer':
            auth.is_oauth = True
            access_token = header[1]
            self.validate_access_token(access_token, auth)
            if not auth.is_valid:
                auth.error = 'access_denied'
        return auth

    def get_authorization_header(self):
        raise NotImplementedError('Subclasses must implement ' \
                                  'get_authorization_header.')

    def validate_access_token(self, access_token, authorization):
        raise NotImplementedError('Subclasses must implement ' \
                                  'validate_token.')


text:
This guide provides the sequence of commands needed to package a version of REDCap software for deployment or upgrade. See the REDCap Deployment Tools document (redcap_deployment_commands_documentation.md) for more details about the individual commands.

---

### Prerequisites
This workflow assumes you have a REDCap zip file exactly as downloaded from the REDCap Consortium. The version of REDCap is up to you, but the zip file needs to be named in the original format of redcap#.#.#.zip (standalone package) OR redcap#.#.#_upgrade.zip (upgrade package). The zip file needs to be in the same directory as the file fabfile.py. The fabric commands will be entered into the command line from this directory.

## Fabric Command Sequence
While you're in the directory that contains both the fabfile and the desired redcap zip file, execute the command `$ fab package:(redcap_zip)`. The redcap\_zip is your redcap zip file or it will default to the most recent redcap zip in the directory. This will remove any existing build directories (builddirs) and create a new one for the build. The new builddir is populated with the extracted contents of the zip file found/specified and plugins if provided. The resultant package file will be named redcap-#.#.#.tgz or redcap-#.#.#_upgrade.tgz according to the name of the redcap.zip used to create this package.

Optionally, you can specify an instance you are building for. This will allow you to specify configurable languages and patches to be included in the package. To do that you would name the instance just before package like this:

    fab instance:vagrant package:redcap7.2.2.zip

## Adding language files

To add a REDCap language file to your REDCap package, download the language file from the REDCap community site, copy it into the same directory as fabfile.py, and add an entry like this to your instance's configuration file:

    [instance]
    languages = [ "Chinese.6.4.3.ini" ]

The languages variable will be interpreted as a JSON list. If you want to load multiple language files, separate their file names with commas:

    [instance]
    languages = [ "Chinese.6.4.3.ini", "German6.10.1.ini" ]

## Adding patches

To apply a patch the REDCap core code, you will need to create a specially formatted git repository with the patch file and a script named `deploy.sh` that can deploy it into the builddir.  That deploy.sh file would look something like this:

    #!/bin/bash
    # deployment script for the redcap_security_settings GLID patch
    # Clone the repo that has this file via
    #
    #   git clone git@ctsit-forge.ctsi.ufl.edu:redcap_security_settings.git
    #
    # Call this script with two parameters:
    #
    #   REDCAP_ROOT - the top level redcap directory.  typically this directory contains cron.php
    #   REDCAP_VERSION - the version of the code being patched/deployed.
    #

    set -e

    export REDCAP_ROOT=$1
    export REDCAP_VERSION=$2

    # determine the directory where this script resides
    DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

    cd $REDCAP_ROOT/redcap_v$REDCAP_VERSION/ControlCenter/
    patch -p1 < $DIR/security_settings.php.patch

The script must be named `deploy.sh`.  It must accept two parameters, `REDCAP_ROOT` and `REDCAP_VERSION`.  It must use these two variables to determine in which directory it should apply the patch.

With this git repository created, you must reference it in the instance configuration file like this:

    [instance]
    patch_repos = [ "git@ctsit-forge.ctsi.ufl.edu:redcap_security_settings.git" ]

As with the language files, you may specify multiple patches in a comma-separated list.

The `package` task will checkout each of these repositories and run ./deploy.sh in the root of the repository.

## Adding Plugins

You can add a plugin by creating deployment script for that plugin at deploy/plugins/`plugin_name`/deploy.sh. The `package` task runs each of deploy/plugins/`plugin_name`/deploy.sh scripts. The deploy.sh scripts swill need to put the plugin files in the right places underneath `builddir`/redcap/plugins/. Whether the deploy/plugins/`plugin_name` directory also contains the plugin files or if the deploy.sh script fetches them from an authoritative source is entirely up to you. The `package` task will pass the a full path to directory where the deploy.sh should copy the plugin files.  deploy.sh must use this *target directory* to as the target when it copies the files into the build directory.

This example is a deploy.sh that clones a git repository and deploys the plugin files into build space to be packaged.

    #!/bin/bash
    set -e

    export MYTARGETDIR=$1

    # determine the directory where this script resides
    DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

    # get source files
    TEMPDIR=`mktemp -d`
    git clone https://github.com/ctsit/redcap-custom-dashboard.git $TEMPDIR

    # copy files to the correct target locations
    mkdir -p $MYTARGETDIR
    cp $TEMPDIR/index.php $MYTARGETDIR
    cp $TEMPDIR/custom_dashboard.js $MYTARGETDIR

    rm -rf $TEMPDIR


text:
var Client = require('../../../../client'), constants = Client.constants;

module.exports = Client.sub({
	getTransactions: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/customer/accounts/{accountId}/transactions'
	}),
	addTransaction: Client.method({
		method: constants.verbs.POST,
		url: '{+tenantPod}api/commerce/customer/accounts/{accountId}/transactions?responseFields={responseFields}'
	}),
	removeTransaction: Client.method({
		method: constants.verbs.DELETE,
		url: '{+tenantPod}api/commerce/customer/accounts/{accountId}/transactions/{transactionId}'
	})
});


text:
package com.thoughtworks.go.apiv1.shared.representers.materials;

import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.api.representers.JsonReader;
import com.thoughtworks.go.config.materials.PasswordDeserializer;
import com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig;

public class TfsMaterialRepresenter {

    public static void toJSON(OutputWriter jsonWriter, TfsMaterialConfig tfsMaterialConfig) {
        ScmMaterialRepresenter.toJSON(jsonWriter, tfsMaterialConfig);
        jsonWriter.add("url", tfsMaterialConfig.getUrl());
        jsonWriter.add("domain", tfsMaterialConfig.getDomain());
        jsonWriter.add("username", tfsMaterialConfig.getUserName());
        jsonWriter.addIfNotNull("encrypted_password", tfsMaterialConfig.getEncryptedPassword());
        jsonWriter.add("project_path", tfsMaterialConfig.getProjectPath());
    }

    public static TfsMaterialConfig fromJSON(JsonReader jsonReader, ConfigHelperOptions options) {
        TfsMaterialConfig tfsMaterialConfig = new TfsMaterialConfig();
        ScmMaterialRepresenter.fromJSON(jsonReader, tfsMaterialConfig);
        jsonReader.readStringIfPresent("url", tfsMaterialConfig::setUrl);
        jsonReader.readStringIfPresent("domain", tfsMaterialConfig::setDomain);
        jsonReader.readStringIfPresent("username", tfsMaterialConfig::setUserName);
        jsonReader.readStringIfPresent("project_path", tfsMaterialConfig::setProjectPath);
        String password = null, encryptedPassword = null;
        if (jsonReader.hasJsonObject("password")) {
            password = jsonReader.getString("password");
        }
        if (jsonReader.hasJsonObject("encrypted_password")) {
            encryptedPassword = jsonReader.getString("encrypted_password");
        }
        PasswordDeserializer passwordDeserializer = options.getPasswordDeserializer();
        String encryptedPasswordValue = passwordDeserializer.deserialize(password, encryptedPassword, tfsMaterialConfig);
        tfsMaterialConfig.setEncryptedPassword(encryptedPasswordValue);
        return tfsMaterialConfig;
    }
}


text:
from pandas import read_csv

from orm import Base, Float, Point
from utils import parse_date_time, xa

"""
Extract, transform, and load procedure for floats database
"""

# column definitions
DATA_COLS='ID,DATE,TIME,LAT,LON,PRESS,U,V,TEMP,Q_TIME,Q_POS,Q_PRESS,Q_VEL,Q_TEMP'.split(',')
METADATA_COLS='ID,PRINCIPAL_INVESTIGATOR,ORGANIZATION,EXPERIMENT,1st_DATE,1st_LAT,1st_LON,END_DATE,END_LAT,END_LON,TYPE,FILENAME'.split(',')

# separators
DATA_SEPARATOR=r'\s+'
METADATA_SEPARATOR=r'(?:\b|\))(?:\s*\t+\s*|\s\s)(?=[-0-9a-zA-Z])'

# number of points to process at once
CHUNK_SIZE=10000

# local database connection information
DATABASE_URL='postgresql://floats:floats@localhost/floats'

def etl_data():
    """
    Load CSV file containing point data for all floats
    """
    n = 0
    for chunk in read_csv('./data/floats.dat',sep=DATA_SEPARATOR,iterator=True,chunksize=CHUNK_SIZE):
        chunk.fillna(0,inplace=True) # FIXME handle NA's better, e.g., with NULLs
        with xa(DATABASE_URL) as session:
            for index, row in chunk.iterrows():
                pt = Point(**{
                    'float_id': row.ID,
                    'date': parse_date_time(row.DATE, row.TIME),
                    'lat': row.LAT,
                    'lon': row.LON,
                    'pressure': row.PRESS,
                    'u': row.U,
                    'v': row.V,
                    'temperature': row.TEMP,
                    'q_time': row.Q_TIME,
                    'q_pos': row.Q_POS,
                    'q_press': row.Q_PRESS,
                    'q_vel': row.Q_VEL,
                    'q_temp': row.Q_TEMP
                })
                session.add(pt)
        n += len(chunk.index)
        print 'added %d point(s)...' % n

def etl_metadata():
    """
    Load CSV file containing metadata for all floats
    """
    df = read_csv('./data/floats_dirfl.dat',sep=METADATA_SEPARATOR,index_col=False)
    print 'adding %s float(s)...' % len(df.index)
    with xa(DATABASE_URL, Base.metadata) as session:
        for index, row in df.iterrows():
            flt = Float(**{
                    'id': row.ID,
                    'pi': row.PRINCIPAL_INVESTIGATOR,
                    'organization': row.ORGANIZATION,
                    'experiment': row.EXPERIMENT,
                    'start_date': row['1st_DATE'],
                    'start_lat': row['1st_LAT'],
                    'start_lon': row['1st_LON'],
                    'end_date': row.END_DATE,
                    'end_lat': row.END_LAT,
                    'end_lon': row.END_LON,
                    'type': row.TYPE,
                    'filename': row.FILENAME
                    })
            session.add(flt)

def etl_tracks():
    """
    Once float and point data is loaded, generate a track geometry
    for each float from the point data. This has less information in it
    than the point data and is used for geospatial queries
    """
    with xa(DATABASE_URL) as session:
        n = 0
        # for each float, construct a WKT LINESTRING geometry
        for f in session.query(Float).order_by(Float.id):
            prev_lon = 0
            ls = []
            ps = []
            np = 0
            # for all the points in this float's track:
            for p in f.points:
                if p.lon != -999 and p.lat != -99: # exclude noninformative points
                    np += 1
                    lat, lon = float(p.lat), float(p.lon)
                    # what if float just crossed the int'l date line
                    if (prev_lon < -90 and lon > 90) or (prev_lon > 90 and lon < -90):
                        if len(ps)==1:
                            ps = ps + ps
                        ls += [ps]
                        ps = []
                    ps.append('%.6f %.6f' % (lon, lat))
                    prev_lon = lon
            if len(ps) == 1: # need more than one point
                ps = ps + ps
            ls += [ps]
            # format in WKT
            ls = 'MULTILINESTRING(%s)' % ','.join(['(%s)' % ','.join(ps) for ps in ls])
            print '%d: Float %ld %d points' % (n, f.id, np)
            f.track = ls
            n += 1
            if n % 100 == 0: # commit occasionally
                session.commit()
            # final commit is handled by the context manager

def etl():
    """
    Extract, transform, and load all data.
    """
    etl_metadata() # first, float metadata
    etl_data() # then all data
    etl_tracks() # then geospatial tracks

if __name__=='__main__':
    """
    Extract, transform, and load all data
    """
    etl()


text:
package com.kunsoftware.controller.manager;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kunsoftware.bean.JsonBean;
import com.kunsoftware.bean.OrdersCashRequestBean;
import com.kunsoftware.controller.BaseController;
import com.kunsoftware.entity.Orders;
import com.kunsoftware.entity.OrdersCash;
import com.kunsoftware.exception.KunSoftwareException;
import com.kunsoftware.service.OrdersCashService;
import com.kunsoftware.service.OrdersService;

@Controller
@RequestMapping("/manager/orderscash")
public class OrdersCashController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(OrdersCashController.class);

	@Autowired
	private OrdersCashService service;

	@Autowired
	private OrdersService ordersService;

	@RequestMapping("/list")
	public String listOrdersCash(ModelMap model,Integer ordersId) throws KunSoftwareException {

		logger.info("收款列表");

		Orders orders = ordersService.selectByPrimaryKey(ordersId);
		List<OrdersCash> list = service.getOrdersCashListAll(ordersId);
		model.addAttribute("retList", list);
		model.addAttribute("orders", orders);
		return "manager/orderscash/orderscash-list";
	}

	@RequestMapping("/add")
	public String addOrdersCash(ModelMap model) throws KunSoftwareException {

		logger.info("添加收款");

		return "manager/orderscash/orderscash-add";
	}

	@RequestMapping(value="/add.json")
	@ResponseBody
	public JsonBean addOrdersCash(OrdersCashRequestBean requestBean) throws KunSoftwareException {

		logger.info("保存收款");

		OrdersCash entity = service.insert(requestBean);
		JsonBean jsonBean = new JsonBean();
		jsonBean.put("id", entity.getId());
		jsonBean.setMessage("操作成功");
		return jsonBean;
	}

	@RequestMapping("/edit")
	public String editOrdersCash(ModelMap model,Integer id) throws KunSoftwareException {

		logger.info("编辑收款");
		OrdersCash entity = service.selectByPrimaryKey(id);
		model.addAttribute("entity", entity);

		return "manager/orderscash/orderscash-edit";
	}

	@RequestMapping(value="/edit.json")
	@ResponseBody
	public JsonBean editOrdersCash(OrdersCashRequestBean requestBean,Integer id) throws KunSoftwareException {

		logger.info("编辑保存收款");

		service.updateByPrimaryKey(requestBean,id);
		JsonBean jsonBean = new JsonBean();
		jsonBean.setMessage("操作成功");
		return jsonBean;
	}

	@RequestMapping(value="/del.json")
	@ResponseBody
	public JsonBean delOrdersCash(Integer[] id) throws KunSoftwareException {

		logger.info("删除收款");
		service.deleteByPrimaryKey(id);
		JsonBean jsonBean = new JsonBean();
		jsonBean.setMessage("操作成功");
		return jsonBean;
	}

}


text:
require 'spec_helper'

describe Walkon do
  it "runs a daemon for playing entrance music" do
    expect(Walkon).to respond_to :start
  end
end


text:
<?xml version="1.0"?>
<ruleset name="PsySH Coding Standard">
    <description>The coding standard for PsySH</description>

    <exclude-pattern>*/bin/*</exclude-pattern>
    <exclude-pattern>*/vendor/*</exclude-pattern>

    <rule ref="PSR2">
        <exclude name="Generic.Functions.FunctionCallArgumentSpacing.TooMuchSpaceAfterComma"/>
    </rule>
</ruleset>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 Karl Bennett
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

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

    <parent>
        <groupId>com.github.shiver-me-timbers</groupId>
        <artifactId>multi-invoker-maven-plugin-test</artifactId>
        <version>1.2-SNAPSHOT</version>
    </parent>

    <artifactId>once-for-each-invocation</artifactId>

    <name>${project.artifactId}</name>

    <description>
        This pom test that the multi-invoker-maven-plugin can run the current project once for each configured item.
    </description>

    <properties>
        <test-invocations>invocation-one,invocation-two,invocation-three</test-invocations>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>com.github.shiver-me-timbers</groupId>
                <artifactId>multi-invoker-maven-plugin</artifactId>
                <version>1.2-SNAPSHOT</version>
                <executions>
                    <execution>
                        <id>multi-invoker</id>
                        <goals>
                            <goal>invoker</goal>
                        </goals>
                        <configuration>
                            <logLevel>ERROR</logLevel>
                            <invocations>${test-invocations}</invocations>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <configuration>
                    <dependenciesToScan>
                        <depedency>com.github.shiver-me-timbers:once-for-each-invocation-it</depedency>
                    </dependenciesToScan>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-install-plugin</artifactId>
                <version>2.5.2</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <executions>
                    <execution>
                        <id>default-jar</id>
                        <phase>none</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>

        <directory>${project.basedir}/target/${invocation.id}</directory>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.github.shiver-me-timbers</groupId>
            <artifactId>once-for-each-invocation-it</artifactId>
            <version>1.2-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>


text:
require "DAL"
class Location < ActiveRecord::Base
  self.table_name = "location"

  #Return nearest location, if no return nil
  def self.find_nearest_point long, lat
    return DAL.findNearestPoint(long, lat)
  end
end


text:
package ua.com.fielden.platform.domain;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import ua.com.fielden.platform.attachment.Attachment;
import ua.com.fielden.platform.attachment.AttachmentPreviewEntityAction;
import ua.com.fielden.platform.attachment.AttachmentUploader;
import ua.com.fielden.platform.attachment.AttachmentsUploadAction;
import ua.com.fielden.platform.dashboard.DashboardRefreshFrequency;
import ua.com.fielden.platform.dashboard.DashboardRefreshFrequencyUnit;
import ua.com.fielden.platform.domain.metadata.DomainExplorer;
import ua.com.fielden.platform.domain.metadata.DomainExplorerInsertionPoint;
import ua.com.fielden.platform.domain.metadata.DomainProperty;
import ua.com.fielden.platform.domain.metadata.DomainPropertyHolder;
import ua.com.fielden.platform.domain.metadata.DomainPropertyTreeEntity;
import ua.com.fielden.platform.domain.metadata.DomainTreeEntity;
import ua.com.fielden.platform.domain.metadata.DomainType;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.EntityDeleteAction;
import ua.com.fielden.platform.entity.EntityEditAction;
import ua.com.fielden.platform.entity.EntityExportAction;
import ua.com.fielden.platform.entity.EntityNewAction;
import ua.com.fielden.platform.entity.SecurityMatrixInsertionPoint;
import ua.com.fielden.platform.entity.SecurityMatrixSaveAction;
import ua.com.fielden.platform.entity.SecurityTokenTreeNodeEntity;
import ua.com.fielden.platform.entity.functional.centre.CentreContextHolder;
import ua.com.fielden.platform.entity.functional.centre.SavingInfoHolder;
import ua.com.fielden.platform.entity.functional.master.AcknowledgeWarnings;
import ua.com.fielden.platform.entity.functional.master.PropertyWarning;
import ua.com.fielden.platform.keygen.KeyNumber;
import ua.com.fielden.platform.master.MasterInfo;
import ua.com.fielden.platform.menu.Action;
import ua.com.fielden.platform.menu.CustomView;
import ua.com.fielden.platform.menu.EntityCentreView;
import ua.com.fielden.platform.menu.EntityMasterView;
import ua.com.fielden.platform.menu.Menu;
import ua.com.fielden.platform.menu.MenuSaveAction;
import ua.com.fielden.platform.menu.ModuleMenu;
import ua.com.fielden.platform.menu.ModuleMenuItem;
import ua.com.fielden.platform.menu.UserMenuVisibilityAssociator;
import ua.com.fielden.platform.menu.View;
import ua.com.fielden.platform.menu.WebMenuItemInvisibility;
import ua.com.fielden.platform.migration.MigrationError;
import ua.com.fielden.platform.migration.MigrationHistory;
import ua.com.fielden.platform.migration.MigrationRun;
import ua.com.fielden.platform.ref_hierarchy.ReferenceHierarchy;
import ua.com.fielden.platform.ref_hierarchy.ReferenceHierarchyEntry;
import ua.com.fielden.platform.ref_hierarchy.ReferenceLevelHierarchyEntry;
import ua.com.fielden.platform.ref_hierarchy.ReferencedByLevelHierarchyEntry;
import ua.com.fielden.platform.ref_hierarchy.TypeLevelHierarchyEntry;
import ua.com.fielden.platform.security.session.UserSession;
import ua.com.fielden.platform.security.user.ReUser;
import ua.com.fielden.platform.security.user.SecurityRoleAssociation;
import ua.com.fielden.platform.security.user.SecurityTokenInfo;
import ua.com.fielden.platform.security.user.User;
import ua.com.fielden.platform.security.user.UserAndRoleAssociation;
import ua.com.fielden.platform.security.user.UserRole;
import ua.com.fielden.platform.security.user.UserRoleTokensUpdater;
import ua.com.fielden.platform.security.user.UserRolesUpdater;
import ua.com.fielden.platform.security.user.UserSecret;
import ua.com.fielden.platform.security.user.locator.UserLocator;
import ua.com.fielden.platform.security.user.master.menu.actions.UserMaster_OpenMain_MenuItem;
import ua.com.fielden.platform.security.user.master.menu.actions.UserMaster_OpenUserAndRoleAssociation_MenuItem;
import ua.com.fielden.platform.security.user.ui_actions.OpenUserMasterAction;
import ua.com.fielden.platform.ui.config.EntityCentreAnalysisConfig;
import ua.com.fielden.platform.ui.config.EntityCentreConfig;
import ua.com.fielden.platform.ui.config.EntityLocatorConfig;
import ua.com.fielden.platform.ui.config.EntityMasterConfig;
import ua.com.fielden.platform.ui.config.MainMenuItem;
import ua.com.fielden.platform.web.centre.CentreColumnWidthConfigUpdater;
import ua.com.fielden.platform.web.centre.CentreConfigConfigureAction;
import ua.com.fielden.platform.web.centre.CentreConfigDeleteAction;
import ua.com.fielden.platform.web.centre.CentreConfigDuplicateAction;
import ua.com.fielden.platform.web.centre.CentreConfigEditAction;
import ua.com.fielden.platform.web.centre.CentreConfigLoadAction;
import ua.com.fielden.platform.web.centre.CentreConfigNewAction;
import ua.com.fielden.platform.web.centre.CentreConfigSaveAction;
import ua.com.fielden.platform.web.centre.CentreConfigShareAction;
import ua.com.fielden.platform.web.centre.CentreConfigUpdater;
import ua.com.fielden.platform.web.centre.CentrePreferredViewUpdater;
import ua.com.fielden.platform.web.centre.CustomisableColumn;
import ua.com.fielden.platform.web.centre.LoadableCentreConfig;
import ua.com.fielden.platform.web.centre.OverrideCentreConfig;

public class PlatformDomainTypes {
    public static final List<Class<? extends AbstractEntity<?>>> types = new ArrayList<>();
    public static final Set<Class<? extends AbstractEntity<?>>> typesDependentOnWebUI = new LinkedHashSet<>();
    public static final Set<Class<? extends AbstractEntity<?>>> typesNotDependentOnWebUI = new LinkedHashSet<>();

    static {
        types.add(MainMenuItem.class);
        types.add(User.class);
        types.add(ReUser.class);
        types.add(UserLocator.class);
        types.add(UserSecret.class);
        types.add(UserRolesUpdater.class);
        types.add(UserSession.class);
        types.add(UserRole.class);
        types.add(UserRoleTokensUpdater.class);
        types.add(SecurityTokenInfo.class);

        types.add(CentreConfigUpdater.class);
        types.add(CustomisableColumn.class);
        types.add(CentreColumnWidthConfigUpdater.class);
        types.add(CentrePreferredViewUpdater.class);
        types.add(CentreConfigShareAction.class);
        types.add(CentreConfigNewAction.class);
        types.add(CentreConfigDuplicateAction.class);
        types.add(CentreConfigLoadAction.class);
        types.add(CentreConfigEditAction.class);
        types.add(CentreConfigDeleteAction.class);
        types.add(CentreConfigSaveAction.class);
        types.add(LoadableCentreConfig.class);
        types.add(OverrideCentreConfig.class);
        types.add(CentreConfigConfigureAction.class);
        types.add(DashboardRefreshFrequencyUnit.class);
        types.add(DashboardRefreshFrequency.class);

        types.add(UserAndRoleAssociation.class);
        types.add(SecurityRoleAssociation.class);
        types.add(EntityCentreConfig.class);
        types.add(EntityCentreAnalysisConfig.class);
        types.add(EntityMasterConfig.class);
        types.add(EntityLocatorConfig.class);
        types.add(Attachment.class);
        types.add(AttachmentUploader.class);
        types.add(AttachmentsUploadAction.class);
        types.add(KeyNumber.class);
        types.add(MigrationRun.class);
        types.add(MigrationHistory.class);
        types.add(MigrationError.class);
        types.add(CentreContextHolder.class);
        types.add(SavingInfoHolder.class);
        types.add(EntityNewAction.class);
        types.add(EntityEditAction.class);
        types.add(EntityDeleteAction.class);
        types.add(EntityExportAction.class);
        types.add(AcknowledgeWarnings.class);
        types.add(PropertyWarning.class);
        types.add(ModuleMenuItem.class);
        types.add(EntityCentreView.class);
        types.add(View.class);
        types.add(CustomView.class);
        types.add(ModuleMenu.class);
        types.add(Menu.class);
        types.add(EntityMasterView.class);
        types.add(MenuSaveAction.class);
        types.add(WebMenuItemInvisibility.class);
        types.add(SecurityMatrixInsertionPoint.class);
        types.add(SecurityTokenTreeNodeEntity.class);
        types.add(SecurityMatrixSaveAction.class);
        types.add(AttachmentPreviewEntityAction.class);
        types.add(MasterInfo.class);
        types.add(ReferenceHierarchy.class);
        types.add(ReferenceHierarchyEntry.class);
        types.add(TypeLevelHierarchyEntry.class);
        types.add(ReferencedByLevelHierarchyEntry.class);
        types.add(ReferenceLevelHierarchyEntry.class);
        types.add(Action.class);
        types.add(DomainType.class);
        types.add(DomainProperty.class);
        types.add(DomainPropertyHolder.class);
        types.add(DomainExplorer.class);
        types.add(DomainExplorerInsertionPoint.class);
        types.add(DomainTreeEntity.class);
        types.add(DomainPropertyTreeEntity.class);
        types.add(UserMenuVisibilityAssociator.class);
        types.add(OpenUserMasterAction.class);
        types.add(UserMaster_OpenMain_MenuItem.class);
        types.add(UserMaster_OpenUserAndRoleAssociation_MenuItem.class);

        typesDependentOnWebUI.add(EntityExportAction.class);
        typesDependentOnWebUI.add(CentreConfigUpdater.class);
        typesDependentOnWebUI.add(CentreConfigLoadAction.class);
        typesDependentOnWebUI.add(CentreConfigEditAction.class);
        typesDependentOnWebUI.add(CentreConfigSaveAction.class);
        typesDependentOnWebUI.add(CentreConfigConfigureAction.class);

        typesNotDependentOnWebUI.addAll(types);
        typesNotDependentOnWebUI.removeAll(typesDependentOnWebUI);
    }
}


text:
namespace EventService.Migrations
{
    using Data;
    using Data.Helpers;
    using System.Data.Entity.Migrations;

    internal sealed class Configuration : DbMigrationsConfiguration<EventServiceContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(EventServiceContext context)
        {
            TenantConfiguration.Seed(context);
            RoleConfiguration.Seed(context);
            UserConfiguration.Seed(context);
        }
    }

    public class DbConfiguration : System.Data.Entity.DbConfiguration
    {
        public DbConfiguration()
        {
            AddInterceptor(new SoftDeleteInterceptor());
        }
    }
}


text:
"use strict";

const fs = require("fs");
const path = require("path");
const Yargs = require("yargs");

// parse .env file into process.env
require('dotenv').config();

const cryptoEngine = require("../lib/cryptoEngine/cryptojsEngine");
const codec = require("../lib/codec");
const { convertCommonJSToBrowserJS, exitEarly, isOptionSetByUser, genFile, getPassword, getFileContent, getSalt} = require("./helpers");
const { generateRandomSalt } = cryptoEngine;
const { encode } = codec.init(cryptoEngine);

const SCRIPT_URL =
  "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js";
const SCRIPT_TAG =
  '<script src="' +
  SCRIPT_URL +
  '" integrity="sha384-lp4k1VRKPU9eBnPePjnJ9M2RF3i7PC30gXs70+elCVfgwLwx1tv5+ctxdtwxqZa7" crossorigin="anonymous"></script>';

const yargs = Yargs.usage("Usage: staticrypt <filename> [<passphrase>] [options]")
  .option("c", {
    alias: "config",
    type: "string",
    describe: 'Path to the config file. Set to "false" to disable.',
    default: ".staticrypt.json",
  })
  .option("decrypt-button", {
    type: "string",
    describe: 'Label to use for the decrypt button. Default: "DECRYPT".',
    default: "DECRYPT",
  })
  .option("e", {
    alias: "embed",
    type: "boolean",
    describe:
      "Whether or not to embed crypto-js in the page (or use an external CDN).",
    default: true,
  })
  .option("f", {
    alias: "file-template",
    type: "string",
    describe: "Path to custom HTML template with passphrase prompt.",
    default: path.join(__dirname, "..", "lib", "password_template.html"),
  })
  .option("i", {
    alias: "instructions",
    type: "string",
    describe: "Special instructions to display to the user.",
    default: "",
  })
  .option("label-error", {
    type: "string",
    describe: "Error message to display on entering wrong passphrase.",
    default: "Bad password!",
  })
  .option("noremember", {
    type: "boolean",
    describe: 'Set this flag to remove the "Remember me" checkbox.',
    default: false,
  })
  .option("o", {
    alias: "output",
    type: "string",
    describe: "File name / path for generated encrypted file.",
    default: null,
  })
  .option("passphrase-placeholder", {
    type: "string",
    describe: "Placeholder to use for the passphrase input.",
    default: "Password",
  })
  .option("r", {
    alias: "remember",
    type: "number",
    describe:
      'Expiration in days of the "Remember me" checkbox that will save the (salted + hashed) passphrase ' +
      'in localStorage when entered by the user. Default: "0", no expiration.',
    default: 0,
  })
  .option("remember-label", {
    type: "string",
    describe: 'Label to use for the "Remember me" checkbox.',
    default: "Remember me",
  })
  // do not give a default option to this parameter - we want to see when the flag is included with no
  // value and when it's not included at all
  .option("s", {
    alias: "salt",
    describe:
      'Set the salt manually. It should be set if you want use "Remember me" through multiple pages. It ' +
      "needs to be a 32 character long hexadecimal string.\nInclude the empty flag to generate a random salt you " +
      'can use: "statycrypt -s".',
    type: "string",
  })
  // do not give a default option to this parameter - we want to see when the flag is included with no
  // value and when it's not included at all
  .option("share", {
    describe:
      'Get a link containing your hashed password that will auto-decrypt the page. Pass your URL as a value to append '
        + '"?staticrypt_pwd=<hashed_pwd>", or leave empty to display the hash to append.',
    type: "string",
  })
  .option("t", {
    alias: "title",
    type: "string",
    describe: "Title for output HTML page.",
    default: "Protected Page",
  });
const namedArgs = yargs.argv;

// if the 's' flag is passed without parameter, generate a salt, display & exit
if (isOptionSetByUser("s", yargs) && !namedArgs.salt) {
  console.log(generateRandomSalt());
  process.exit(0);
}

// validate the number of arguments
const positionalArguments = namedArgs._;
if (positionalArguments.length > 2 || positionalArguments.length === 0) {
  Yargs.showHelp();
  process.exit(1);
}

// parse input
const inputFilepath = positionalArguments[0].toString(),
  password = getPassword(positionalArguments);

// get config file
const isUsingconfigFile = namedArgs.config.toLowerCase() !== "false";
const configPath = "./" + namedArgs.config;
let config = {};
if (isUsingconfigFile && fs.existsSync(configPath)) {
  config = JSON.parse(fs.readFileSync(configPath, "utf8"));
}

// get the salt
const salt = getSalt(namedArgs, config);

// validate the salt
if (salt.length !== 32 || /[^a-f0-9]/.test(salt)) {
  exitEarly(
    "The salt should be a 32 character long hexadecimal string (only [0-9a-f] characters allowed)"
      + "\nDetected salt: " + salt
  );
}

// write salt to config file
if (isUsingconfigFile && config.salt !== salt) {
  config.salt = salt;
  fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
}

// display the share link with the hashed password if the --share flag is set
if (isOptionSetByUser("share", yargs)) {
    const url = namedArgs.share || "";
    const hashedPassphrase = cryptoEngine.hashPassphrase(password, salt);

    console.log(url + "?staticrypt_pwd=" + hashedPassphrase);
}

// get the file content
const contents = getFileContent(inputFilepath);

// encrypt input
const encryptedMessage = encode(contents, password, salt);

// create crypto-js tag (embedded or not)
let cryptoTag = SCRIPT_TAG;
if (namedArgs.embed) {
  try {
    const embedContents = fs.readFileSync(
      path.join(__dirname, "..", "lib", "kryptojs-3.1.9-1.min.js"),
      "utf8"
    );

    cryptoTag = "<script>" + embedContents + "</script>";
  } catch (e) {
    exitEarly("Failure: embed file does not exist!");
  }
}

const data = {
  crypto_tag: cryptoTag,
  decrypt_button: namedArgs.decryptButton,
  embed: namedArgs.embed,
  encrypted: encryptedMessage,
  instructions: namedArgs.instructions,
  is_remember_enabled: namedArgs.noremember ? "false" : "true",
  js_codec: convertCommonJSToBrowserJS("lib/codec"),
  js_crypto_engine: convertCommonJSToBrowserJS("lib/cryptoEngine/cryptojsEngine"),
  label_error: namedArgs.labelError,
  passphrase_placeholder: namedArgs.passphrasePlaceholder,
  remember_duration_in_days: namedArgs.remember,
  remember_me: namedArgs.rememberLabel,
  salt: salt,
  title: namedArgs.title,
};

const outputFilePath = namedArgs.output !== null
    ? namedArgs.output
    : inputFilepath.replace(/\.html$/, "") + "_encrypted.html";

genFile(data, outputFilePath, namedArgs.f);


text:
<?php

/**
* 	$image = new PhrailsPaperclip('image', 'File, Rsc', 'user:null', 'key:null');
*
*	$image->path('/assets/images/{id}/{file-name}-{style}.{extension}')
*
*	$image->style('medium', '300X300>');
*	$image->style('thumb', '25X25#', 'png')
*
*	$schema->rule('image_file_name', $image->content_type_rule('image/png', 'image/jpeg', 'image/jpg'));
*
*	$this->image = $image;
*
*
*	//Stores the asset where it should go file or Rsc or ...
*	//Throws an exception if the file can not get saved.
*	//returns an array of items to be stored in the model.
*	$this->image->process();
*/
class PhrailsPaperclip
{
	const original = 'original';

	private $model, $column, $storage, $container=null, $styles=array(), $path, $hasPath=false;
	private $public=false;
	/**
	 * The storage object making
	 */
	private $attachment;
	/**
	 * Store the url when we get it.
	 */
	private $url = null;

	private $file_content_for_upload;

	private $files = array();

	private $valid_storage = array('File', 'Rsc');

	function __construct($model, $column, $storage='File')
	{
		$key = array_pop(explode('\\', get_class($model)));
		$config = Registry::get('pr-plugin-phrails-paperclip');
		if($config === null || !(isset($config->$key))){
			throw new Exception('Phrails Paperclip relies on having a config/phrails-paperclip.ini file defined correctly.');
		}
		//Set storage and container before we make sure that we have a
		//valid storage type.
		$this->storage = $storage;
		//If we have what we need for a cloud service then feed it to the object
		if(isset($config->global, $config->$key)){
			$this->setAttachmentObject($config->$key, $config->global->user, $config->global->key);
			$this->container = $config->$key;
		//Else just pass null
		}else{
			//Make sure we have a valid storage area and create it.
			$this->setAttachmentObject();
		}
		//Initialize the vars
		$this->column = $column;
		$this->model = $model;
		$property = $column . '_file_name';
		$this->model->$property = $this->get('name');
		$this->addFilter();
		$this->model->$column = $this;
		$this->styles = array();
	}

	/**
	 * Add the filter if we can at this time.
	 *
	 * @return void
	 */
	public function addFilter(){
		$property = $this->column . '_file_name';
		if($this->canUpload() && $this->model->$property !== null){

			//If we can let's set the mime_type and size
			try {
				$this->model->mime_type = $this->get('type');
				$this->model->size = $this->get('size');
			} catch (\NoColumnInTableException $e) {}
			$this->model->filters()->afterSave(array($this->column, 'write'));
		}
	}

	/**
	 * Set the stream to upload a file.
	 *
	 * @return void
	 */
	public function setFileContentForUpload($content){
		$this->file_content_for_upload = $content;
		$this->addFilter();
	}

	/**
	 * Store the asset where it belongs.
	 *
	 * @throws Exception
	 * @return void
	 * @author Justin Palmer
	 **/
	public function write()
	{
		//If we don't have a file we will return.
		if(!$this->canUpload())
			return;

		//Process styles.
		if(empty($this->styles)){
			$path = $this->getPath();
			$file = (is_null($this->file_content_for_upload)) ? $this->get('tmp_name') : $this->file_content_for_upload;
			$this->files[] = array($file, $path);
		}else{
			$this->convert();
		}
		try{
			foreach($this->files as $array){
				$this->attachment->write($array[0], $array[1]);
			}
		}catch(InvalidResponseException $e){
			$this->model->errors()->set('invalid-response', 'The system could not perform the upload requested due to an invalid response.  If the problem persists please contact support.');
			return false;
		}catch(Exception $e){
			$this->model->errors()->set('exception', 'The system could not perform the upload requested due to an unknown exception.  If the problem persists please contact support. ' . $e->getCode() . ':' . $e->getMessage());
			return false;
		}
	}

	/**
	 * Get the path to the file
	 *
	 * @param string $style
	 * @return string
	 * @author Justin Palmer
	 **/
	public function getPath($style='')
	{
		$path = '';

		if($this->container !== null && !$this->hasPath())
			return $this->get('name');

		$model_column_name = $this->column . '_file_name';
		$style = ($style === '') ? self::original : $style;
		$files_name = $this->get('name');
		if($files_name === null){
			$files_name = $this->model->$model_column_name;
		}
		$pieces = explode('.', $files_name);
		$extension = '';
		if(sizeof($pieces) > 1)
			$extension = array_pop($pieces);
		$file_name_no_extension = implode('.', $pieces);
		if($this->hasPath()){
			$path = $this->path;
			$id = $this->model->primary_key();
			$path = str_replace('{id}', $this->model->$id, $path);
			$path = str_replace('{file-name}', $file_name_no_extension, $path);
			$path = str_replace('{style}', $style, $path);
			$path = str_replace('{extension}', $extension, $path);
			$path = str_replace('{time}', time(), $path);
		}else{
			$install_path = Registry::get('pr-install-path');
			$default_path = $install_path . '/public/images/paperclip/';
			$file_name = $file_name_no_extension . '-' . $style;
			if($extension != '')
			 	$file_name .= '.' . $extension;
			$path = $default_path . $file_name;
		}
		return $this->getGoodFileName($path);
	}

	/**
	 * convert the images according to the styles.
	 *
	 * @return void
	 * @author Justin Palmer
	 **/
	private function convert()
	{
		foreach($this->styles as $style){
			$path = $name = $this->getPath($style->style);
			if($this->storage !== 'File'){
				$path = '/tmp/' . $name;
			}
			setlocale(LC_CTYPE, "en_US.UTF-8");
			$command = "convert " . $this->get('tmp_name') . " -resize $style->size $style->command $path";
			$command = escapeshellcmd($command);
			`$command`;
			$this->files[] = array($path, $name);
		}
	}

	/**
	 * Get the url for the item.
	 *
	 * @return void
	 * @author Justin Palmer
	 **/
	public function url($style='', $stream=false)
	{
		$model_column_name = $this->column . '_file_name';
		$file = $this->model->$model_column_name;
		if($file == '')
			return '';

		if($this->url !== null)
			return $this->url;

		//print 'url' . '
';
		if($this->storage != 'File'){
			if($this->hasPath()){
				$file = $this->getPath($style);
			}
			$this->url = ($stream) ? $this->attachment->stream($file, 'inline')
								   : $this->attachment->read($file);
			return $this->url;
		}else{
			return $this->url = $this->getPath($style);
		}
	}

	/**
	 * Download the file.
	 *
	 * @return mixed
	 * @author Justin Palmer
	 **/
	public function download($disposition='attachment')
	{
		$send_mime_type = true;
		if($this->storage != 'File'){
			$model_column_name = $this->column . '_file_name';
			$file = $this->model->$model_column_name;
			if($this->hasPath()){
				$file = $this->getPath();
			}
			//If we can send the headers let's try.
			try {
				header('Content-Disposition: ' . $disposition . '; filename="' . $this->model->$model_column_name . '"');
				//make sure the mimetype is here before we build the header
				//$this->model->mime_type;
				//header('Content-Type: ' . $this->model->mime_type);
				//make sure the size is here before we build the header
				//$this->model->size;
				//header('Content-Length: ' . $this->model->size);
			} catch (\NoColumnInTableException $e) {
				$send_mime_type = true;
			}
			$this->attachment->stream($file, $send_mime_type);
		}
	}

	/**
	 * Set the various styles for images
	 *
	 * @param string $name
	 * @param string $size Size will be passed to the -resize parameter of convert
	 * @param string $command Additional commands to be passed to convert
	 * @return void
	 * @author Justin Palmer
	 **/
	public function style($style, $size, $command='')
	{
		$o = new stdClass;
		$o->style = $style;
		$o->size = $size;
		$o->command = $command;
		$this->styles[] = $o;
	}

	/**
	 * Set the rule for the attachment
	 *
	 * @return ContentTypeRule
	 * @author Justin Palmer
	 **/
	public function content_type_rule($types)
	{
		$args = func_get_args();
		if(is_array($args[0])){
			$args = $args[0];
		}
		$type = (is_null($this->file_content_for_upload)) ? $this->get('type') : $args[0];
		return new ContentTypeRule($type, $args);
	}

	/**
	 * The path that the attachment should be saved to.
	 *
	 * @return void
	 * @author Justin Palmer
	 **/
	public function path($path)
	{
		$this->hasPath = true;
		$this->path = $path;
	}

	/**
	 * Did the user set a path
	 *
	 * @return string
	 * @author Justin Palmer
	 **/
	private function hasPath()
	{
		return $this->hasPath;
	}

	/**
	 * Should the attachment be public or private.
	 *
	 * This is ONLY taken into consideration when the storage is a cloud storage.
	 *
	 * @return void
	 * @author Justin Palmer
	 **/
	public function isPublic($public=false)
	{
		$this->public = $public;
	}

	/**
	 * Get information from the files global.
	 *
	 * @return string
	 * @author Justin Palmer
	 **/
	public function get($name)
	{
		$files_name = $this->column . '_file_name';
		$table_name = Inflections::singularize($this->model->table_name());
		//Is it in the files global, return it.
		if(isset($_FILES[$table_name][$name][$files_name]))
			return $_FILES[$table_name][$name][$files_name];
		//is the model property not null, return it.
		if($this->model->$files_name !== null)
			return $this->model->$files_name;
		return null;
	}

	public function fileUploaded(){
		return ($this->get('error') === UPLOAD_ERR_OK) ? true : false;
	}

	/**
	 * Create the correct storage object.
	 *
	 * @return InterfacePhrailsPaperclip
	 * @author Justin Palmer
	 **/
	private function setAttachmentObject($container=null, $user=null, $key=null)
	{
		//Make sure it is a valid storage mechanism.
		if(!in_array($this->storage, $this->valid_storage))
			throw new Exception('Invalid PhrailsPaperclip Storage mechanism.');

		$storage = 'PhrailsPaperclip' . $this->storage;

		$this->attachment = new $storage($container, $user, $key);
	}

	/**
	 * Take out spaces and other things in the filename
	 *
	 * @return void
	 * @author Justin Palmer
	 **/
	private function getGoodFileName($path)
	{
		return str_replace(' ', '-', $path);
	}

	/**
	 * Can we attempt a file upload
	 *
	 * @return boolean
	 */
	private function canUpload(){
		return ($this->fileUploaded() || !is_null($this->file_content_for_upload));
	}

}


text:
using System;
using System.Collections.Generic;
using PopForums.Configuration;
using PopForums.Models;
using PopForums.Repositories;

namespace PopForums.Data.SqlSingleWebServer.Repositories
{
	public class SubscribedTopicsRepository : ISubscribedTopicsRepository
	{
		public SubscribedTopicsRepository(ISqlObjectFactory sqlObjectFactory)
		{
			_sqlObjectFactory = sqlObjectFactory;
		}

		private readonly ISqlObjectFactory _sqlObjectFactory;

		public List<Topic> GetSubscribedTopics(int userID, int startRow, int pageSize)
		{
			var list = new List<Topic>();
			const string sql = @"
DECLARE @Counter int
SET @Counter = (@StartRow + @PageSize - 1)

SET ROWCOUNT @Counter;

WITH Entries AS (
SELECT ROW_NUMBER() OVER (ORDER BY IsPinned DESC, LastPostTime DESC)
AS Row, pf_Topic.TopicID, pf_Topic.ForumID, pf_Topic.Title, pf_Topic.ReplyCount, pf_Topic.ViewCount,
pf_Topic.StartedByUserID, pf_Topic.StartedByName, pf_Topic.LastPostUserID, pf_Topic.LastPostName,
pf_Topic.LastPostTime, pf_Topic.IsClosed, pf_Topic.IsPinned, pf_Topic.IsDeleted, pf_Topic.IsIndexed, pf_Topic.UrlName
FROM pf_Topic JOIN pf_SubscribeTopic S ON pf_Topic.TopicID = S.TopicID
WHERE S.UserID = @UserID AND pf_Topic.IsDeleted = 0)

SELECT TopicID, ForumID, Title, ReplyCount, ViewCount,
StartedByUserID, StartedByName, LastPostUserID, LastPostName,
LastPostTime, IsClosed, IsPinned, IsDeleted, IsIndexed, UrlName
FROM Entries
WHERE Row between
@StartRow and @StartRow + @PageSize - 1

SET ROWCOUNT 0";
			_sqlObjectFactory.GetConnection().Using(connection =>
				connection.Command(sql)
				.AddParameter("@UserID", userID)
				.AddParameter("@StartRow", startRow)
				.AddParameter("@PageSize", pageSize)
				.ExecuteReader()
				.ReadAll(r => list.Add(TopicRepository.GetTopicFromReader(r))));
			return list;
		}

		public int GetSubscribedTopicCount(int userID)
		{
			var count = 0;
			_sqlObjectFactory.GetConnection().Using(connection =>
				count = Convert.ToInt32(connection.Command("SELECT COUNT(*) FROM pf_SubscribeTopic S JOIN pf_Topic T ON S.TopicID = T.TopicID WHERE S.UserID = @UserID AND T.IsDeleted = 0")
				.AddParameter("@UserID", userID)
				.ExecuteScalar()));
			return count;
		}

		public List<User> GetSubscribedUsersThatHaveViewed(int topicID)
		{
			var list = new List<User>();
			_sqlObjectFactory.GetConnection().Using(connection =>
					connection.Command("SELECT " + UserRepository.PopForumsUserColumns + " FROM pf_PopForumsUser JOIN pf_SubscribeTopic ON pf_PopForumsUser.UserID = pf_SubscribeTopic.UserID WHERE TopicID = @TopicID AND IsViewed = 1")
					.AddParameter("@TopicID", topicID)
					.ExecuteReader()
					.ReadAll(r => list.Add(UserRepository.PopulateUser(r))));
			return list;
		}

		public bool IsTopicSubscribed(int userID, int topicID)
		{
			var result = false;
			_sqlObjectFactory.GetConnection().Using(connection =>
				connection.Command("SELECT * FROM pf_SubscribeTopic WHERE UserID = @UserID AND TopicID = @TopicID")
				.AddParameter("@UserID", userID)
				.AddParameter("@TopicID", topicID)
				.ExecuteReader()
				.ReadOne(r => result = true));
			return result;
		}

		public void AddSubscribedTopic(int userID, int topicID)
		{
			_sqlObjectFactory.GetConnection().Using(connection =>
				connection.Command("INSERT INTO pf_SubscribeTopic (UserID, TopicID, IsViewed) VALUES (@UserID, @TopicID, 1)")
				.AddParameter("@UserID", userID)
				.AddParameter("@TopicID", topicID)
				.ExecuteNonQuery());
		}

		public void RemoveSubscribedTopic(int userID, int topicID)
		{
			_sqlObjectFactory.GetConnection().Using(connection =>
				connection.Command("DELETE FROM pf_SubscribeTopic WHERE UserID = @UserID AND TopicID = @TopicID")
				.AddParameter("@UserID", userID)
				.AddParameter("@TopicID", topicID)
				.ExecuteNonQuery());
		}

		public void MarkSubscribedTopicViewed(int userID, int topicID)
		{
			_sqlObjectFactory.GetConnection().Using(connection =>
				connection.Command("UPDATE pf_SubscribeTopic SET IsViewed = 1 WHERE UserID = @UserID AND TopicID = @TopicID")
				.AddParameter("@UserID", userID)
				.AddParameter("@TopicID", topicID)
				.ExecuteNonQuery());
		}

		public void MarkSubscribedTopicUnviewed(int topicID)
		{
			_sqlObjectFactory.GetConnection().Using(connection =>
				connection.Command("UPDATE pf_SubscribeTopic SET IsViewed = 0 WHERE TopicID = @TopicID")
				.AddParameter("@TopicID", topicID)
				.ExecuteNonQuery());
		}
	}
}


text:
#include "config.h"
#include "MIMETypeRegistry.h"

#include "MediaPlayer.h"
#include "PlatformBridge.h"
#include "PluginDataChromium.h"
#include <wtf/text/CString.h>

// NOTE: Unlike other ports, we don't use the shared implementation bits in
// MIMETypeRegistry.cpp.  Instead, we need to route most functions via the
// PlatformBridge to the embedder.

namespace WebCore {

#if ENABLE(FILE_SYSTEM) && ENABLE(WORKERS)
String MIMETypeRegistry::getMIMETypeForExtensionThreadSafe(const String &ext)
{
    return PlatformBridge::mimeTypeForExtension(ext);
}
#endif

// NOTE: We have to define getMIMETypeForExtension() here though the shared
// implementation has getMIMETypeForExtension() since we don't use the shared
// implementation bits in MIMETypeRegistry.cpp.

String MIMETypeRegistry::getMIMETypeForExtension(const String &ext)
{
    return PlatformBridge::mimeTypeForExtension(ext);
}

// Returns the file extension if one is found.  Does not include the dot in the
// filename.  E.g., 'html'.
String MIMETypeRegistry::getPreferredExtensionForMIMEType(const String& type)
{
    // Prune out any parameters in case they happen to have snuck in there...
    // FIXME: Is this really necessary??
    String mimeType = type.substring(0, static_cast<unsigned>(type.find(';')));

    String ext = PlatformBridge::preferredExtensionForMIMEType(type);
    if (!ext.isEmpty() && ext[0] == '.')
        ext = ext.substring(1);

    return ext;
}

String MIMETypeRegistry::getMIMETypeForPath(const String& path)
{
    int pos = path.reverseFind('.');
    if (pos < 0)
        return "application/octet-stream";
    String extension = path.substring(pos + 1);
    String mimeType = getMIMETypeForExtension(extension);
    if (mimeType.isEmpty()) {
        // If there's no mimetype registered for the extension, check to see
        // if a plugin can handle the extension.
        mimeType = getPluginMimeTypeFromExtension(extension);
    }
    if (mimeType.isEmpty())
        return "application/octet-stream";
    return mimeType;
}

bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType)
{
    return PlatformBridge::isSupportedImageMIMEType(mimeType);
}

bool MIMETypeRegistry::isSupportedImageResourceMIMEType(const String& mimeType)
{
    return isSupportedImageMIMEType(mimeType);
}

bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType)
{
    return mimeType == "image/jpeg" || mimeType == "image/png";
}

bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType)
{
    return PlatformBridge::isSupportedJavaScriptMIMEType(mimeType);
}

bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType)
{
    return PlatformBridge::isSupportedNonImageMIMEType(mimeType);
}

bool MIMETypeRegistry::isSupportedMediaMIMEType(const String& mimeType)
{
    HashSet<String> supportedMediaMIMETypes;
#if ENABLE(VIDEO)
    MediaPlayer::getSupportedTypes(supportedMediaMIMETypes);
#endif
    return !mimeType.isEmpty() && supportedMediaMIMETypes.contains(mimeType);
}

bool MIMETypeRegistry::isJavaAppletMIMEType(const String& mimeType)
{
    // Since this set is very limited and is likely to remain so we won't bother with the overhead
    // of using a hash set.
    // Any of the MIME types below may be followed by any number of specific versions of the JVM,
    // which is why we use startsWith()
    return mimeType.startsWith("application/x-java-applet", false)
        || mimeType.startsWith("application/x-java-bean", false)
        || mimeType.startsWith("application/x-java-vm", false);
}

String MIMETypeRegistry::getMediaMIMETypeForExtension(const String&)
{
    return String();
}

bool MIMETypeRegistry::isApplicationPluginMIMEType(const String&)
{
    return false;
}

static HashSet<String>& dummyHashSet()
{
    ASSERT_NOT_REACHED();
    static HashSet<String> dummy;
    return dummy;
}

// NOTE: the following methods should never be reached
HashSet<String>& MIMETypeRegistry::getSupportedImageMIMETypes() { return dummyHashSet(); }
HashSet<String>& MIMETypeRegistry::getSupportedImageResourceMIMETypes() { return dummyHashSet(); }
HashSet<String>& MIMETypeRegistry::getSupportedImageMIMETypesForEncoding() { return dummyHashSet(); }
HashSet<String>& MIMETypeRegistry::getSupportedNonImageMIMETypes() { return dummyHashSet(); }
HashSet<String>& MIMETypeRegistry::getSupportedMediaMIMETypes() { return dummyHashSet(); }

} // namespace WebCore