text:
package be.warp9.json;

import be.warp9.json.util.Maps;
import org.junit.Test;

public class MapsTest {

    @Test(expected = IllegalArgumentException.class)
    public void testMap() {
        Maps.map("foo");
    }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>add user</title>

add user

    <form action="__URL__/addUser" method="post" enctype="multipart/form-data">
        昵称:
        <input type="text" placeholder="please type your nickname" name="nickname">
        头像:
        <input type="file" name="face">
        微信号
        <input type="text" name="wechatiId" placeholder="用于打赏">
        用户名:
        <input type="text" placeholder="登陆帐户" name="username">
        密  码:
        <input type="password" placeholder="登陆密码" name="password">
        <input type="submit" value="submit">
    </form>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Security;
using AutoMapper;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Security;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using umbraco.businesslogic.Exceptions;
using Umbraco.Core.Models.Identity;
using Umbraco.Web.Models.ContentEditing;
using GlobalSettings = Umbraco.Core.Configuration.GlobalSettings;
using User = umbraco.BusinessLogic.User;

namespace Umbraco.Web.Security
{
    /// <summary>
    /// A utility class used for dealing with USER security in Umbraco
    /// </summary>
    public class WebSecurity : DisposableObject
    {
        private HttpContextBase _httpContext;
        private ApplicationContext _applicationContext;

        public WebSecurity(HttpContextBase httpContext, ApplicationContext applicationContext)
        {
            _httpContext = httpContext;
            _applicationContext = applicationContext;
        }

        /// <summary>
        /// Returns true or false if the currently logged in member is authorized based on the parameters provided
        /// </summary>
        /// <param name="allowAll"></param>
        /// <param name="allowTypes"></param>
        /// <param name="allowGroups"></param>
        /// <param name="allowMembers"></param>
        /// <returns></returns>
        [Obsolete("Use MembershipHelper.IsMemberAuthorized instead")]
        public bool IsMemberAuthorized(
            bool allowAll = false,
            IEnumerable<string> allowTypes = null,
            IEnumerable<string> allowGroups = null,
            IEnumerable<int> allowMembers = null)
        {
            if (HttpContext.Current == null || ApplicationContext.Current == null)
            {
                return false;
            }
            var helper = new MembershipHelper(ApplicationContext.Current, new HttpContextWrapper(HttpContext.Current));
            return helper.IsMemberAuthorized(allowAll, allowTypes, allowGroups, allowMembers);
        }

        private IUser _currentUser;

        /// <summary>
        /// Gets the current user.
        /// </summary>
        /// <value>The current user.</value>
        public virtual IUser CurrentUser
        {
            get
            {
                //only load it once per instance!
                if (_currentUser == null)
                {
                    var id = GetUserId();
                    if (id == -1)
                    {
                        return null;
                    }
                    _currentUser = _applicationContext.Services.UserService.GetUserById(id);
                }

                return _currentUser;
            }
        }

        private BackOfficeSignInManager _signInManager;
        private BackOfficeSignInManager SignInManager
        {
            get
            {
                if (_signInManager == null)
                {
                    var mgr = _httpContext.GetOwinContext().Get<BackOfficeSignInManager>();
                    if (mgr == null)
                    {
                        throw new NullReferenceException("Could not resolve an instance of " + typeof(BackOfficeSignInManager) + " from the " + typeof(IOwinContext));
                    }
                    _signInManager = mgr;
                }
                return _signInManager;
            }
        }

        private BackOfficeUserManager<BackOfficeIdentityUser> _userManager;
        protected BackOfficeUserManager<BackOfficeIdentityUser> UserManager
        {
            get { return _userManager ?? (_userManager = _httpContext.GetOwinContext().GetBackOfficeUserManager()); }
        }

        /// <summary>
        /// Logs a user in.
        /// </summary>
        /// <param name="userId">The user Id</param>
        /// <returns>returns the number of seconds until their session times out</returns>
        public virtual double PerformLogin(int userId)
        {
            var owinCtx = _httpContext.GetOwinContext();
            //ensure it's done for owin too
            owinCtx.Authentication.SignOut(Constants.Security.BackOfficeExternalAuthenticationType);

            var user = UserManager.FindByIdAsync(userId).Result;
            var userData = Mapper.Map<UserData>(user);
            _httpContext.SetPrincipalForRequest(userData);

            SignInManager.SignInAsync(user, isPersistent: true, rememberBrowser: false).Wait();
            return TimeSpan.FromMinutes(GlobalSettings.TimeOutInMinutes).TotalSeconds;
        }

        [Obsolete("This method should not be used, login is performed by the OWIN pipeline, use the overload that returns double and accepts a UserId instead")]
        public virtual FormsAuthenticationTicket PerformLogin(IUser user)
        {
            //clear the external cookie - we do this first without owin context because we're writing cookies directly to httpcontext
            // and cookie handling is different with httpcontext vs webapi and owin, normally we'd just do:
            //_httpContext.GetOwinContext().Authentication.SignOut(Constants.Security.BackOfficeExternalAuthenticationType);

            var externalLoginCookie = _httpContext.Request.Cookies.Get(Constants.Security.BackOfficeExternalCookieName);
            if (externalLoginCookie != null)
            {
                externalLoginCookie.Expires = DateTime.Now.AddYears(-1);
                _httpContext.Response.Cookies.Set(externalLoginCookie);
            }

            //ensure it's done for owin too
            _httpContext.GetOwinContext().Authentication.SignOut(Constants.Security.BackOfficeExternalAuthenticationType);

            var ticket = _httpContext.CreateUmbracoAuthTicket(Mapper.Map<UserData>(user));
            return ticket;
        }

        /// <summary>
        /// Clears the current login for the currently logged in user
        /// </summary>
        public virtual void ClearCurrentLogin()
        {
            _httpContext.UmbracoLogout();
            _httpContext.GetOwinContext().Authentication.SignOut(
                Core.Constants.Security.BackOfficeAuthenticationType,
                Core.Constants.Security.BackOfficeExternalAuthenticationType);
        }

        /// <summary>
        /// Renews the user's login ticket
        /// </summary>
        public virtual void RenewLoginTimeout()
        {
            _httpContext.RenewUmbracoAuthTicket();
        }

        /// <summary>
        /// Validates credentials for a back office user
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public virtual bool ValidateBackOfficeCredentials(string username, string password)
        {
            var membershipProvider = Core.Security.MembershipProviderExtensions.GetUsersMembershipProvider();
            return membershipProvider != null && membershipProvider.ValidateUser(username, password);
        }

        /// <summary>
        /// Returns the MembershipUser from the back office membership provider
        /// </summary>
        /// <param name="username"></param>
        /// <param name="setOnline"></param>
        /// <returns></returns>
        public virtual MembershipUser GetBackOfficeMembershipUser(string username, bool setOnline)
        {
            var membershipProvider = Core.Security.MembershipProviderExtensions.GetUsersMembershipProvider();
            return membershipProvider != null ? membershipProvider.GetUser(username, setOnline) : null;
        }

        /// <summary>
        /// Returns the back office IUser instance for the username specified
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        /// <remarks>
        /// This will return an Iuser instance no matter what membership provider is installed for the back office, it will automatically
        /// create any missing Iuser accounts if one is not found and a custom membership provider is being used.
        /// </remarks>
        internal IUser GetBackOfficeUser(string username)
        {
            //get the membership user (set user to be 'online' in the provider too)
            var membershipUser = GetBackOfficeMembershipUser(username, true);
            var provider = Core.Security.MembershipProviderExtensions.GetUsersMembershipProvider();

            if (membershipUser == null)
            {
                throw new InvalidOperationException(
                    "The username & password validated but the membership provider '" +
                    provider.Name +
                    "' did not return a MembershipUser with the username supplied");
            }

            //regarldess of the membership provider used, see if this user object already exists in the umbraco data
            var user = _applicationContext.Services.UserService.GetByUsername(membershipUser.UserName);

            //we're using the built-in membership provider so the user will already be available
            if (provider.IsUmbracoUsersProvider())
            {
                if (user == null)
                {
                    //this should never happen
                    throw new InvalidOperationException("The user '" + username + "' could not be found in the Umbraco database");
                }
                return user;
            }

            //we are using a custom membership provider for the back office, in this case we need to create user accounts for the logged in member.
            //if we already have a user object in Umbraco we don't need to do anything, otherwise we need to create a mapped Umbraco account.
            if (user != null) return user;

            //we need to create an Umbraco IUser of a 'writer' type with access to only content - this was how v6 operates.
            var writer = _applicationContext.Services.UserService.GetUserTypeByAlias("writer");

            var email = membershipUser.Email;
            if (email.IsNullOrWhiteSpace())
            {
                //in some cases if there is no email we have to generate one since it is required!
                email = Guid.NewGuid().ToString("N") + "@example.com";
            }

            user = new Core.Models.Membership.User(writer)
            {
                Email = email,
                Language = GlobalSettings.DefaultUILanguage,
                Name = membershipUser.UserName,
                RawPasswordValue = Guid.NewGuid().ToString("N"), //Need to set this to something - will not be used though
                Username = membershipUser.UserName,
                StartContentId = -1,
                StartMediaId = -1,
                IsLockedOut = false,
                IsApproved = true
            };
            user.AddAllowedSection("content");

            _applicationContext.Services.UserService.Save(user);

            return user;
        }

        /// <summary>
        /// Validates the user node tree permissions.
        /// </summary>
        /// <param name="umbracoUser"></param>
        /// <param name="path">The path.</param>
        /// <param name="action">The action.</param>
        /// <returns></returns>
        internal bool ValidateUserNodeTreePermissions(User umbracoUser, string path, string action)
        {
            var permissions = umbracoUser.GetPermissions(path);
            if (permissions.IndexOf(action, StringComparison.Ordinal) > -1 && (path.Contains("-20") || ("," + path + ",").Contains("," + umbracoUser.StartNodeId + ",")))
                return true;

            var user = umbracoUser;
            LogHelper.Info<WebSecurity>("User {0} has insufficient permissions in UmbracoEnsuredPage: '{1}', '{2}', '{3}'", () => user.Name, () => path, () => permissions, () => action);
            return false;
        }

        /// <summary>
        /// Validates the current user to see if they have access to the specified app
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        internal bool ValidateUserApp(string app)
        {
            //if it is empty, don't validate
            if (app.IsNullOrWhiteSpace())
            {
                return true;
            }
            return CurrentUser.AllowedSections.Any(uApp => uApp.InvariantEquals(app));
        }

        /// <summary>
        /// Gets the user id.
        /// </summary>
        /// <param name="umbracoUserContextId">This is not used</param>
        /// <returns></returns>
        [Obsolete("This method is no longer used, use the GetUserId() method without parameters instead")]
        public int GetUserId(string umbracoUserContextId)
        {
            return GetUserId();
        }

        /// <summary>
        /// Gets the currnet user's id.
        /// </summary>
        /// <returns></returns>
        public virtual int GetUserId()
        {
            var identity = _httpContext.GetCurrentIdentity(false);
            if (identity == null)
                return -1;
            return Convert.ToInt32(identity.Id);
        }

        /// <summary>
        /// Returns the current user's unique session id - used to mitigate csrf attacks or any other reason to validate a request
        /// </summary>
        /// <returns></returns>
        public virtual string GetSessionId()
        {
            var identity = _httpContext.GetCurrentIdentity(false);
            if (identity == null)
                return null;
            return identity.SessionId;
        }

        /// <summary>
        /// Validates the user context ID.
        /// </summary>
        /// <param name="currentUmbracoUserContextId">This doesn't do anything</param>
        /// <returns></returns>
        [Obsolete("This method is no longer used, use the ValidateCurrentUser() method instead")]
        public bool ValidateUserContextId(string currentUmbracoUserContextId)
        {
            return ValidateCurrentUser();
        }

        /// <summary>
        /// Validates the currently logged in user and ensures they are not timed out
        /// </summary>
        /// <returns></returns>
        public virtual bool ValidateCurrentUser()
        {
            var result = ValidateCurrentUser(false);
            return result == ValidateRequestAttempt.Success;
        }

        /// <summary>
        /// Validates the current user assigned to the request and ensures the stored user data is valid
        /// </summary>
        /// <param name="throwExceptions">set to true if you want exceptions to be thrown if failed</param>
        /// <returns></returns>
        internal ValidateRequestAttempt ValidateCurrentUser(bool throwExceptions)
        {
            //This will first check if the current user is already authenticated - which should be the case in nearly all circumstances
            // since the authentication happens in the Module, that authentication also checks the ticket expiry. We don't
            // need to check it a second time because that requires another decryption phase and nothing can tamper with it during the request.

            if (IsAuthenticated() == false)
            {
                //There is no user
                if (throwExceptions) throw new InvalidOperationException("The user has no umbraco contextid - try logging in");
                return ValidateRequestAttempt.FailedNoContextId;
            }

            var user = CurrentUser;

            // Check for console access
            if (user == null || user.IsApproved == false || (user.IsLockedOut && GlobalSettings.RequestIsInUmbracoApplication(_httpContext)))
            {
                if (throwExceptions) throw new ArgumentException("You have no priviledges to the umbraco console. Please contact your administrator");
                return ValidateRequestAttempt.FailedNoPrivileges;
            }
            return ValidateRequestAttempt.Success;

        }

        /// <summary>
        /// Authorizes the full request, checks for SSL and validates the current user
        /// </summary>
        /// <param name="throwExceptions">set to true if you want exceptions to be thrown if failed</param>
        /// <returns></returns>
        internal ValidateRequestAttempt AuthorizeRequest(bool throwExceptions = false)
        {
            // check for secure connection
            if (GlobalSettings.UseSSL && _httpContext.Request.IsSecureConnection == false)
            {
                if (throwExceptions) throw new UserAuthorizationException("This installation requires a secure connection (via SSL). Please update the URL to include https://");
                return ValidateRequestAttempt.FailedNoSsl;
            }
            return ValidateCurrentUser(throwExceptions);
        }

        /// <summary>
        /// Checks if the specified user as access to the app
        /// </summary>
        /// <param name="app"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        internal bool UserHasAppAccess(string app, IUser user)
        {
            var apps = user.AllowedSections;
            return apps.Any(uApp => uApp.InvariantEquals(app));
        }

        [Obsolete("Do not use this method if you don't have to, use the overload with IUser instead")]
        internal bool UserHasAppAccess(string app, User user)
        {
            return user.Applications.Any(uApp => uApp.alias == app);
        }

        /// <summary>
        /// Checks if the specified user by username as access to the app
        /// </summary>
        /// <param name="app"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        internal bool UserHasAppAccess(string app, string username)
        {
            var user = _applicationContext.Services.UserService.GetByUsername(username);
            if (user == null)
            {
                return false;
            }
            return UserHasAppAccess(app, user);
        }

        [Obsolete("Returns the current user's unique umbraco sesion id - this cannot be set and isn't intended to be used in your code")]
        public string UmbracoUserContextId
        {
            get
            {
                return _httpContext.GetUmbracoAuthTicket() == null ? "" : GetSessionId();
            }
            set
            {
            }
        }

        /// <summary>
        /// Ensures that a back office user is logged in
        /// </summary>
        /// <returns></returns>
        public bool IsAuthenticated()
        {
            return _httpContext.User.Identity.IsAuthenticated && _httpContext.GetCurrentIdentity(false) != null;
        }

        protected override void DisposeResources()
        {
            _httpContext = null;
        }

    }
}


text:
package net.onrc.onos.api.rest;

import com.codahale.metrics.Meter;
import net.onrc.onos.core.metrics.OnosMetrics;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.restlet.resource.ClientResource;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;

/**
 * Unit tests for REST APIs for Meter Metrics.
 */
public class TestRestMetricsMeters extends TestRestMetrics {

    //  Test data for Meters

    private static final OnosMetrics.MetricsComponent COMPONENT =
            OnosMetrics.registerComponent("MetricsUnitTest");
    private static final OnosMetrics.MetricsFeature FEATURE =
            COMPONENT.registerFeature("Meters");

    private static final String METER1_NAME = "METER1";
    private static final String METER1_FULL_NAME =
            OnosMetrics.generateName(COMPONENT, FEATURE, METER1_NAME);
    private static final int METER1_ITERATIONS = 1;

    private static final String METER2_NAME = "METER2";
    private static final String METER2_FULL_NAME =
            OnosMetrics.generateName(COMPONENT, FEATURE, METER2_NAME);
    private static final int METER2_ITERATIONS = 10;

    private static final String METER3_NAME = "METER3";
    private static final String METER3_FULL_NAME =
            OnosMetrics.generateName(COMPONENT, FEATURE, METER3_NAME);
    private static final int METER3_ITERATIONS = 100;

    private final Meter meter1 = new Meter(getMockClock());
    private final Meter meter2 = new Meter(getMockClock());
    private final Meter meter3 = new Meter(getMockClock());

    /**
     * Fill in test data for a given Meter.
     *
     * @param meter Meter object to fill in
     * @param iterations How many times to mark the meter
     */
    private void fillMeter(final Meter meter,
                           final long iterations) {
        for (int i = 0; i < iterations; i++) {
            meter.mark();
        }
    }

    /**
     * Fill in test data in the test Meters.
     */
    private void fillMeters() {
        fillMeter(meter1, METER1_ITERATIONS);
        fillMeter(meter2, METER2_ITERATIONS);
        fillMeter(meter3, METER3_ITERATIONS);

        OnosMetrics.registerMetric(COMPONENT,
                                   FEATURE,
                                   METER1_NAME,
                                   meter1);

        OnosMetrics.registerMetric(COMPONENT,
                                   FEATURE,
                                   METER2_NAME,
                                   meter2);

        OnosMetrics.registerMetric(COMPONENT,
                                   FEATURE,
                                   METER3_NAME,
                                   meter3);
    }

    /**
     * Check if the data in a Meter matches the expected values.
     *
     * @param meter the meter object that this JSON representation should match
     * @param meterContainer JSON object for the Meter
     * @param name name of the Meter
     * @param iterations count of marks that should be in the Meter
     * @throws JSONException if any of the JSON processing fails
     */
    private void checkMeter(final Meter meter,
                            final JSONObject meterContainer,
                            final String name,
                            final int iterations)
                 throws JSONException {
        final String meterName = meterContainer.getString("name");
        assertThat(meterName, is(notNullValue()));
        assertThat(meterName, is(equalTo(name)));

        final JSONObject meterObject = meterContainer.getJSONObject("meter");
        assertThat(meterObject, is(notNullValue()));

        final int meterCount = meterObject.getInt("count");
        assertThat(meterCount, is(equalTo(iterations)));

        final double m15Rate = meterObject.getDouble("m15_rate");
        assertThat(m15Rate, is(equalTo(meter.getFifteenMinuteRate())));

        final double m5Rate = meterObject.getDouble("m5_rate");
        assertThat(m5Rate, is(equalTo(meter.getFiveMinuteRate())));

        final double m1Rate = meterObject.getDouble("m1_rate");
        assertThat(m1Rate, is(equalTo(meter.getOneMinuteRate())));

        // mean should be between 0.0 and the longest rate.  Since all the rates
        // are the same because of the mocked clock, use the 15 minute rate as
        // the max - all the rates should be the same.
        final double meanRate = meterObject.getDouble("mean_rate");
        assertThat(meanRate,
                is(both(greaterThanOrEqualTo(0.0)).
                        and(lessThanOrEqualTo(m15Rate))));

        final String units = meterObject.getString("units");
        assertThat(units, is(equalTo("events/second")));
    }

    /**
     * UNIT test for the Metrics REST API for Meters.
     *
     * @throws JSONException if any JSON processing fails
     */
    @Test
    public void testMeters() throws JSONException {

        fillMeters();

        //  Read the metrics from the REST API for the test data
        final ClientResource client = new ClientResource(getBaseRestMetricsUrl());

        final JSONObject metrics = getJSONObject(client);
        assertThat(metrics.length(), is(equalTo(5)));

        //  There should be 3 meters
        final JSONArray meters = metrics.getJSONArray("meters");
        assertThat(meters, is(notNullValue()));
        assertThat(meters.length(), is(3));

        //  There should be no timers, gauges, histograms or counters
        checkEmptyLists(metrics, "timers", "gauges", "histograms", "counters");

        //  Check the values for meter 1
        final JSONObject meter1Container = meters.getJSONObject(0);
        checkMeter(meter1, meter1Container, METER1_FULL_NAME, METER1_ITERATIONS);

        //  Check the values for meter 2
        final JSONObject meter2Container = meters.getJSONObject(1);
        checkMeter(meter2, meter2Container, METER2_FULL_NAME, METER2_ITERATIONS);

        //  Check the values for meter 3
        final JSONObject meter3Container = meters.getJSONObject(2);
        checkMeter(meter3, meter3Container, METER3_FULL_NAME, METER3_ITERATIONS);

    }

}


text:
"""A QR Get SCU application.

For sending Query/Retrieve (QR) C-GET requests to a QR Get SCP.
"""

import argparse
import os
import sys

from pydicom.dataset import Dataset
from pydicom.uid import (
    ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian
)

from pynetdicom import (
    AE, build_role, evt,
    StoragePresentationContexts,
    QueryRetrievePresentationContexts,
)
from pynetdicom.apps.common import setup_logging, create_dataset, handle_store
from pynetdicom._globals import DEFAULT_MAX_LENGTH
from pynetdicom.pdu_primitives import SOPClassExtendedNegotiation
from pynetdicom.sop_class import (
    PatientRootQueryRetrieveInformationModelGet,
    StudyRootQueryRetrieveInformationModelGet,
    PatientStudyOnlyQueryRetrieveInformationModelGet,
    PlannedImagingAgentAdministrationSRStorage,
    PerformedImagingAgestAdministrationSRStorage,
    EncapsulatedSTLStorage,
)

__version__ = '0.4.0'

def _setup_argparser():
    """Setup the command line arguments"""
    # Description
    parser = argparse.ArgumentParser(
        description=(
            "The getscu application implements a Service Class User "
            "(SCU) for the Query/Retrieve (QR) Service Class. getscu only "
            "supports query functionality using the C-GET message. It sends "
            "query keys to an SCP and waits for a response. The application "
            "can be used to test SCPs of the QR Service Class."
        ),
        usage="getscu [options] addr port"
    )

    # Parameters
    req_opts = parser.add_argument_group('Parameters')
    req_opts.add_argument(
        "addr", help="TCP/IP address or hostname of DICOM peer", type=str
    )
    req_opts.add_argument("port", help="TCP/IP port number of peer", type=int)

    # General Options
    gen_opts = parser.add_argument_group('General Options')
    gen_opts.add_argument(
        "--version",
        help="print version information and exit",
        action="store_true"
    )
    output = gen_opts.add_mutually_exclusive_group()
    output.add_argument(
        "-q", "--quiet",
        help="quiet mode, print no warnings and errors",
        action="store_const",
        dest='log_type', const='q'
    )
    output.add_argument(
        "-v", "--verbose",
        help="verbose mode, print processing details",
        action="store_const",
        dest='log_type', const='v'
    )
    output.add_argument(
        "-d", "--debug",
        help="debug mode, print debug information",
        action="store_const",
        dest='log_type', const='d'
    )
    gen_opts.add_argument(
        "-ll", "--log-level", metavar='[l]',
        help=(
            "use level l for the logger (critical, error, warn, info, debug)"
        ),
        type=str,
        choices=['critical', 'error', 'warn', 'info', 'debug']
    )
    parser.set_defaults(log_type='v')

    # Network Options
    net_opts = parser.add_argument_group('Network Options')
    net_opts.add_argument(
        "-aet", "--calling-aet", metavar='[a]etitle',
        help="set my calling AE title (default: GETSCU)",
        type=str,
        default='GETSCU'
    )
    net_opts.add_argument(
        "-aec", "--called-aet", metavar='[a]etitle',
        help="set called AE title of peer (default: ANY-SCP)",
        type=str,
        default='ANY-SCP'
    )
    net_opts.add_argument(
        "-ta", "--acse-timeout", metavar='[s]econds',
        help="timeout for ACSE messages (default: 30 s)",
        type=float,
        default=30
    )
    net_opts.add_argument(
        "-td", "--dimse-timeout", metavar='[s]econds',
        help="timeout for DIMSE messages (default: 30 s)",
        type=float,
        default=30
    )
    net_opts.add_argument(
        "-tn", "--network-timeout", metavar='[s]econds',
        help="timeout for the network (default: 30 s)",
        type=float,
        default=30
    )
    net_opts.add_argument(
        "-pdu", "--max-pdu", metavar='[n]umber of bytes',
        help=(
            f"set max receive pdu to n bytes (0 for unlimited, "
            f"default: {DEFAULT_MAX_LENGTH})"
        ),
        type=int,
        default=DEFAULT_MAX_LENGTH
    )

    # Query information model choices
    qr_group = parser.add_argument_group('Query Information Model Options')
    qr_model = qr_group.add_mutually_exclusive_group()
    qr_model.add_argument(
        "-P", "--patient",
        help="use patient root information model (default)",
        action="store_true"
    )
    qr_model.add_argument(
        "-S", "--study",
        help="use study root information model",
        action="store_true"
    )
    qr_model.add_argument(
        "-O", "--psonly",
        help="use patient/study only information model",
        action="store_true"
    )

    # Query Options
    qr_query = parser.add_argument_group('Query Options')
    qr_query.add_argument(
        '-k', '--keyword',
        metavar='[k]eyword: (gggg,eeee)=str, keyword=str',
        help=(
            "add or override a query element using either an element tag as "
            "(group,element) or the element's keyword (such as PatientName)"
        ),
        type=str,
        action='append',
    )
    qr_query.add_argument(
        '-f', '--file',
        metavar='path to [f]ile',
        help=(
            "use a DICOM file as the query dataset, if "
            "used with -k then the elements will be added to or overwrite "
            "those present in the file"
        ),
        type=str,
    )

    # Extended Negotiation Options
    ext_neg = parser.add_argument_group('Extended Negotiation Options')
    ext_neg.add_argument(
        '--relational-retrieval',
        help="request the use of relational retrieval",
        action="store_true",
    )
    ext_neg.add_argument(
        '--enhanced-conversion',
        help="request the use of enhanced multi-frame image conversion",
        action="store_true",
    )

    # Output Options
    out_opts = parser.add_argument_group('Output Options')
    out_opts.add_argument(
        '-od', "--output-directory", metavar="[d]irectory",
        help="write received objects to directory d",
        type=str
    )
    out_opts.add_argument(
        '--ignore',
        help="receive data but don't store it",
        action="store_true"
    )

    ns = parser.parse_args()
    if ns.version:
        pass
    elif not bool(ns.file) and not bool(ns.keyword):
        parser.error('-f and/or -k must be specified')

    return ns

def main(args=None):
    """Run the application."""
    if args is not None:
        sys.argv = args

    args = _setup_argparser()

    if args.version:
        print(f'getscu.py v{__version__}')
        sys.exit()

    APP_LOGGER = setup_logging(args, 'getscu')
    APP_LOGGER.debug(f'getscu.py v{__version__}')
    APP_LOGGER.debug('')

    # Create query (identifier) dataset
    try:
        # If you're looking at this to see how QR Get works then `identifer`
        # is a pydicom Dataset instance with your query keys, e.g.:
        #     identifier = Dataset()
        #     identifier.QueryRetrieveLevel = 'PATIENT'
        #     identifier.PatientName = '*'
        identifier = create_dataset(args, APP_LOGGER)
    except Exception as exc:
        APP_LOGGER.exception(exc)
        sys.exit(1)

    # Exclude these SOP Classes
    _exclusion = [
        PlannedImagingAgentAdministrationSRStorage,
        PerformedImagingAgestAdministrationSRStorage,
        EncapsulatedSTLStorage,
    ]
    store_contexts = [
        cx for cx in StoragePresentationContexts
        if cx.abstract_syntax not in _exclusion
    ]

    # Create application entity
    # Binding to port 0 lets the OS pick an available port
    ae = AE(ae_title=args.calling_aet)
    ae.acse_timeout = args.acse_timeout
    ae.dimse_timeout = args.dimse_timeout
    ae.network_timeout = args.network_timeout

    # Extended Negotiation - SCP/SCU Role Selection
    ext_neg = []
    ae.add_requested_context(PatientRootQueryRetrieveInformationModelGet)
    ae.add_requested_context(StudyRootQueryRetrieveInformationModelGet)
    ae.add_requested_context(PatientStudyOnlyQueryRetrieveInformationModelGet)
    for cx in store_contexts:
        ae.add_requested_context(cx.abstract_syntax)
        # Add SCP/SCU Role Selection Negotiation to the extended negotiation
        # We want to act as a Storage SCP
        ext_neg.append(build_role(cx.abstract_syntax, scp_role=True))

    if args.study:
        query_model = StudyRootQueryRetrieveInformationModelGet
    elif args.psonly:
        query_model = PatientStudyOnlyQueryRetrieveInformationModelGet
    else:
        query_model = PatientRootQueryRetrieveInformationModelGet

    # Extended Negotiation - SOP Class Extended
    ext_opts = [args.relational_retrieval, args.enhanced_conversion]
    if any(ext_opts):
        app_info = b''
        for option in ext_opts:
            app_info += b'\x01' if option else b'\x00'

        item = SOPClassExtendedNegotiation()
        item.sop_class_uid = query_model
        item.service_class_application_information = app_info
        ext_neg.append(item)

    # Request association with remote
    assoc = ae.associate(
        args.addr,
        args.port,
        ae_title=args.called_aet,
        ext_neg=ext_neg,
        evt_handlers=[(evt.EVT_C_STORE, handle_store, [args, APP_LOGGER])],
        max_pdu=args.max_pdu
    )

    if assoc.is_established:
        # Send query
        responses = assoc.send_c_get(identifier, query_model)
        for (status, rsp_identifier) in responses:
            # If `status.Status` is one of the 'Pending' statuses then
            #   `rsp_identifier` is the C-GET response's Identifier dataset
            if status and status.Status in [0xFF00, 0xFF01]:
                # `rsp_identifier` is a pydicom Dataset containing a query
                # response. You may want to do something interesting here...
                pass

        assoc.release()
    else:
        sys.exit(1)

if __name__ == "__main__":
    main()


text:
package com.wsl.library.widget.demo;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;

import com.wsl.library.widget.DdNineGridAppendAdapter;

import java.util.List;
import java.util.Random;

/**
 * Created by wsl on 17/4/15.
 */

public class DemoAdapter1 extends DdNineGridAppendAdapter<Bean> {

    private LayoutInflater mLayoutInflater;

    public DemoAdapter1(Context context, List<Bean> objects) {
        this(context, objects, 9);
    }

    public DemoAdapter1(Context context, List<Bean> objects, int max) {
        super(objects, max);
        this.mLayoutInflater = LayoutInflater.from(context);
    }

    @Override
    protected View getNormalView(int position) {
        View view = mLayoutInflater.inflate(R.layout.item, null);
        view.setBackgroundColor(getNormalColor());
        return view;
    }

    @Override
    protected View getAddView() {
        View view = mLayoutInflater.inflate(R.layout.item, null);
        view.setBackgroundColor(Color.BLACK);
        return view;
    }

    private int getNormalColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }
}


text:
"""
Created on Mon Jul  2 14:40:44 2018
"""
import os
import random
import sys

import itertools as it
import pandas as pd

def get_uniq_unit_ids(dframe, unit_id_field):
    """Get all unit ids in the output file"""
    unique_unit_ids = dframe[unit_id_field].unique()
    return unique_unit_ids

def get_no_work_unit_id(dframe, unit_id, unit_id_field):
    """Get the worker annotations for a unit"""
    subset_unit_id = dframe[dframe[unit_id_field] == unit_id]
    return (len(subset_unit_id), subset_unit_id)

def count_bits(number, n_bits):
    """ Optimization function for creating all possible combinations"""
    ret = 0
    bit_pos = []
    for i in range(0, n_bits):
        if (1 << i) & number != 0:
            ret += 1
            bit_pos.append(i)
    return (ret, bit_pos)

def gen_all_k_combinations(k, num_size):
    """ Generic function to compute combinations"""
    result = []
    for i in range(1, 2**num_size):
        bit_count, bit_pos = count_bits(i, num_size)
        if bit_count == k:
            result.append(bit_pos)
    return result

def gen_all_worker_combinations(subset_size, count, subset_unit_id, worker_id_field):
    """ Get all worker combinations"""
    combinations = gen_all_k_combinations(subset_size, count)
    final_result = []
    for comb in combinations:
        crnt_workers = []
        for j in range(0, len(comb)):
            crnt_workers.append(subset_unit_id[worker_id_field].iloc[comb[j]])
        final_result.append(crnt_workers)
    return final_result

def get_all_unit_combinations(unit_dict):
    """ Create worker combinations for all units"""
    sorted_unit_dict = sorted(unit_dict)
    combinations = it.product(*(unit_dict[unit_id] for unit_id in sorted_unit_dict))
    print(list(combinations))

def my_product(dicts):
    """Create sets of workers"""
    units, comb_of_workers = zip(*dicts.items())
    return [dict(zip(units, x)) for x in it.product(*comb_of_workers)]

def pick_random_worker_set(worker_sets):
    """Pick random set of workers"""
    return random.choice(worker_sets)

def create_analysis_files(dataset_file, max_no_workers, max_runs, \
                          storing_folder, unit_id_field, worker_id_field):
    """Create files of various number of workers"""
    dataset = pd.read_csv(dataset_file)
    unique_unit_ids = get_uniq_unit_ids(dataset, unit_id_field)

    for subset_size in range(3, max_no_workers + 1):
        workers_directory = storing_folder + str(subset_size) + "workers"
        if not os.path.exists(workers_directory):
            os.makedirs(workers_directory)

        map_unit_id_combinations = {}
        for unit_id in range(0, len(unique_unit_ids)):
            (count, subset_unit_id) = get_no_work_unit_id(dataset, unique_unit_ids[unit_id], \
                                                          unit_id_field)
            combinations = gen_all_worker_combinations(subset_size, count, subset_unit_id, \
                                                       worker_id_field)
            map_unit_id_combinations[unique_unit_ids[unit_id]] = combinations

        for run_no in range(0, max_runs + 1):
            unit_worker_set = {}
            for unit_id, worker_sets in map_unit_id_combinations.items():
                unit_worker_set[unit_id] = pick_random_worker_set(worker_sets)

            df_subset_size = pd.DataFrame()
            for unit_id, worker_set in unit_worker_set.items():
                df_subset = dataset[(dataset[unit_id_field] == unit_id) &
                                    (dataset[worker_id_field].isin(worker_set))]
                frames = [df_subset_size, df_subset]
                df_subset_size = pd.concat(frames)

            df_subset_size.to_csv(workers_directory + "/run_" + str(run_no) + ".csv", index=False)

def main(argv=None):
    """Run the script"""
    if argv is None:
        argv = sys.argv

    if len(argv) < 6:
        print('Usage: python replication_experiment_wrt_workers.py dataset_filename'
              ' max_no_workers max_runs storing_folder unit_id_field, worker_id_field')

    else:
        create_analysis_files(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5])

if __name__ == '__main__':
    main()


text:
package org.jkiss.dbeaver.model.sql;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Platform;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPObject;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.data.*;
import org.jkiss.dbeaver.model.edit.DBEPersistAction;
import org.jkiss.dbeaver.model.exec.DBCSession;
import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect;
import org.jkiss.dbeaver.model.impl.sql.RelationalSQLDialect;
import org.jkiss.dbeaver.model.runtime.DBRFinder;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.dbeaver.model.struct.rdb.DBSTableForeignKey;
import org.jkiss.dbeaver.model.struct.rdb.DBSTableForeignKeyColumn;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import org.jkiss.utils.Pair;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQL Utils
 */
public final class SQLUtils {

    private static final Log log = Log.getLog(SQLUtils.class);

    public static final Pattern PATTERN_OUT_PARAM = Pattern.compile("((\\?)|(:[a-z0-9]+))\\s*:=");
    public static final Pattern PATTERN_SIMPLE_NAME = Pattern.compile("[a-z][a-z0-9_]*", Pattern.CASE_INSENSITIVE);

    private static final Pattern CREATE_PREFIX_PATTERN = Pattern.compile("(CREATE (:OR REPLACE)?).+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static final int MIN_SQL_DESCRIPTION_LENGTH = 512;
    private static final int MAX_SQL_DESCRIPTION_LENGTH = 500;

    private static final String DBEAVER_DDL_COMMENT = "-- DDL generated by ";
    private static final String DBEAVER_DDL_WARNING = "-- WARNING: It may differ from actual native database DDL";
    private static final String DBEAVER_SCRIPT_DELIMITER = "$$";

    public static String stripTransformations(String query)
    {
        return query;
//        if (!query.contains(TOKEN_TRANSFORM_START)) {
//            return query;
//        } else {
//            return PATTERN_XFORM.matcher(query).replaceAll("");
//        }
    }

    public static String stripComments(@NotNull SQLDialect dialect, @NotNull String query)
    {
        Pair<String, String> multiLineComments = dialect.getMultiLineComments();
        return stripComments(
            query,
            multiLineComments == null ? null : multiLineComments.getFirst(),
            multiLineComments == null ? null : multiLineComments.getSecond(),
            dialect.getSingleLineComments());
    }

    public static boolean isCommentLine(SQLDialect dialect, String line) {
        for (String slc : dialect.getSingleLineComments()) {
            if (line.startsWith(slc)) {
                return true;
            }
        }
        return false;
    }

    public static String stripComments(@NotNull String query, @Nullable String mlCommentStart, @Nullable String mlCommentEnd, String[] slComments)
    {
        String leading = "", trailing = "";
        {
            int startPos, endPos;
            for (startPos = 0; startPos < query.length(); startPos++) {
                if (!Character.isWhitespace(query.charAt(startPos))) {
                    break;
                }
            }
            for (endPos = query.length() - 1; endPos > startPos; endPos--) {
                if (!Character.isWhitespace(query.charAt(endPos))) {
                    break;
                }
            }
            if (startPos > 0) {
                leading = query.substring(0, startPos);
            }
            if (endPos < query.length() - 1) {
                trailing = query.substring(endPos + 1);
            }
        }
        query = query.trim();
        if (mlCommentStart != null && mlCommentEnd != null && query.startsWith(mlCommentStart)) {
            int endPos = query.indexOf(mlCommentEnd);
            if (endPos != -1) {
                query = query.substring(endPos + mlCommentEnd.length());
            }
        }
        for (int i = 0; i < slComments.length; i++) {
            while (query.startsWith(slComments[i])) {
                int crPos = query.indexOf('\n');
                if (crPos == -1) {
                    // Query is comment line - return empty
                    query = "";
                    break;
                } else {
                    query = query.substring(crPos).trim();
                }
            }
        }
        return leading + query + trailing;
    }

    public static List<String> splitFilter(String filter)
    {
        if (CommonUtils.isEmpty(filter)) {
            return Collections.emptyList();
        }
        return CommonUtils.splitString(filter, ',');
    }

    public static boolean matchesAnyLike(String string, Collection<String> likes)
    {
        for (String like : likes) {
            if (matchesLike(string, like)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isLikePattern(String like)
    {
        return like.indexOf('%') != -1 || like.indexOf('*') != -1 || like.indexOf('_') != -1 || like.indexOf('?') != -1;// || like.indexOf('_') != -1;
    }

    @NotNull
    public static String makeLikePattern(@NotNull String like) {
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < like.length(); i++) {
            char c = like.charAt(i);
            if (c == '*') result.append(".*");
            else if (c == '?' || c == '_') result.append(".");
            else if (c == '%') result.append(".*");
            else if (Character.isLetterOrDigit(c)) result.append(c);
            else if (c == '(' || c == ')' || c == '[' || c == ']') result.append('\\').append(c);
            else if (c == '\\') {
                if (i < like.length() - 1) {
                    char nc = like.charAt(i + 1);
                    if (nc == '_' || nc == '*' || nc == '?' || nc == '.' || nc == '%') {
                        result.append("\\").append(nc);
                        i++;
                    } else {
                        result.append("\\");
                    }
                }
            }
            else {
                result.append(c);
            }
        }
        return result.toString();
    }

    @NotNull
    public static String makeRegexFromLike(@NotNull String clause) {
        final StringBuilder sb = new StringBuilder();
        for (int index = 0, length = clause.length(); index < length; index++) {
            final char ch = clause.charAt(index);
            if (ch == '%') {
                if (index > 0 && index < length - 1) {
                    sb.append(".*");
                }
            } else {
                if (index == 0) {
                    sb.append('^');
                }
                sb.append(ch == '_' ? '.' : ch);
                if (index == length - 1) {
                    sb.append('$');
                }
            }
        }
        return sb.toString();
    }

    public static String makeSQLLike(String like)
    {
        return like.replace("*", "%").replace("?", "_");
    }

    public static boolean matchesLike(String string, String like)
    {
        Pattern pattern = Pattern.compile(makeLikePattern(like), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
        return pattern.matcher(string).matches();
    }

    public static void appendValue(StringBuilder buffer, DBSTypedObject type, Object value)
    {
        if (type.getDataKind() == DBPDataKind.NUMERIC || type.getDataKind() == DBPDataKind.BOOLEAN) {
            buffer.append(value);
        } else {
            buffer.append('\'').append(value).append('\'');
        }
    }

    public static boolean isStringQuoted(DBSObject object, String string) {
        return object.getDataSource().getSQLDialect().isQuotedString(string);
    }

    public static String quoteString(DBSObject object, String string)
    {
        return quoteString(object.getDataSource(), string);
    }

    public static String quoteString(DBPDataSource dataSource, String string)
    {
        return dataSource.getSQLDialect().getQuotedString(string);
    }

    public static String escapeString(DBPDataSource dataSource, String string)
    {
        return dataSource.getSQLDialect().escapeString(string);
    }

    public static String unQuoteString(DBPDataSource dataSource, String string)
    {
        if (string.length() > 1 && string.charAt(0) == '\'' && string.charAt(string.length() - 1) == '\'') {
            return dataSource.getSQLDialect().unEscapeString(string.substring(1, string.length() - 1));
        }
        return string;
    }

    public static String getFirstKeyword(SQLDialect dialect, String query)
    {
        query = stripComments(dialect, query);
        int startPos = 0, endPos = -1;
        for (int i = 0; i < query.length(); i++) {
            if (Character.isLetterOrDigit(query.charAt(i))) {
                startPos = i;
                break;
            }
        }
        for (int i = startPos; i < query.length(); i++) {
            if (Character.isWhitespace(query.charAt(i))) {
                endPos = i;
                break;
            }
        }
        if (endPos == -1) {
            return query;
        }
        return query.substring(startPos, endPos);
    }

    @Nullable
    public static String getQueryOutputParameter(DBCSession session, String query)
    {
        final Matcher matcher = PATTERN_OUT_PARAM.matcher(query);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    /**
     * Removes \\r characters from query.
     * Actually this is done specially for Oracle due to some bug in it's driver
     *
     * @param dataSource
     * @param query query
     * @return normalized query
     */
    public static String makeUnifiedLineFeeds(DBPDataSource dataSource, String query)
    {
        SQLDialect dialect = SQLUtils.getDialectFromDataSource(dataSource);
        if (!dialect.isCRLFBroken()) {
            return query;
        }
        if (query.indexOf('\r') == -1) {
            return query;
        }
        StringBuilder result = new StringBuilder(query.length());
        for (int i = 0; i < query.length(); i++) {
            char c = query.charAt(i);
            if (c == '\r') {
                continue;
            }
            result.append(c);
        }
        return result.toString();
    }

    public static void appendLikeCondition(@NotNull StringBuilder sql,@NotNull String value, boolean not,@Nullable SQLDialect dialect) {
        value = makeSQLLike(value);
        if (value.contains("%") || value.contains("_")) {
            if (not) sql.append(" NOT");
            sql.append(" LIKE ?");
            if (dialect instanceof RelationalSQLDialect &&
                ((RelationalSQLDialect) dialect).getLikeEscapeClause(SQLConstants.DEFAULT_LIKE_ESCAPE) != null)
            {
                sql.append(((RelationalSQLDialect) dialect).getLikeEscapeClause(SQLConstants.DEFAULT_LIKE_ESCAPE));
            }
        } else {
            sql.append(not ? "<>?" : "=?");
        }
    }

    public static boolean appendFirstClause(StringBuilder sql, boolean firstClause)
    {
        if (firstClause) {
            sql.append(" WHERE ");
        } else {
            sql.append(" AND ");
        }
        return false;
    }

    public static String trimQueryStatement(SQLSyntaxManager syntaxManager, String sql, boolean trimDelimiter)
    {
        // This is called only when use selects query (i.e. no automatic query detection)
        if (sql.isEmpty() || !trimDelimiter) {
            // Do not trim delimiter
            return sql;
        }

        // Here we cur trailing query delimiter. most of DBs don't expect it in the end of query
        // However Oracle REQUIRES that block queries (e.g. DDL like CREATE PROCEDURE) must have trailing delimiter
        // So we check whether this query is a block query (by checking for all SQL dialect block delimiters)
        String trailingSpaces = "";
        {
            int trailingSpacesCount = 0;
            for (int i = sql.length() - 1; i >= 0; i--) {
                if (!Character.isWhitespace(sql.charAt(i))) {
                    break;
                }
                trailingSpacesCount++;
            }
            if (trailingSpacesCount > 0) {
                trailingSpaces = sql.substring(sql.length() - trailingSpacesCount);
                sql = sql.substring(0, sql.length() - trailingSpacesCount);
            }
        }
        for (String statementDelimiter : syntaxManager.getStatementDelimiters()) {
            if (!sql.endsWith(statementDelimiter) && sql.length() > statementDelimiter.length()) {
                continue;
            }
            if (Character.isAlphabetic(statementDelimiter.charAt(0))) {
                // Delimiter is alphabetic (e.g. "GO") so it must be prefixed with whitespace
                char lastChar = sql.charAt(sql.length() - statementDelimiter.length() - 1);
                if (Character.isUnicodeIdentifierPart(lastChar)) {
                    break;
                }
            }
            // Remove trailing delimiter only if it is not block end
            boolean isBlockQuery = false;
            String trimmed = sql.substring(0, sql.length() - statementDelimiter.length());
            {
                String test = trimmed.toUpperCase().trim();
                String[][] blockBoundStrings = syntaxManager.getDialect().getBlockBoundStrings();
                if (blockBoundStrings != null) {
                    for (String[] blocks : blockBoundStrings) {
                        int endIndex = test.lastIndexOf(blocks[1]);
                        if (endIndex > 0) {
                            // This is a block query if it ends with 'END' or with 'END id'
                            if (test.endsWith(blocks[1])) {
                                isBlockQuery = true;
                                break;
                            } else {
                                String afterEnd = test.substring(endIndex + blocks[1].length()).trim();
                                if (afterEnd.chars().noneMatch(Character::isWhitespace)) {
                                    isBlockQuery = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (!isBlockQuery) {
                sql = trimmed;
            }
            break;
        }
        return sql + trailingSpaces;
    }

    public static boolean isBlockStartKeyword(SQLDialect dialect, String keyword) {
        String[][] blockBoundStrings = dialect.getBlockBoundStrings();
        if (blockBoundStrings != null) {
            for (String[] block : blockBoundStrings) {
                if (block.length > 0 && keyword.equalsIgnoreCase(block[0])) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isBlockEndKeyword(SQLDialect dialect, String keyword) {
        String[][] blockBoundStrings = dialect.getBlockBoundStrings();
        if (blockBoundStrings != null) {
            for (String[] block : blockBoundStrings) {
                if (block.length > 1 && keyword.equalsIgnoreCase(block[1])) {
                    return true;
                }
            }
        }
        return false;
    }

    @NotNull
    public static SQLDialect getDialectFromObject(DBPObject object)
    {
        if (object instanceof DBSObject) {
            DBPDataSource dataSource = ((DBSObject)object).getDataSource();
            return getDialectFromDataSource(dataSource);
        }
        return BasicSQLDialect.INSTANCE;
    }

    @NotNull
    public static SQLDialect getDialectFromDataSource(@Nullable DBPDataSource dataSource) {
        return dataSource == null ? BasicSQLDialect.INSTANCE : dataSource.getSQLDialect();
    }

    public static void appendConditionString(
        @NotNull DBDDataFilter filter,
        @NotNull DBPDataSource dataSource,
        @Nullable String conditionTable,
        @NotNull StringBuilder query,
        boolean inlineCriteria)
    {
        appendConditionString(filter, dataSource, conditionTable, query, inlineCriteria, false);
    }

    public static void appendConditionString(
        @NotNull DBDDataFilter filter,
        @NotNull DBPDataSource dataSource,
        @Nullable String conditionTable,
        @NotNull StringBuilder query,
        boolean inlineCriteria,
        boolean subQuery
    ) {
        dataSource.getSQLDialect().getQueryGenerator().appendConditionString(filter, dataSource, conditionTable, query, inlineCriteria,
            subQuery);
    }

    public static void appendConditionString(
        @NotNull DBDDataFilter filter,
        @NotNull List<DBDAttributeConstraint> constraints,
        @NotNull DBPDataSource dataSource,
        @Nullable String conditionTable,
        @NotNull StringBuilder query,
        boolean inlineCriteria,
        boolean subQuery) {
        dataSource.getSQLDialect().getQueryGenerator().appendConditionString(filter, constraints, dataSource,
            conditionTable, query, inlineCriteria, subQuery);
    }

    public static void appendOrderString(
        @NotNull DBDDataFilter filter,
        @NotNull DBPDataSource dataSource,
        @Nullable String conditionTable,
        boolean subQuery,
        @NotNull StringBuilder query) {
        dataSource.getSQLDialect()
            .getQueryGenerator()
            .appendOrderString(filter, dataSource, conditionTable, subQuery, query);
    }

    @Nullable
    public static String getConstraintCondition(@NotNull DBPDataSource dataSource, @NotNull DBDAttributeConstraint constraint, @Nullable String conditionTable, boolean inlineCriteria) {
        return dataSource.getSQLDialect().getQueryGenerator().getConstraintCondition(dataSource, constraint,
            conditionTable,
            inlineCriteria);
    }

    private static String getStringValue(@NotNull DBPDataSource dataSource, @NotNull DBDAttributeConstraint constraint, boolean inlineCriteria, Object value) {
        String strValue;
        if (constraint.getAttribute() == null) {
            // We have only attribute name
            if (value instanceof CharSequence) {
                strValue = dataSource.getSQLDialect().getQuotedString(value.toString());
            } else {
                strValue = CommonUtils.toString(value);
            }
        } else if (inlineCriteria) {
            strValue = convertValueToSQL(dataSource, constraint.getAttribute(), value);
        } else {
            strValue = dataSource.getSQLDialect().getTypeCastClause(constraint.getAttribute(), "?", true);
        }
        return strValue;
    }

    public static int getConstraintOrderIndex(@NotNull DBDDataFilter dataFilter, @NotNull DBDAttributeConstraint constraint) {
        int index = dataFilter.getConstraints().indexOf(constraint);
        return index == -1 ? index : index + 1;
    }

    public static String convertValueToSQL(@NotNull DBPDataSource dataSource, @NotNull DBSTypedObject attribute, @Nullable Object value) {
        DBDValueHandler valueHandler = DBUtils.findValueHandler(dataSource, attribute);

        return convertValueToSQL(dataSource, attribute, valueHandler, value, DBDDisplayFormat.NATIVE);
    }

    public static String convertValueToSQL(@NotNull DBPDataSource dataSource, @NotNull DBSTypedObject attribute, @NotNull DBDValueHandler valueHandler, @Nullable Object value, DBDDisplayFormat displayFormat) {
        if (DBUtils.isNullValue(value)) {
            return SQLConstants.NULL_VALUE;
        }

        return dataSource.getSQLDialect().getTypeCastClause(
            attribute,
            convertValueToSQLFormat(dataSource, attribute, valueHandler, value, displayFormat), false);
    }

    private static String convertValueToSQLFormat(@NotNull DBPDataSource dataSource, @NotNull DBSTypedObject attribute, @NotNull DBDValueHandler valueHandler, @Nullable Object value, DBDDisplayFormat displayFormat) {
        if (DBUtils.isNullValue(value)) {
            return SQLConstants.NULL_VALUE;
        }

        String strValue;

        if (value instanceof DBDContent) {
            strValue = convertStreamToSQL(attribute, (DBDContent) value, valueHandler, dataSource);
        } else {
            strValue = valueHandler.getValueDisplayString(attribute, value, displayFormat);
        }
        SQLDialect sqlDialect = dataSource.getSQLDialect();

        DBPDataKind dataKind = attribute.getDataKind();
        switch (dataKind) {
            case CONTENT:
                if (value instanceof DBDContent) {
                    String contentType = ((DBDContent) value).getContentType();
                    if (contentType != null && !contentType.startsWith("text")) {
                        return strValue;
                    }
                }
                // Text content. Fall down
            case STRING:
            case ROWID:
                if (sqlDialect != null) {
                    return sqlDialect.getQuotedString(strValue);
                }
                return strValue;
            case BOOLEAN:
            case NUMERIC:
            default:
                if (sqlDialect != null) {
                    return sqlDialect.escapeScriptValue(attribute, value, strValue);
                }
                return strValue;
        }
    }

    public static String convertStreamToSQL(DBSTypedObject attribute, DBDContent content, DBDValueHandler valueHandler, DBPDataSource dataSource) {
        try {
            DBRProgressMonitor monitor = new VoidProgressMonitor();
            if (!content.isNull() && ContentUtils.isTextContent(content)) {
                return ContentUtils.getContentStringValue(monitor, content);
            } else {
                byte[] binValue = ContentUtils.getContentBinaryValue(monitor, content);
                if (binValue == null) {
                    return SQLConstants.NULL_VALUE;
                }
                return dataSource.getSQLDialect().getNativeBinaryFormatter().toString(binValue, 0, binValue.length);
            }
        }
        catch (Throwable e) {
            log.warn(e);
            return SQLConstants.NULL_VALUE;
        }
    }

    public static String getColumnTypeModifiers(@Nullable DBPDataSource dataSource, DBSTypedObject column, @NotNull String typeName, @NotNull DBPDataKind dataKind) {
        if (column == null) {
            return null;
        }
        if (dataSource == null) {
            return null;
        }
        return dataSource.getSQLDialect().getColumnTypeModifiers(dataSource, column, typeName, dataKind);
    }

    public static String getScriptDescripion(@NotNull String sql) {
        sql = stripComments(BasicSQLDialect.INSTANCE, sql);
        Matcher matcher = CREATE_PREFIX_PATTERN.matcher(sql);
        if (matcher.find() && matcher.start(0) == 0) {
            sql = sql.substring(matcher.end(1));
        }
        sql = sql.replaceAll(" +", " ");
        if (sql.length() > MAX_SQL_DESCRIPTION_LENGTH) {
            sql = sql.substring(0, MAX_SQL_DESCRIPTION_LENGTH) + " ...";
        }
        return sql;
    }

    @Nullable
    public static String getScriptDescription(@NotNull IFile sqlScript)
    {
        try {
            //log.debug("Read script '" + sqlScript.getName() + "' description");
            StringBuilder sql = new StringBuilder();
            try (BufferedReader is = new BufferedReader(new InputStreamReader(sqlScript.getContents()))) {
                for (;;) {
                    String line = is.readLine();
                    if (line == null) {
                        break;
                    }
                    line = line.trim();
                    if (line.startsWith(SQLConstants.SL_COMMENT) ||
                        line.startsWith("Rem") ||
                        line.startsWith("rem") ||
                        line.startsWith("REM")
                        )
                    {
                        continue;
                    }
                    sql.append(line).append('\n');
                    if (sql.length() > MIN_SQL_DESCRIPTION_LENGTH) {
                        break;
                    }
                }
            }
            return SQLUtils.getScriptDescripion(sql.toString());
        } catch (Exception e) {
            log.warn("", e);
        }
        return null;
    }

    public static String generateEntityAlias(DBSEntity entity, DBRFinder<Boolean, String> aliasFinder) {
        String name = entity.getName();
        if (CommonUtils.isEmpty(name)) {
            return name;
        }

        StringBuilder buf = new StringBuilder();
        boolean prevNonLetter = true;
        char prevChar = 0;
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (!Character.isLetter(c)) {
                prevNonLetter = true;
            } else {
                if (prevNonLetter || (prevChar != 0 && Character.isLowerCase(prevChar) && Character.isUpperCase(c))) {
                    buf.append(c);
                }
                prevNonLetter = false;
            }
            prevChar = c;
        }
        String alias;
        if(!CommonUtils.isEmpty(buf)) {
            alias = buf.toString().toLowerCase(Locale.ENGLISH);
        }
        else{
            alias = "t";
        }

        String result = alias;
        for (int i = 2; i < 500; i++) {
            if (aliasFinder.findObject(result)) {
                result = alias + i;
            } else {
                return result;
            }
        }

        return alias;
    }

    @NotNull
    public static String generateCommentLine(@Nullable DBPDataSource dataSource, @NotNull String comment) {
        final String separator = GeneralUtils.getDefaultLineSeparator();
        String slComment = SQLConstants.SL_COMMENT;
        if (dataSource != null) {
            String[] slComments = dataSource.getSQLDialect().getSingleLineComments();
            if (!ArrayUtils.isEmpty(slComments)) {
                slComment = slComments[0];
            }
        }
        final StringBuilder sb = new StringBuilder();
        for (String line : comment.split("\n|\r|\r\n")) {
            sb.append(slComment).append(" ").append(line).append(separator);
        }
        return sb.toString();
    }

    public static String generateParamList(int paramCount) {
        if (paramCount == 0) {
            return "";
        } else if (paramCount == 1) {
            return "?";
        }
        StringBuilder sql = new StringBuilder("?");
        for (int i = 0; i < paramCount - 1; i++) {
            sql.append(",?");
        }
        return sql.toString();
    }

    /**
     * Replaces single \r linefeeds with space (some databases don't like them)
     */
    public static String fixLineFeeds(String sql) {
        if (sql.indexOf('\r') == -1) {
            return sql;
        }
        boolean hasFixes = false;
        char[] fixed = sql.toCharArray();
        for (int i = 0; i < fixed.length; i++) {
            if (fixed[i] == '\r') {
                if (i > 0 && fixed[i - 1] == '\n') {
                    // \n\r
                    continue;
                }
                if (i == fixed.length - 1 || fixed[i + 1] == '\n') {
                    // \r\n
                    continue;
                }
                // Single \r - replace it with space
                fixed[i] = ' ';
                hasFixes = true;
            }
        }
        return hasFixes ? String.valueOf(fixed) : sql;
    }

    /**
     * Compares two string ignoring extra whitespaces.
     * We can remove double whitespaces and any whitespaces between special chars (*-+,: etc).
     */
    public static boolean compareAliases(String str1, String str2) {
        if (str1 == null && str2 == null) {
            return true;
        }
        if (str1 == null || str2 == null) {
            return false;
        }
        return removeExtraSpaces(str1).equals(removeExtraSpaces(str2));
    }

    public static String removeExtraSpaces(@NotNull String str) {
        if (str.indexOf(' ') == -1) {
            return str;
        }
        StringBuilder result = new StringBuilder(str.length());
        int length = str.length();
        for (int i = 0; i < length; i++) {
            char c = str.charAt(i);
            if (Character.isWhitespace(c)) {
                boolean needsSpace = i > 0 && Character.isLetterOrDigit(str.charAt(i - 1));
                for (i = i + 1; i < length; i++) {
                    c = str.charAt(i);
                    if (Character.isWhitespace(c)) {
                        continue;
                    }
                    if (needsSpace && Character.isLetterOrDigit(c)) {
                        // We need exactly one space before letter/digit
                        result.append(' ');
                    } else {
                        // We don't need spaces before control symbols
                    }
                    result.append(c);
                    break;
                }
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

    @NotNull
    public static String generateScript(DBPDataSource dataSource, DBEPersistAction[] persistActions, boolean addComments)
    {
        final SQLDialect sqlDialect = SQLUtils.getDialectFromDataSource(dataSource);
        final String lineSeparator = GeneralUtils.getDefaultLineSeparator();

        StringBuilder script = new StringBuilder(64);
        if (addComments) {
            script.append(DBEAVER_DDL_COMMENT).append(Platform.getProduct().getName()).append(lineSeparator)
                .append(DBEAVER_DDL_WARNING).append(lineSeparator);
        }
        if (persistActions != null) {
            for (DBEPersistAction action : persistActions) {
                String scriptLine = action.getScript();
                if (CommonUtils.isEmpty(scriptLine)) {
                    continue;
                }

                String redefiner = sqlDialect.getScriptDelimiterRedefiner();
                String delimiter = getScriptLineDelimiter(sqlDialect);
                if (action.isComplex() && redefiner != null && !redefiner.equals(delimiter)) {
                    script.append(lineSeparator).append(redefiner).append(" ").append(DBEAVER_SCRIPT_DELIMITER).append(lineSeparator);
                    delimiter = DBEAVER_SCRIPT_DELIMITER;
                    script.append(delimiter).append(lineSeparator);
                } else if (action.getType() == DBEPersistAction.ActionType.COMMENT) {
                    if (script.length() > 2) {
                        int lfCount = 0;
                        for (int i = script.length() - 1; i >= 0; i--) {
                            if (!Character.isWhitespace(script.charAt(i))) {
                                break;
                            }
                            if (script.charAt(i) == '\n') lfCount++;
                        }
                        if (lfCount < 2) {
                            // Add line feed if we do not have empty line before
                            script.append(lineSeparator);
                        }
                    }
                }
                script.append(scriptLine);
                if (action.getType() != DBEPersistAction.ActionType.COMMENT) {
                    String testLine = scriptLine.trim();
                    if (testLine.lastIndexOf(delimiter) != (testLine.length() - delimiter.length())) {
                        script.append(delimiter);
                    }
                } else {
                    script.append(lineSeparator);
                }
                script.append(lineSeparator);

                if (action.isComplex() && redefiner != null && !redefiner.equals(delimiter)) {
                    script.append(redefiner).append(" ").append(getScriptLineDelimiter(sqlDialect)).append(lineSeparator);
                }
            }
        }
        return script.toString();
    }

    @NotNull
    public static String generateComments(DBPDataSource dataSource, DBEPersistAction[] persistActions, boolean addComments)
    {
        final SQLDialect sqlDialect = SQLUtils.getDialectFromDataSource(dataSource);
        final String lineSeparator = GeneralUtils.getDefaultLineSeparator();

        StringBuilder script = new StringBuilder(64);
        if (addComments) {
            script.append(DBEAVER_DDL_COMMENT).append(Platform.getProduct().getName()).append(lineSeparator)
                .append(DBEAVER_DDL_WARNING).append(lineSeparator);
        }
        if (persistActions != null) {
            String slComment;
            String[] slComments = sqlDialect.getSingleLineComments();
            if (ArrayUtils.isEmpty(slComments)) {
                slComment = "--";
            } else {
                slComment = slComments[0];
            }
            for (DBEPersistAction action : persistActions) {
                if (action.getType() != DBEPersistAction.ActionType.COMMENT) {
                    String scriptLine = action.getTitle();
                    if (CommonUtils.isEmpty(scriptLine)) {
                        continue;
                    }
                    script.append(slComment).append(" ").append(scriptLine);
                } else {
                    String scriptLine = action.getScript();
                    if (CommonUtils.isEmpty(scriptLine)) {
                        continue;
                    }
                    script.append(scriptLine);
                }
                script.append(lineSeparator);
            }
        }
        return script.toString();
    }

    public static String getScriptLineDelimiter(SQLDialect sqlDialect) {
        String delimiter = SQLUtils.getDefaultScriptDelimiter(sqlDialect);
        if (!delimiter.isEmpty() && Character.isLetterOrDigit(delimiter.charAt(0))) {
            delimiter = ' ' + delimiter;
        }
        return delimiter;
    }

    public static String[] splitFullIdentifier(final String fullName, char nameSeparator, String[][] quoteStrings) {
        return splitFullIdentifier(fullName, String.valueOf(nameSeparator), quoteStrings, false);
    }

    public static String[] splitFullIdentifier(final String fullName, String nameSeparator, String[][] quoteStrings, boolean keepQuotes) {
        String name = fullName.trim();
        if (ArrayUtils.isEmpty(quoteStrings)) {
            return name.split(Pattern.quote(nameSeparator));
        }
        if (!name.contains(nameSeparator)) {
            name = keepQuotes ? name : DBUtils.getUnQuotedIdentifier(name, quoteStrings);
            return new String[]{name};
        }
        List<String> nameList = new ArrayList<>();
        while (!name.isEmpty()) {
            boolean hadQuotedPart = false;
            for (String[] quotePair : quoteStrings) {
                String startQuote = quotePair[0];
                String endQuote = quotePair[1];
                if (!CommonUtils.isEmpty(startQuote) && !CommonUtils.isEmpty(endQuote) && name.startsWith(startQuote)) {
                    int endPos = name.indexOf(endQuote, startQuote.length());
                    if (endPos != -1) {
                        // Quoted part
                        String partName = keepQuotes ?
                            name.substring(0, endPos + endQuote.length()) :
                            name.substring(startQuote.length(), endPos);
                        while (partName.endsWith(nameSeparator)) {
                            partName = partName.substring(0, partName.length() - 1);
                        }
                        if (!partName.isEmpty()) {
                            nameList.add(partName);
                        }
                        name = name.substring(endPos + endQuote.length()).trim();
                        hadQuotedPart = true;
                        break;
                    }
                }
            }
            if (!hadQuotedPart) {
                int endPos = name.indexOf(nameSeparator);
                if (endPos != -1) {
                    nameList.add(name.substring(0, endPos));
                    name = name.substring(endPos);
                } else {
                    nameList.add(name);
                    break;
                }
            }
            if (!name.isEmpty() && name.startsWith(nameSeparator)) {
                name = name.substring(nameSeparator.length()).trim();
            }
        }
        return nameList.toArray(new String[0]);
    }

    public static String generateTableJoin(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException {
        // Try to find FK in left table referencing to right table
        String sql = generateTableJoinByAssociation(monitor, leftTable, leftAlias, rightTable, rightAlias);
        if (sql != null) return sql;

        // Now try right to left
        sql = generateTableJoinByAssociation(monitor, rightTable, rightAlias, leftTable, leftAlias);
        if (sql != null) return sql;

        // Try to find columns in left table which match unique key in right table
        sql = generateTableJoinByColumns(monitor, leftTable, leftAlias, rightTable, rightAlias);
        if (sql != null) return sql;

        // In reverse order
        sql = generateTableJoinByColumns(monitor, rightTable, rightAlias, leftTable, leftAlias);
        if (sql != null) return sql;

        return null;
    }

    private static String generateTableJoinByColumns(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException {
        List<DBSEntityAttribute> leftIdentifier = new ArrayList<>(DBUtils.getBestTableIdentifier(monitor, leftTable));
        if (!leftIdentifier.isEmpty()) {
            List<DBSEntityAttribute> rightAttributes = new ArrayList<>();
            for (DBSEntityAttribute attr : leftIdentifier) {
                DBSEntityAttribute rightAttr = rightTable.getAttribute(monitor, attr.getName());
                if (rightAttr == null) {
                    break;
                }
                rightAttributes.add(rightAttr);
            }
            if (leftIdentifier.size() != rightAttributes.size()) {
                return null;
            }
            StringBuilder joinSQL = new StringBuilder();
            for (int i = 0; i < leftIdentifier.size(); i++) {
                joinSQL
                    .append(leftAlias).append(".").append(DBUtils.getQuotedIdentifier(leftIdentifier.get(i))).append(" = ")
                    .append(rightAlias).append(".").append(DBUtils.getQuotedIdentifier(rightAttributes.get(i)));
            }
            return joinSQL.toString();
        }
        return null;
    }

    private static String generateTableJoinByAssociation(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException {
        Collection<? extends DBSEntityAssociation> associations = leftTable.getAssociations(monitor);
        if (!CommonUtils.isEmpty(associations)) {
            for (DBSEntityAssociation fk : associations) {
                if (fk instanceof DBSTableForeignKey && fk.getAssociatedEntity() == rightTable) {
                    return generateTablesJoin(monitor, (DBSTableForeignKey)fk, leftAlias, rightAlias);
                }
            }
        }
        return null;
    }

    private static String generateTablesJoin(DBRProgressMonitor monitor, DBSTableForeignKey fk, String leftAlias, String rightAlias) throws DBException {
        boolean hasCriteria = false;
        StringBuilder joinSQL = new StringBuilder();
        for (DBSEntityAttributeRef ar : fk.getAttributeReferences(monitor)) {
            if (ar instanceof DBSTableForeignKeyColumn) {
                if (hasCriteria) {
                    joinSQL.append(" AND ");
                }
                DBSTableForeignKeyColumn fkc = (DBSTableForeignKeyColumn)ar;
                joinSQL
                    .append(leftAlias).append(".").append(DBUtils.getQuotedIdentifier(fkc)).append(" = ")
                    .append(rightAlias).append(".").append(DBUtils.getQuotedIdentifier(fkc.getReferencedColumn()));
                hasCriteria = true;
            }
        }
        return joinSQL.toString();
    }

    public static String getTableAlias(DBSEntity table) {
        return CommonUtils.escapeIdentifier(table.getName());
    }

    public static void appendQueryConditions(
        DBPDataSource dataSource,
        @NotNull StringBuilder query,
        @Nullable String tableAlias,
        @Nullable DBDDataFilter dataFilter
    ) {
        dataSource.getSQLDialect().getQueryGenerator().appendQueryConditions(dataSource, query, tableAlias, dataFilter);
    }

    public static void appendQueryOrder(
        DBPDataSource dataSource,
        @NotNull StringBuilder query,
        @Nullable String tableAlias,
        @Nullable DBDDataFilter dataFilter
    ) {
        dataSource.getSQLDialect().getQueryGenerator().appendQueryOrder(dataSource, query, tableAlias, dataFilter);
    }

    public static boolean isExecQuery(@NotNull SQLDialect dialect, String query) {
        // Check for EXEC query
        final String[] executeKeywords = dialect.getExecuteKeywords();
        if (executeKeywords != null && executeKeywords.length > 0) {
            final String queryStart = getFirstKeyword(dialect, query);
            return isExecKeyword(dialect, queryStart);
        }
        return false;
    }

    public static boolean isExecKeyword(SQLDialect dialect, String word) {
        return ArrayUtils.containsIgnoreCase(dialect.getExecuteKeywords(), word);
    }

    public static String stripColumnTypeModifiers(String type) {
        int startPos = type.indexOf("(");
        if (startPos != -1) {
            int endPos = type.lastIndexOf(")");
            if (endPos != -1) {
                return type.substring(0, startPos);
            }
        }
        return type;
    }

    public static void fillQueryParameters(SQLQuery sqlStatement, List<SQLQueryParameter> parameters) {
        // Set values for all parameters
        // Replace parameter tokens with parameter values
        String query = sqlStatement.getText();
        for (int i = parameters.size(); i > 0; i--) {
            SQLQueryParameter parameter = parameters.get(i - 1);
            String paramValue = parameter.getValue();
            if (paramValue == null || paramValue.isEmpty()) {
                paramValue = SQLConstants.NULL_VALUE;
            }
            query = query.substring(0, parameter.getTokenOffset()) + paramValue + query.substring(parameter.getTokenOffset() + parameter.getTokenLength());
        }
        sqlStatement.setText(query);
        //sqlStatement.setOriginalText(query);
    }

    public static boolean needQueryDelimiter(SQLDialect sqlDialect, String query) {
        String[] scriptDelimiters = sqlDialect.getScriptDelimiters();
        for (String delimiter : scriptDelimiters) {
            if (!delimiter.isEmpty()) {
                if (Character.isLetterOrDigit(delimiter.charAt(0))) {
                    if (query.toUpperCase().endsWith(delimiter.toUpperCase())) {
                        if (!Character.isLetterOrDigit(query.charAt(query.length() - delimiter.length() - 1))) {
                            return true;
                        }
                    }
                } else {
                    return !query.endsWith(delimiter);
                }
            }
        }
        return false;
    }

    public static String removeQueryDelimiter(SQLDialect sqlDialect, String query) {
        String[] scriptDelimiters = sqlDialect.getScriptDelimiters();
        for (String delimiter : scriptDelimiters) {
            if (!delimiter.isEmpty() && query.contains(delimiter)) {
                String queryWithoutDelimiter = query.substring(0, query.lastIndexOf(delimiter));
                if (Character.isLetterOrDigit(delimiter.charAt(0))) {
                    if (query.toUpperCase().endsWith(delimiter.toUpperCase())) {
                        if (!Character.isLetterOrDigit(query.charAt(query.length() - delimiter.length() - 1))) {
                            return queryWithoutDelimiter;
                        }
                    }
                } else if (query.endsWith(delimiter)) {
                    return queryWithoutDelimiter;
                }
            }
        }
        return query;
    }

    public static String getDefaultScriptDelimiter(SQLDialect sqlDialect) {
        String[] scriptDelimiters = sqlDialect.getScriptDelimiters();
        if (!ArrayUtils.isEmpty(scriptDelimiters)) {
            return scriptDelimiters[0];
        }
        return SQLConstants.DEFAULT_STATEMENT_DELIMITER;
    }
}


text:
/*
 *******************************************************************************
 *   BTChip Bitcoin Hardware Wallet Java API
 *   (c) 2014 BTChip - 1BTChip7VfTnrPra5jqci7ejnMguuHogTn
 *   (c) 2018 m2049r
 *
 *  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.
 ********************************************************************************
 */

package com.btchip.comm;

import java.io.ByteArrayOutputStream;

public class LedgerHelper {

    private static final int TAG_APDU = 0x05;

    public static byte[] wrapCommandAPDU(int channel, byte[] command, int packetSize) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        if (packetSize < 3) {
            throw new IllegalArgumentException("Can't handle Ledger framing with less than 3 bytes for the report");
        }
        int sequenceIdx = 0;
        int offset = 0;
        output.write(channel >> 8);
        output.write(channel);
        output.write(TAG_APDU);
        output.write(sequenceIdx >> 8);
        output.write(sequenceIdx);
        sequenceIdx++;
        output.write(command.length >> 8);
        output.write(command.length);
        int blockSize = (command.length > packetSize - 7 ? packetSize - 7 : command.length);
        output.write(command, offset, blockSize);
        offset += blockSize;
        while (offset != command.length) {
            output.write(channel >> 8);
            output.write(channel);
            output.write(TAG_APDU);
            output.write(sequenceIdx >> 8);
            output.write(sequenceIdx);
            sequenceIdx++;
            blockSize = (command.length - offset > packetSize - 5 ? packetSize - 5 : command.length - offset);
            output.write(command, offset, blockSize);
            offset += blockSize;
        }
        if ((output.size() % packetSize) != 0) {
            byte[] padding = new byte[packetSize - (output.size() % packetSize)];
            output.write(padding, 0, padding.length);
        }
        return output.toByteArray();
    }

    public static byte[] unwrapResponseAPDU(int channel, byte[] data, int packetSize) {
        ByteArrayOutputStream response = new ByteArrayOutputStream();
        int offset = 0;
        int responseLength;
        int sequenceIdx = 0;
        if ((data == null) || (data.length < 7 + 5)) {
            return null;
        }
        if (data[offset++] != (channel >> 8)) {
            throw new IllegalArgumentException("Invalid channel");
        }
        if (data[offset++] != (channel & 0xff)) {
            throw new IllegalArgumentException("Invalid channel");
        }
        if (data[offset++] != TAG_APDU) {
            throw new IllegalArgumentException("Invalid tag");
        }
        if (data[offset++] != 0x00) {
            throw new IllegalArgumentException("Invalid sequence");
        }
        if (data[offset++] != 0x00) {
            throw new IllegalArgumentException("Invalid sequence");
        }
        responseLength = ((data[offset++] & 0xff) << 8);
        responseLength |= (data[offset++] & 0xff);
        if (data.length < 7 + responseLength) {
            return null;
        }
        int blockSize = (responseLength > packetSize - 7 ? packetSize - 7 : responseLength);
        response.write(data, offset, blockSize);
        offset += blockSize;
        while (response.size() != responseLength) {
            sequenceIdx++;
            if (offset == data.length) {
                return null;
            }
            if (data[offset++] != (channel >> 8)) {
                throw new IllegalArgumentException("Invalid channel");
            }
            if (data[offset++] != (channel & 0xff)) {
                throw new IllegalArgumentException("Invalid channel");
            }
            if (data[offset++] != TAG_APDU) {
                throw new IllegalArgumentException("Invalid tag");
            }
            if (data[offset++] != (sequenceIdx >> 8)) {
                throw new IllegalArgumentException("Invalid sequence");
            }
            if (data[offset++] != (sequenceIdx & 0xff)) {
                throw new IllegalArgumentException("Invalid sequence");
            }
            blockSize = (responseLength - response.size() > packetSize - 5 ? packetSize - 5 : responseLength - response.size());
            if (blockSize > data.length - offset) {
                return null;
            }
            response.write(data, offset, blockSize);
            offset += blockSize;
        }
        return response.toByteArray();
    }

}


text:
package org.opensaml.xml.signature.impl;

import org.opensaml.xml.AbstractXMLObjectBuilder;
import org.opensaml.xml.signature.X509Data;
import org.opensaml.xml.signature.XMLSignatureBuilder;
import org.opensaml.xml.util.XMLConstants;

/**
 * Builder of {@link org.opensaml.xml.signature.X509Data}
 */
public class X509DataBuilder extends AbstractXMLObjectBuilder<X509Data> implements XMLSignatureBuilder<X509Data> {

    /**
     * Constructor
     *
     */
    public X509DataBuilder() {
    }

    /** {@inheritDoc} */
    public X509Data buildObject(String namespaceURI, String localName, String namespacePrefix) {
        return new X509DataImpl(namespaceURI, localName, namespacePrefix);
    }

    /** {@inheritDoc} */
    public X509Data buildObject() {
        return buildObject(XMLConstants.XMLSIG_NS, X509Data.DEFAULT_ELEMENT_LOCAL_NAME, XMLConstants.XMLSIG_PREFIX);
    }

}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-index',
  template: `
    <app-child [(value)]="parentValue"></app-child>

Parent Value: {{ parentValue }}

  `
})
export class IndexComponent implements OnInit {
  public parentValue = 'two way binding';

  constructor() { }

  ngOnInit() {
  }

}


text:
// This file is automatically generated.

package adila.db;

/*
 * Alcatel ONE TOUCH 6030X-orange
 *
 * DEVICE: Diablo
 * MODEL: ALCATEL ONE TOUCH 6030X-orange
 */
final class diablo_alcatel20one20touch206030x2dorange {
    public static final String DATA = "Alcatel|ONE TOUCH 6030X-orange|";
}


text:
"""Testing the functions in typhon.geographical.
"""
import numpy as np

from typhon import geographical

class TestGeographical:
    """Testing the geographical functions."""
    def test_area_weighted_mean(self):
        """Test calculation of area weighted mean."""
        lon = np.arange(0, 360, 10)
        lat = np.arange(-90, 90, 10)
        f = np.ones(lon.shape) + np.cos(np.deg2rad(lat))[:, np.newaxis]
        mean = geographical.area_weighted_mean(lon, lat, f)

        assert np.allclose(mean, 1.7852763105888174)

class TestGeoIndex:
    """Testing the GeoIndex functions."""

    def test_query(self):
        """Test the function collocate with dicts, xarray and GroupedArrays.
        Checks on temporal, spatial and temporal-spatial conditions.

        """
        # Update this test
        return

        # Test with dictionaries:
        lat1 = 30. * np.sin(np.linspace(-3.14, 3.14, 24)) + 20
        lon1 = np.linspace(0, 90, 24)
        lat2 = 30. * np.sin(np.linspace(-3.14, 3.14, 24) + 1.) + 20
        lon2 = np.linspace(0, 90, 24)

        index = geographical.GeoIndex(lat1, lon1)
        pairs, distances = index.query(lat2, lon2, r="500 km")

        check_pairs = [
            [4, 15, 15, 16],
            [4, 15, 16, 15]
        ]

        assert pairs.tolist() == check_pairs


text:
gtts
============
With google text to speech utility you can write text on your terminal and google will read it for you.

How to use it
----------------------
Just clone the repository and hit. Do not forget to install the dependencies with npm.

```sh
$ coffee gtts.coffee
Hola mundo
[ctrl+d]
```

Pretty easy. By default will read the text as es_MX but you can specify your language.

```sh
$ coffee gtts.coffee -l en_US
Hello world
[ctrl+d]
```

If you have a text file and want to listen  instead of read, you can use gtts too.

```sh
$ coffee gtts.coffee -l en_US < my_bored_file.txt
```

Maybe you want to listen after, gtts allows you to create a mp3 file too.

```sh
$ coffee gtts.coffee -l en_US -o ~/my_file.mp3 < my_bored_file.txt
```

And of course, you can only create the mp3 and do not listening the result with -n option.

```sh
$ coffee gtts.coffee -l en_US -n -o ~/my_file.mp3 < my_bored_file.txt
```

Know issues
----------------------
Exit when finish instead ctrl+c.


text:
package net.sf.esfinge.metadata.validate.optimizeExecution.CT14;

import net.sf.esfinge.metadata.validate.optimizeExecution.Logging02;

public class OrderProcessing14{
	@Logging02
	public void registerPurchase(){}
}