/**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2006 Sun Microsystems Inc. All Rights Reserved
 *
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License). You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the License at
 * https://opensso.dev.java.net/public/CDDLv1.0.html or
 * opensso/legal/CDDLv1.0.txt
 * See the License for the specific language governing
 * permission and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at opensso/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * $Id: AMIdentitySubject.java,v 1.3 2008/06/25 05:43:50 qcheng Exp $
 *
 */

/*
 * Portions Copyrighted [2011] [ForgeRock AS]
 */
package com.sun.identity.policy.plugins;

import com.iplanet.sso.SSOToken;
import com.iplanet.sso.SSOException;

import com.sun.identity.shared.debug.Debug;

import com.sun.identity.idm.AMIdentity;
import com.sun.identity.idm.IdRepoException;
import com.sun.identity.idm.IdType;
import com.sun.identity.idm.IdUtils;

import com.sun.identity.policy.PolicyException;
import com.sun.identity.policy.PolicyEvaluator;
import com.sun.identity.policy.ValidValues;
import com.sun.identity.policy.ResBundleUtils;
import com.sun.identity.policy.PolicyManager;
import com.sun.identity.policy.Syntax;
import com.sun.identity.policy.NameNotFoundException;
import com.sun.identity.policy.InvalidNameException;
import com.sun.identity.policy.SubjectEvaluationCache;

import com.sun.identity.policy.interfaces.Subject;

import com.sun.identity.security.AdminTokenAction;

import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;

import java.security.Principal;
import java.security.AccessController;

/**
 * AMIdentitySubject is a Subject implementation that checks for
 * membership in a set of AMIdentity objects using the underlying
 * Identity repository service.
 *
 * @deprecated Use {@link org.forgerock.openam.entitlement.conditions.subject.IdentitySubject} instead.
 */
@Deprecated
public class AMIdentitySubject implements Subject {

    private Set subjectValues = new HashSet();

    private static Debug debug = Debug.getInstance(
        PolicyManager.POLICY_DEBUG_NAME);

    /** Constructs an AMIdentityObject
     */
    public AMIdentitySubject() {
    }

    /**
     * Initialize the AMIdentitySubject object by using the configuration
     * information passed by the Policy Framework.
     *

     * This implementation  not need anything out of the configParams
     * I/code> so does no operation.
     *
     * @param configParams configuration parameters as a Map.
     *
     * @exception PolicyException if an error occured during
     * initialization of Subject instance
     */
    public void initialize(Map configParams) throws PolicyException {
	//no op
    }

    /**
     * Returns the syntax of the values the
     * AMIdentitySubject implementation can have.
     * @see com.sun.identity.policy.Syntax
     *
     * @param token the SSOToken that will be used
     * to determine the syntax
     *
     * @return Syntax of the values in this plugin.
     * It returns Syntax.MULTIPLE_CHOICE.
     *
     * @exception SSOException if SSOToken is not valid
     * @exception PolicyException if unable to get the list of
     * valid names.
     *
     * @return Syntax of the values for the Subject
     */
    public Syntax getValueSyntax(SSOToken token) throws SSOException {
        return (Syntax.MULTIPLE_CHOICE);
    }

    /**
     * Returns a list of possible values for the Subject.
     *
     * @param token the SSOToken that will be used
     * to determine the possible values
     *
     * @return ValidValues object
     *
     * @exception SSOException if SSOToken is not valid
     * @exception PolicyException if unable to get the list of valid
     * names.
     * NOTE: The AMIdentitySubject plugin does not support this
     * functionality and in turn throws unsupported
     * PolicyException
     */
    public ValidValues getValidValues(SSOToken token) throws
        SSOException, PolicyException {
        return (getValidValues(token, "*"));
    }

    /**
     * Returns a list of possible values for the Subject
     *  that matches the pattern.
     *
     * @param token the SSOToken that will be used
     * to determine the possible values
     *
     * @return ValidValues object
     *
     * @exception SSOException if SSO token is not valid
     * @exception PolicyException if unable to get the list of valid
     * names.
     * NOTE: The AMIdentitySubject plugin does not support this
     * functionality and in turn throws unsupported
     * PolicyException
     */
    public ValidValues getValidValues(SSOToken token, String pattern)
        throws SSOException, PolicyException {
        throw (new PolicyException(ResBundleUtils.rbName,
            "am_id_subject_does_not_support_getvalidvalues", null, null));
    }

    /**
     * Returns the display name for the value for the given locale.
     * For all the valid values obtained through the methods
     * getValidValues this method must be called
     * by GUI and CLI to get the corresponding display name.
     * The locale variable could be used by the
     * plugin to customize the display name for the given locale.
     * The locale variable could be null,
     * in which case the plugin must use the default locale (most probabily
     * en_US).
     * Alternatively, if the plugin does not have to localize
     * the value, it can just return the value as is.
     *
     * @param value one of the valid value for the plugin
     * @param locale locale for which the display name must be customized
     *
     * @exception NameNotFoundException if the given value
     * is not one of the valid values for the plugin
     */
    public String getDisplayNameForValue(String value, Locale locale)
        throws NameNotFoundException {
        return (value);
    }

    /**
     * Returns the values that was set using the
     * method setValues.
     *
     * @return Set</code of values that have been set for the user
     * collection
     */
    public Set getValues() {
        if (subjectValues == null) {
            return (Collections.EMPTY_SET);
        }
        return (subjectValues);
    }

    /**
     * Sets the values identifying AMIdentity objects on which
     * membership would be checked
     *
     * @param names universalId(s) of AMIdentity
     * objects on which memberships would be checked
     *
     * @exception InvalidNameException if the given names are not valid
     *
     *
     */
    public void setValues(Set names) throws InvalidNameException {
        if (names == null) {
            throw (new InvalidNameException(ResBundleUtils.rbName,
                "amidentity_subject_invalid_subject_values", null, null,
                PolicyException.USER_COLLECTION));
        }
        subjectValues.addAll(names);
        if (debug.messageEnabled()) {
            debug.message("AMIdentitySubejct set subjectValues to: "
                    + subjectValues);
        }
    }

    /**
     * Determines if the user is a member of this instance of the
     * Subject object.
     *
     * @param token single sign on token of the user
     *
     * @return true if the user is member of
     * this subject; false otherwise.
     *
     * @exception SSOException if SSO token is not valid
     * @exception PolicyException if an error occured while
     * checking if the user is a member of this subject
     */
    public boolean isMember(SSOToken token)
            throws SSOException, PolicyException {

        String tokenID = null;
        String userDN = null;
        if (token != null) {
            Object tokenIDObject = token.getTokenID();
            if (tokenIDObject != null) {
                tokenID = tokenIDObject.toString();
            }
        }

        if (tokenID == null) {
            if (debug.warningEnabled()) {
                debug.warning("AMIdentitySubject.isMember():"
                        +"tokenID is null");
                debug.warning("AMIdentitySubject.isMember():"
                        +"returning false");
            }
            return false;
        } else {
            Principal principal = token.getPrincipal();
            if(principal != null) {
                userDN = principal.getName();
            }
            if (userDN == null) {
                if (debug.warningEnabled()) {
                    debug.warning("AMIdentitySubject.isMember():"
                            +"userDN is null");
                    debug.warning("AMIdentitySubject.isMember():"
                            +"returning false");
                }
                return false;
            }
        }

        boolean listenerAdded = false;
        boolean subjectMatch = false;

        if (debug.messageEnabled()) {
            debug.message("AMIndentitySubject.isMember(): "
                    + "entering with userDN = " + userDN);
        }

        if (subjectValues.size() > 0) {
            Iterator valueIter = subjectValues.iterator();
            while (valueIter.hasNext()) {
                Boolean matchFound = null;

                /* Actually this is universal id of AMIdentity object
                 *
                 */
                String subjectValue = (String)valueIter.next();

                if (debug.messageEnabled()) {
                    debug.message("AMIndentitySubject.isMember(): "
                            + "checking membership with userDN = " + userDN
                            + ", subjectValue = " + subjectValue);
                }

                if ((matchFound = SubjectEvaluationCache.isMember(
                        tokenID, "AMIdentitySubject" ,subjectValue)) != null) {
                    if (debug.messageEnabled()) {
                        debug.message("AMIdentitySubject.isMember():"
                                + "got membership from SubjectEvaluationCache "
                                + " for userDN = " + userDN
                                + ", subjectValue = " + subjectValue
                                + ", result = " + matchFound.booleanValue());
                    }
                    boolean result = matchFound.booleanValue();
                    if (result) {
                        if (debug.messageEnabled()) {
                            debug.message("AMIndentitySubject.isMember(): "
                                    + " returning membership status = "
                                    + result);
                        }
                        return result;
                    } else {
                        continue;
                    }
                }

                // got here so entry not in subject evalauation cache
                if (debug.messageEnabled()) {
                    debug.message("AMIdentitySubject:isMember():entry for "
                            + subjectValue + " not in subject evaluation "
                            +"cache, so compute using IDRepo api");
                    }

                try {
                    AMIdentity subjectIdentity = IdUtils.getIdentity(
                            getAdminToken(), subjectValue);
                    if (subjectIdentity == null) {
                        if (debug.messageEnabled()) {
                            debug.message("AMidentitySubject.isMember():"
                                    + "subjectIdentity is null for "
                                    + "subjectValue = " + subjectValue);
                            debug.message("AMidentitySubject.isMember():"
                                    + "returning false");
                        }
                        return false;
                    }

                    AMIdentity tmpIdentity = IdUtils.getIdentity(token);
                    String univId = IdUtils.getUniversalId(tmpIdentity);
                    AMIdentity userIdentity = IdUtils.getIdentity(
                        getAdminToken(), univId);
                    if (userIdentity == null) {
                        if (debug.messageEnabled()) {
                            debug.message("AMidentitySubject.isMember():"
                                    + "userIdentity is null");
                            debug.message("AMidentitySubject.isMember():"
                                    + "returning false");
                        }
                        return false;
                    }

                    if (debug.messageEnabled()) {
                        debug.message("AMidentitySubject.isMember():"
                                + "user uuid = "
                                + IdUtils.getUniversalId( userIdentity)
                                + ", subject uuid = "
                                + IdUtils.getUniversalId(subjectIdentity) );
                    }

                    IdType userIdType = userIdentity.getType();
                    IdType subjectIdType = subjectIdentity.getType();
                    Set allowedMemberTypes = null;
                    if (userIdentity.equals(subjectIdentity)) {
                        if (debug.messageEnabled()) {
                            debug.message("AMidentitySubject.isMember():"
                                    + "userIdentity equals subjectIdentity:"
                                    + "membership=true");
                        }
                        subjectMatch = true;
                    } else if (
                            ((allowedMemberTypes
                            = subjectIdType.canHaveMembers()) != null)
                            && allowedMemberTypes.contains(userIdType)) {
                        subjectMatch = userIdentity.isMember(subjectIdentity);
                        if (debug.messageEnabled()) {
                            debug.message("AMIdentitySubject.isMember():"
                                    + "userIdentity type " + userIdType +
                                    " can be a member of "
                                    + "subjectIdentityType " + subjectIdType
                                    + ":membership=" + subjectMatch);
                        }
                    } else {
                        subjectMatch = false;
                        if (debug.messageEnabled()) {
                            debug.message("AMIdentitySubject.isMember():"
                                    + "userIdentity type " + userIdType +
                                    " can not be a member of "
                                    + "subjectIdentityType " + subjectIdType
                                    + ":membership=" + subjectMatch);
                        }
                    }

                    if (debug.messageEnabled()) {
                        debug.message("AMIdentitySubject.isMember: adding "
                            +"entry in SubjectEvaluationCache for "
                            + ", for userDN = " + userDN
                            + ", subjectValue = " + subjectValue
                            + ", subjectMatch = " + subjectMatch);
                    }
                    SubjectEvaluationCache.addEntry(tokenID,
                        "AMIdentitySubject", subjectValue, subjectMatch);
                    if (!listenerAdded) {
                        if (!PolicyEvaluator.ssoListenerRegistry.containsKey(
                                tokenID)) {
                            token.addSSOTokenListener(
                                PolicyEvaluator.ssoListener);
                            PolicyEvaluator.ssoListenerRegistry.put(
                                    tokenID, PolicyEvaluator.ssoListener);
                            if (debug.messageEnabled()) {
                                debug.message("AMIdentitySubject.isMember():"
                                        + " sso listener added ");
                            }
                            listenerAdded = true;
                        }
                    }
                    if (subjectMatch) {
                        break;
                    }
                } catch (IdRepoException ire) {
                    debug.warning("AMidentitySubject.isMember():"
                            + "can not check membership for user "
                            + userDN + ", subject "
                            + subjectValue, ire);
                    String[] args = {userDN, subjectValue};
                    throw (new PolicyException(ResBundleUtils.rbName,
                        "am_id_subject_membership_evaluation_error", args,
                        ire));
                }
            }
        }
        if (debug.messageEnabled()) {
            if (!subjectMatch) {
                debug.message("AMIdentitySubject.isMember(): user " + userDN
                      + " is not a member of this subject");
            } else {
                debug.message("AMIdentitySubject.isMember(): User " + userDN
                      + " is a member of this subject");
            }
        }
        return subjectMatch;
    }

   /**
    * Return a hash code for this AMIdentitySubject.
    *
    * @return a hash code for this AMIdentitySubject object.
    */

    public int hashCode() {
        return subjectValues.hashCode();
    }

    /**
     * Indicates whether some other object is "equal to" this one.
     *
     * @param o another object that will be compared with this one
     *
     * @return true if eqaul; false
     * otherwise
     */
    public boolean equals(Object o) {
        if (o instanceof AMIdentitySubject) {
            AMIdentitySubject subject = (AMIdentitySubject) o;
            return(subjectValues.equals(subject.subjectValues));
        }
        return (false);
    }

    /**
     * Creates and returns a copy of this object.
     *
     * @return a copy of this object
     */
    public Object clone() {
        AMIdentitySubject theClone = null;
        try {
            theClone = (AMIdentitySubject) super.clone();
        } catch (CloneNotSupportedException e) {
            // this should never happen
            throw new InternalError();
        }
        if (subjectValues != null) {
            theClone.subjectValues = new HashSet();
            theClone.subjectValues.addAll(subjectValues);
        }
        return theClone;
    }

    /**
     * This method returns an admin SSOToken
     * which can be used to perform privileged operations.
     */

    private SSOToken getAdminToken() throws SSOException{
        SSOToken token = (SSOToken) AccessController.doPrivileged(
            AdminTokenAction.getInstance());
        if (token == null) {
            throw (new SSOException(new PolicyException(
                ResBundleUtils.rbName, "invalid_admin", null, null)));
        }
        return (token);
    }

}

{'repo_name': 'OpenRock/OpenAM', 'stars': '136', 'repo_language': 'Java', 'file_name': 'FSAccountManager.java', 'mime_type': 'text/x-java', 'hash': 8150127283075632065, 'source_dataset': 'data'}


#!/bin/bash

# Put your own certificate and private key at /ssl/nginx.crt and /ssl/nginx.key
# respectively on the host to have them picked up by the nginx container.

# The order of `--volumes-from` is important. The last one wins.
#
# `logs`, `data`, `db` are all based on the same image, so they have
# conflicting `VOLUME` declarations.
# - The standard postgres image declares the volume `/var/lib/postgresql/data`.
# - datahuborg/postgres inherits that and adds the volume `/user_data`.
# - The `logs` container below adds volumes for three log directories.
#
# When `db` includes volumes from `logs`, all five of those paths are overlaid
# in place of `db`'s content. Adding `data` last then overlays its content for
# the original two paths.
#
# This is necessary because only the postgres image has a postgres user with a
# logs directory that the user can write to, and the volume to the postgres
# data path is declared in the base postgres image, so having one requires the
# other.

if (( EUID != 0 )); then
   echo "Script must be run as root."
   exit 126
fi

echo "Creating \"datahub_dev\" Docker network if needed..."
docker network create datahub_dev 2> /dev/null

echo "Creating Docker containers..."
echo "(1/6) Creating \"logs\" - Data container for all server logs"
docker create --name logs \
    -v /var/log/postgresql \
    -v /var/log/gunicorn \
    -v /var/log/nginx \
    --entrypoint /bin/true \
    datahuborg/postgres
echo "(2/6) Creating \"data\" - Data container for Postgres db and user_data uploads"
docker create --name data \
    --entrypoint /bin/true \
    datahuborg/postgres
echo "(3/6) Creating \"db\" - Postgres server"
docker create --name db \
    --volumes-from logs \
    --volumes-from data \
    --net=datahub_dev \
    datahuborg/postgres
echo "(4/6) Creating \"app\" - gunicorn server hosting DataHub"
docker create --name app \
    --env 'USER=vagrant' \
    --volumes-from logs \
    --volumes-from data \
    --net=datahub_dev \
    -v /vagrant:/datahub \
    datahuborg/datahub
    # gunicorn browser.wsgi --config=provisions/gunicorn/config_dev.py
echo "(5/6) Creating \"web\" - nginx http proxy"
docker create --name web \
    --volumes-from logs \
    --volumes-from app \
    -v /ssl/:/etc/nginx/ssl/ \
    --net=datahub_dev \
    -p 80:80 -p 443:443 \
    datahuborg/nginx
echo "(6/6) Creating \"phantomjs\" - PhantomJS remote web driver for Selenium tests"
docker create --name phantomjs \
    --env 'USER=vagrant' \
    --net=datahub_dev \
    wernight/phantomjs \
    phantomjs --webdriver=8910
echo "Done."

{'repo_name': 'datahuborg/datahub', 'stars': '201', 'repo_language': 'JavaScript', 'file_name': 'output.txt', 'mime_type': 'text/plain', 'hash': 3051781634823641142, 'source_dataset': 'data'}


/*
* Copyright (c) 2015 Cossack Labs Limited
*
* 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.
*/

#import <objcthemis/ssession.h>
#import <objcthemis/serror.h>
#import <themis/themis.h>

@interface TSSession ()

@property(nonatomic) secure_session_t *session;

@end

@implementation TSSession

- (nullable instancetype)initWithUserId:(NSData *)userId
                             privateKey:(NSData *)privateKey
                              callbacks:(TSSessionTransportInterface *)callbacks {
    self = [super init];
    if (self) {
        self.session = secure_session_create([userId bytes], [userId length],
                [privateKey bytes], [privateKey length], [callbacks callbacks]);
        if (!self.session) {
            return nil;
        }
    }
    return self;
}

- (BOOL)connect:(NSError *__autoreleasing *)error {
    TSErrorType result = (TSErrorType) secure_session_connect(self.session);
    if (result != TSErrorTypeSuccess) {
        if (error) {
            *error = SCERROR(result, @"Secure Session failed connection");
        }
        return NO;
    }
    return YES;
}

- (nullable NSData *)connectRequest:(NSError *__autoreleasing *)error {
    size_t connectRequestLength = 0;
    TSErrorType result = (TSErrorType) secure_session_generate_connect_request(self.session, NULL, &connectRequestLength);

    if (result != TSErrorTypeBufferTooSmall) {
        if (error) {
            *error = SCERROR(result, @"Secure Session failed making connection request");
        }
        return nil;
    }

    NSMutableData *requestData = [[NSMutableData alloc] initWithLength:connectRequestLength];
    result = (TSErrorType) secure_session_generate_connect_request(self.session, [requestData mutableBytes], &connectRequestLength);

    if (result != TSErrorTypeSuccess) {
        if (error) {
            *error = SCERROR(result, @"Secure Session failed making connection request");
        }
        return nil;
    }
    return [requestData copy];
}

- (nullable NSData *)wrapData:(nullable NSData *)message error:(NSError *__autoreleasing *)error {
    size_t wrappedMessageLength = 0;

    TSErrorType result = (TSErrorType) secure_session_wrap(self.session, [message bytes], [message length],
            NULL, &wrappedMessageLength);

    if (result != TSErrorTypeBufferTooSmall) {
        if (error) {
            *error = SCERROR(result, @"Secure Session failed encryption");
        }
        return nil;
    }

    NSMutableData *wrappedMessage = [[NSMutableData alloc] initWithLength:wrappedMessageLength];
    result = (TSErrorType) secure_session_wrap(self.session, [message bytes], [message length],
            [wrappedMessage mutableBytes], &wrappedMessageLength);

    if (result != TSErrorTypeSuccess) {
        if (error) {
            *error = SCERROR(result, @"Secure Session failed encryption");
        }
        return nil;
    }
    return [wrappedMessage copy];
}

- (nullable NSData *)unwrapData:(nullable NSData *)message error:(NSError *__autoreleasing *)error {
    size_t unwrappedMessageLength = 0;
    TSErrorType result = (TSErrorType) secure_session_unwrap(self.session, [message bytes], [message length],
            NULL, &unwrappedMessageLength);

    if (result != TSErrorTypeBufferTooSmall) {
        if (result == TSErrorTypeSuccess) {
            return nil; // TODO: This is really strange! Success and returning nil???
        }
        if (error) {
            *error = SCERROR(result, @"Secure Session failed decryption");
        }
        return nil;
    }

    NSMutableData *unwrappedMessage = [[NSMutableData alloc] initWithLength:unwrappedMessageLength];
    result = (TSErrorType) secure_session_unwrap(self.session, [message bytes], [message length],
            [unwrappedMessage mutableBytes], &unwrappedMessageLength);

    if (result != TSErrorTypeSuccess) {
        if (result == TSErrorTypeSendAsIs) {
            return unwrappedMessage;
        } else {
            if (error) {
                *error = SCERROR(result, @"Secure Session failed decryption");
            }
            return nil;
        }
    }

    return [unwrappedMessage copy];
}

- (BOOL)wrapAndSend:(nullable NSData *)message error:(NSError *__autoreleasing *)error {
    TSErrorType result = (TSErrorType) secure_session_send(self.session, [message bytes], [message length]);
    if (result != TSErrorTypeSuccess) {
        if (error) {
            *error = SCERROR(result, @"Secure Session failed sending");
        }
        return NO;
    }
    return YES;
}

- (nullable NSData *)unwrapAndReceive:(NSUInteger)length error:(NSError *__autoreleasing *)error {
    NSMutableData *receivedData = [[NSMutableData alloc] initWithLength:length];
    TSErrorType result = (TSErrorType) secure_session_receive(self.session, [receivedData mutableBytes],
            [receivedData length]);

    if (result != TSErrorTypeSuccess) {
        if (error) {
            *error = SCERROR(result, @"Secure Session failed receiving");
        }
        return nil;
    }
    return [receivedData copy];
}

- (BOOL)isSessionEstablished {
    return secure_session_is_established(self.session);
}

@end

{'repo_name': 'cossacklabs/themis', 'stars': '1067', 'repo_language': 'C', 'file_name': 'AndroidManifest.xml', 'mime_type': 'text/xml', 'hash': -2799970154057231412, 'source_dataset': 'data'}


// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

namespace Microsoft.Quantum.Simulation.QuantumProcessor.Extensions {
    operation ApplyIfZero<'T>(measurementResult : Result, (onResultZeroOp : ('T => Unit), zeroArg : 'T)) : Unit { }
    operation ApplyIfZeroA<'T>(measurementResult : Result, (onResultZeroOp : ('T => Unit is Adj), zeroArg : 'T)) : Unit is Adj { }
    operation ApplyIfZeroC<'T>(measurementResult : Result, (onResultZeroOp : ('T => Unit is Ctl), zeroArg : 'T)) : Unit is Ctl { }
    operation ApplyIfZeroCA<'T>(measurementResult : Result, (onResultZeroOp : ('T => Unit is Ctl + Adj), zeroArg : 'T)) : Unit is Ctl + Adj { }

    operation ApplyIfOne<'T>(measurementResult : Result, (onResultOneOp : ('T => Unit), oneArg : 'T)) : Unit { }
    operation ApplyIfOneA<'T>(measurementResult : Result, (onResultOneOp : ('T => Unit is Adj), oneArg : 'T)) : Unit is Adj { }
    operation ApplyIfOneC<'T>(measurementResult : Result, (onResultOneOp : ('T => Unit is Ctl), oneArg : 'T)) : Unit is Ctl { }
    operation ApplyIfOneCA<'T>(measurementResult : Result, (onResultOneOp : ('T => Unit is Ctl + Adj), oneArg : 'T)) : Unit is Ctl + Adj { }

    operation ApplyIfElseR<'T,'U>(measurementResult : Result, (onResultZeroOp : ('T => Unit), zeroArg : 'T) , (onResultOneOp : ('U => Unit), oneArg : 'U)) : Unit { }
    operation ApplyIfElseRA<'T,'U>(measurementResult : Result, (onResultZeroOp : ('T => Unit is Adj), zeroArg : 'T) , (onResultOneOp : ('U => Unit is Adj), oneArg : 'U)) : Unit is Adj { }
    operation ApplyIfElseRC<'T,'U>(measurementResult : Result, (onResultZeroOp : ('T => Unit is Ctl), zeroArg : 'T) , (onResultOneOp : ('U => Unit is Ctl), oneArg : 'U)) : Unit is Ctl { }
    operation ApplyIfElseRCA<'T,'U>(measurementResult : Result, (onResultZeroOp : ('T => Unit is Adj + Ctl), zeroArg : 'T) , (onResultOneOp : ('U => Unit is Adj + Ctl), oneArg : 'U)) : Unit is Ctl + Adj { }

    operation ApplyConditionally<'T,'U>(measurementResults : Result[], resultsValues : Result[], (onEqualOp : ('T => Unit), equalArg : 'T) , (onNonEqualOp : ('U => Unit), nonEqualArg : 'U)) : Unit { }
    operation ApplyConditionallyA<'T,'U>(measurementResults : Result[], resultsValues : Result[], (onEqualOp : ('T => Unit is Adj), equalArg : 'T) , (onNonEqualOp : ('U => Unit is Adj), nonEqualArg : 'U)) : Unit is Adj { }
    operation ApplyConditionallyC<'T,'U>(measurementResults : Result[], resultsValues : Result[], (onEqualOp : ('T => Unit is Ctl), equalArg : 'T) , (onNonEqualOp : ('U => Unit is Ctl), nonEqualArg : 'U)) : Unit is Ctl { }
    operation ApplyConditionallyCA<'T,'U>(measurementResults : Result[], resultsValues : Result[], (onEqualOp : ('T => Unit is Ctl + Adj), equalArg : 'T) , (onNonEqualOp : ('U => Unit is Ctl + Adj), nonEqualArg : 'U)) : Unit is Ctl + Adj { }
}

namespace SubOps {
    operation SubOp1() : Unit { }
    operation SubOp2() : Unit { }
    operation SubOp3() : Unit { }

    operation SubOpCA1() : Unit is Ctl + Adj { }
    operation SubOpCA2() : Unit is Ctl + Adj { }
    operation SubOpCA3() : Unit is Ctl + Adj { }
}

// =================================

// Basic Lift
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            SubOp1();
            SubOp2();
            SubOp3();
            let temp = 4;
            using (q = Qubit()) {
                let temp2 = q;
            }
        }
    }
}

// =================================

// Lift Loops
namespace Microsoft.Quantum.Testing.ClassicalControl {

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            for (index in 0 .. 3) {
                let temp = index;
            }

            repeat {
                let success = true;
            } until (success)
            fixup {
                let temp2 = 0;
            }
        }
    }
}

// =================================

// Don't Lift Single Call
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;
        if (r == Zero) {
            SubOp1();
        }
    }
}

// =================================

// Lift Single Non-Call
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            let temp = 2;
        }
    }
}

// =================================

// Don't Lift Return Statements
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;
        if (r == Zero) {
            SubOp1();
            return ();
        }
    }
}

// =================================

// All-Or-None Lifting
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation IfInvalid() : Unit {
        let r = Zero;
        if (r == Zero) {
            SubOp1();
            SubOp2();
            return ();
        } else {
            SubOp2();
            SubOp3();
        }
    }

    operation ElseInvalid() : Unit {
        let r = Zero;
        if (r == Zero) {
            SubOp1();
            SubOp2();
        } else {
            SubOp2();
            SubOp3();
            return ();
        }
    }

    operation BothInvalid() : Unit {
        let r = Zero;
        if (r == Zero) {
            SubOp1();
            SubOp2();
            return ();
        } else {
            SubOp2();
            SubOp3();
            return ();
        }
    }
}

// =================================

// ApplyIfZero And ApplyIfOne
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            SubOp1();
        }

        let temp = 0;

        if (r == One) {
            SubOp2();
        }
    }
}

// =================================

// Apply If Zero Else One
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Bar(r : Result) : Unit { }

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            Bar(r);
        } else {
            SubOp1();
        }
    }
}

// =================================

// Apply If One Else Zero
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Bar(r : Result) : Unit { }

    operation Foo() : Unit {
        let r = One;

        if (r == One) {
            Bar(r);
        } else {
            SubOp1();
        }
    }
}

// =================================

// If Elif
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            SubOp1();
        } elif (r == One) {
            SubOp2();
        } else {
            SubOp3();
        }
    }
}

// =================================

// And Condition
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero and r == One) {
            SubOp1();
        } else {
            SubOp2();
        }
    }
}

// =================================

// Or Condition
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero or r == One) {
            SubOp1();
        } else {
            SubOp2();
        }
    }
}

// =================================

// Don't Lift Functions
namespace Microsoft.Quantum.Testing.ClassicalControl {

    function Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            SubFunc1();
            SubFunc2();
            SubFunc3();
        }
    }

    function SubFunc1() : Unit { }
    function SubFunc2() : Unit { }
    function SubFunc3() : Unit { }
}

// =================================

// Lift Self-Contained Mutable
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r == Zero) {
            mutable temp = 3;
            set temp = 4;
        }
    }
}

// =================================

// Don't Lift General Mutable
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        mutable temp = 3;
        if (r == Zero) {
            set temp = 4;
        }
    }
}

// =================================

// Generics Support
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo<'A, 'B, 'C>() : Unit {
        let r = Zero;

        if (r == Zero) {
            SubOp1();
            SubOp2();
        }
    }
}

// =================================

// Adjoint Support
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Provided() : Unit is Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        adjoint (...) {
            let w = One;

            if (w == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }
    }

    operation Self() : Unit is Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        adjoint self;
    }

    operation Invert() : Unit is Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        adjoint invert;
    }
}

// =================================

// Controlled Support
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Provided() : Unit is Ctl {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }
    }

    operation Distribute() : Unit is Ctl {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled distribute;
    }
}

// =================================

// Controlled Adjoint Support - Provided
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation ProvidedBody() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled adjoint (ctl, ...) {
            let y = One;

            if (y == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }
    }

    operation ProvidedAdjoint() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        adjoint (...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        controlled adjoint (ctl, ...) {
            let y = One;

            if (y == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }
    }

    operation ProvidedControlled() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        controlled adjoint (ctl, ...) {
            let y = One;

            if (y == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }
    }

    operation ProvidedAll() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        adjoint (...) {
            let y = One;

            if (y == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }

        controlled adjoint (ctl, ...) {
            let b = One;

            if (b == One) {
                let temp1 = 0;
                let temp2 = 0;
                SubOpCA3();
            }
        }
    }
}

// =================================

// Controlled Adjoint Support - Distribute
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation DistributeBody() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled adjoint distribute;
    }

    operation DistributeAdjoint() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        adjoint (...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        controlled adjoint distribute;
    }

    operation DistributeControlled() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        controlled adjoint distribute;
    }

    operation DistributeAll() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        adjoint (...) {
            let y = One;

            if (y == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }

        controlled adjoint distribute;
    }
}

// =================================

// Controlled Adjoint Support - Invert
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation InvertBody() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled adjoint invert;
    }

    operation InvertAdjoint() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        adjoint (...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        controlled adjoint invert;
    }

    operation InvertControlled() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        controlled adjoint invert;
    }

    operation InvertAll() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        adjoint (...) {
            let y = One;

            if (y == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }

        controlled adjoint invert;
    }
}

// =================================

// Controlled Adjoint Support - Self
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation SelfBody() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled adjoint self;
    }

    operation SelfControlled() : Unit is Ctl + Adj {
        body (...) {
            let r = Zero;

            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        }

        controlled (ctl, ...) {
            let w = One;

            if (w == One) {
                SubOpCA3();
                SubOpCA1();
            }
        }

        controlled adjoint self;
    }
}

// =================================

// Within Block Support
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = One;
        within {
            if (r == Zero) {
                SubOpCA1();
                SubOpCA2();
            }
        } apply {
            if (r == One) {
                SubOpCA2();
                SubOpCA3();
            }
        }
    }
}

// =================================

// Arguments Partially Resolve Type Parameters
namespace Microsoft.Quantum.Testing.ClassicalControl {

    operation Bar<'Q, 'W> (q : 'Q, w : 'W) : Unit { }

    operation Foo() : Unit {
        let r = Zero;
        if (r == Zero) {
            Bar<Int, _>(1, 1.0);
        }
    }
}

// =================================

// Lift Functor Application
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;
        if (r == Zero) {
            Adjoint SubOpCA1();
        }
    }
}

// =================================

// Lift Partial Application
namespace Microsoft.Quantum.Testing.ClassicalControl {

    operation Bar (q : Int, w : Double) : Unit { }

    operation Foo() : Unit {
        let r = Zero;
        if (r == Zero) {
            (Bar(1, _))(1.0);
        }
    }
}

// =================================

// Lift Array Item Call
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let f = [SubOp1];
        let r = Zero;
        if (r == Zero) {
            f[0]();
        }
    }
}

// =================================

// Lift One Not Both
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;
        if (r == Zero) {
            SubOp1();
            SubOp2();
        }
        else {
            SubOp3();
        }
    }
}

// =================================

// Apply Conditionally
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Bar(r : Result) : Unit { }

    operation Foo() : Unit {
        let r1 = Zero;
        let r2 = Zero;

        if (r1 == r2) {
            Bar(r1);
        }
        else {
            SubOp1();
        }
    }
}

// =================================

// Apply Conditionally With NoOp
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Bar(r : Result) : Unit { }

    operation Foo() : Unit {
        let r1 = Zero;
        let r2 = Zero;

        if (r1 == r2) {
            Bar(r1);
        }
    }
}

// =================================

// Inequality with ApplyConditionally
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Bar(r : Result) : Unit { }

    operation Foo() : Unit {
        let r1 = Zero;
        let r2 = Zero;

        if (r1 != r2) {
            Bar(r1);
        }
        else {
            SubOp1();
        }
    }
}

// =================================

// Inequality with Apply If One Else Zero
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Bar(r : Result) : Unit { }

    operation Foo() : Unit {
        let r = Zero;

        if (r != Zero) {
            Bar(r);
        }
        else {
            SubOp1();
        }
    }
}

// =================================

// Inequality with Apply If Zero Else One
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Bar(r : Result) : Unit { }

    operation Foo() : Unit {
        let r = Zero;

        if (r != One) {
            Bar(r);
        }
        else {
            SubOp1();
        }
    }
}

// =================================

// Inequality with ApplyIfOne
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r != Zero) {
            SubOp1();
        }
    }
}

// =================================

// Inequality with ApplyIfZero
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (r != One) {
            SubOp1();
        }
    }
}

// =================================

// Literal on the Left
namespace Microsoft.Quantum.Testing.ClassicalControl {
    open SubOps;

    operation Foo() : Unit {
        let r = Zero;

        if (Zero == r) {
            SubOp1();
        }
    }
}

{'repo_name': 'microsoft/qsharp-compiler', 'stars': '358', 'repo_language': 'C#', 'file_name': 'extensions.json', 'mime_type': 'text/plain', 'hash': -1651831095542857746, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <WorkflowKit/WFVariableSubstitutableParameterState.h>

@interface WFLocationParameterState : WFVariableSubstitutableParameterState
{
}

+ (id)serializedRepresentationFromValue:(id)arg1;
+ (id)valueFromSerializedRepresentation:(id)arg1 variableProvider:(id)arg2 parameter:(id)arg3;
+ (Class)processingValueClass;
- (void)getContentItemFromValue:(id)arg1 withContext:(id)arg2 completionHandler:(CDUnknownBlockType)arg3;
- (void)getContentCollectionWithContext:(id)arg1 completionHandler:(CDUnknownBlockType)arg2;
- (void)processWithContext:(id)arg1 userInputRequiredHandler:(CDUnknownBlockType)arg2 valueHandler:(CDUnknownBlockType)arg3;
- (id)initWithValue:(id)arg1;

@end

{'repo_name': 'LeoNatan/Apple-Runtime-Headers', 'stars': '131', 'repo_language': 'None', 'file_name': 'CDStructures.h', 'mime_type': 'text/x-c', 'hash': 4893948084938065724, 'source_dataset': 'data'}


import $ from 'jquery';
import ParsleyUtils from './utils';

var requirementConverters = {
  string: function(string) {
    return string;
  },
  integer: function(string) {
    if (isNaN(string))
      throw 'Requirement is not an integer: "' + string + '"';
    return parseInt(string, 10);
  },
  number: function(string) {
    if (isNaN(string))
      throw 'Requirement is not a number: "' + string + '"';
    return parseFloat(string);
  },
  reference: function(string) { // Unused for now
    var result = $(string);
    if (result.length === 0)
      throw 'No such reference: "' + string + '"';
    return result;
  },
  boolean: function(string) {
    return string !== 'false';
  },
  object: function(string) {
    return ParsleyUtils.deserializeValue(string);
  },
  regexp: function(regexp) {
    var flags = '';

    // Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
    if (/^\/.*\/(?:[gimy]*)$/.test(regexp)) {
      // Replace the regexp literal string with the first match group: ([gimy]*)
      // If no flag is present, this will be a blank string
      flags = regexp.replace(/.*\/([gimy]*)$/, '$1');
      // Again, replace the regexp literal string with the first match group:
      // everything excluding the opening and closing slashes and the flags
      regexp = regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
    } else {
      // Anchor regexp:
      regexp = '^' + regexp + '$';
    }
    return new RegExp(regexp, flags);
  }
};

var convertArrayRequirement = function(string, length) {
  var m = string.match(/^\s*\[(.*)\]\s*$/);
  if (!m)
    throw 'Requirement is not an array: "' + string + '"';
  var values = m[1].split(',').map(ParsleyUtils.trimString);
  if (values.length !== length)
    throw 'Requirement has ' + values.length + ' values when ' + length + ' are needed';
  return values;
};

var convertRequirement = function(requirementType, string) {
  var converter = requirementConverters[requirementType || 'string'];
  if (!converter)
    throw 'Unknown requirement specification: "' + requirementType + '"';
  return converter(string);
};

var convertExtraOptionRequirement = function(requirementSpec, string, extraOptionReader) {
  var main = null;
  var extra = {};
  for (var key in requirementSpec) {
    if (key) {
      var value = extraOptionReader(key);
      if ('string' === typeof value)
        value = convertRequirement(requirementSpec[key], value);
      extra[key] = value;
    } else {
      main = convertRequirement(requirementSpec[key], string);
    }
  }
  return [main, extra];
};

// A Validator needs to implement the methods `validate` and `parseRequirements`

var ParsleyValidator = function(spec) {
  $.extend(true, this, spec);
};

ParsleyValidator.prototype = {
  // Returns `true` iff the given `value` is valid according the given requirements.
  validate: function(value, requirementFirstArg) {
    if (this.fn) { // Legacy style validator

      if (arguments.length > 3)  // If more args then value, requirement, instance...
        requirementFirstArg = [].slice.call(arguments, 1, -1);  // Skip first arg (value) and last (instance), combining the rest
      return this.fn.call(this, value, requirementFirstArg);
    }

    if ($.isArray(value)) {
      if (!this.validateMultiple)
        throw 'Validator `' + this.name + '` does not handle multiple values';
      return this.validateMultiple(...arguments);
    } else {
      if (this.validateNumber) {
        if (isNaN(value))
          return false;
        arguments[0] = parseFloat(arguments[0]);
        return this.validateNumber(...arguments);
      }
      if (this.validateString) {
        return this.validateString(...arguments);
      }
      throw 'Validator `' + this.name + '` only handles multiple values';
    }
  },

  // Parses `requirements` into an array of arguments,
  // according to `this.requirementType`
  parseRequirements: function(requirements, extraOptionReader) {
    if ('string' !== typeof requirements) {
      // Assume requirement already parsed
      // but make sure we return an array
      return $.isArray(requirements) ? requirements : [requirements];
    }
    var type = this.requirementType;
    if ($.isArray(type)) {
      var values = convertArrayRequirement(requirements, type.length);
      for (var i = 0; i < values.length; i++)
        values[i] = convertRequirement(type[i], values[i]);
      return values;
    } else if ($.isPlainObject(type)) {
      return convertExtraOptionRequirement(type, requirements, extraOptionReader);
    } else {
      return [convertRequirement(type, requirements)];
    }
  },
  // Defaults:
  requirementType: 'string',

  priority: 2

};

export default ParsleyValidator;

{'repo_name': 'ant4g0nist/vegvisir', 'stars': '177', 'repo_language': 'JavaScript', 'file_name': 'apis.js', 'mime_type': 'text/html', 'hash': -1652953326657711006, 'source_dataset': 'data'}


# Determine MATLAB library path and provide facilities to load libraries with
# this path

function matlab_homepath()
    matlab_home = get(ENV, "MATLAB_HOME", "")
    if isempty(matlab_home)
        if islinux()
            matlab_home = dirname(dirname(realpath(chomp(read(`which matlab`, String)))))
        elseif isapple()
            default_dir = "/Applications"
            if isdir(default_dir)
                dirs = readdir(default_dir)
                filter!(app -> occursin(r"^MATLAB_R[0-9]+[ab]\.app$", app), dirs)
                if !isempty(dirs)
                    matlab_home = joinpath(default_dir, maximum(dirs))
                end
            end
        elseif iswindows()
            default_dir = Sys.WORD_SIZE == 32 ? "C:\\Program Files (x86)\\MATLAB" : "C:\\Program Files\\MATLAB"
            if isdir(default_dir)
                dirs = readdir(default_dir)
                filter!(dir -> occursin(r"^R[0-9]+[ab]$", dir), dirs)
                if !isempty(dirs)
                    matlab_home = joinpath(default_dir, maximum(dirs))
                end
            end
        end
    end
    if isempty(matlab_home)
        error("The MATLAB path could not be found. Set the MATLAB_HOME environmental variable to specify the MATLAB path.")
    end
    return matlab_home
end

function matlab_libpath()
    # get path to MATLAB libraries
    matlab_home = matlab_homepath()
    matlab_lib_dir = if islinux()
        Sys.WORD_SIZE == 32 ? "glnx86" : "glnxa64"
    elseif isapple()
        Sys.WORD_SIZE == 32 ? "maci" : "maci64"
    elseif iswindows()
        Sys.WORD_SIZE == 32 ? "win32" : "win64"
    end
    matlab_libpath = joinpath(matlab_home, "bin", matlab_lib_dir)
    if !isdir(matlab_libpath)
        error("The MATLAB library path could not be found.")
    end
    return matlab_libpath
end

function matlab_cmd()
    matlab_home = matlab_homepath()
    if !iswindows()
        matlab_cmd = joinpath(matlab_home, "bin", "matlab")
        if !isfile(matlab_cmd)
            error("The MATLAB path is invalid. Set the MATLAB_HOME evironmental variable to the MATLAB root.")
        end
        matlab_cmd = "exec $(Base.shell_escape(matlab_cmd))"
    elseif iswindows()
        matlab_cmd = joinpath(matlab_home, "bin", (Sys.WORD_SIZE == 32 ? "win32" : "win64"), "MATLAB.exe")
        if !isfile(matlab_cmd)
            error("The MATLAB path is invalid. Set the MATLAB_HOME evironmental variable to the MATLAB root.")
        end
    end
    return matlab_cmd
end

# helper library access function

engfunc(fun::Symbol) = Libdl.dlsym(libeng[], fun)
mxfunc(fun::Symbol)  = Libdl.dlsym(libmx[], fun)
matfunc(fun::Symbol) = Libdl.dlsym(libmat[], fun)

{'repo_name': 'JuliaInterop/MATLAB.jl', 'stars': '139', 'repo_language': 'Julia', 'file_name': 'matfile.jl', 'mime_type': 'text/x-c', 'hash': 7334188203143708005, 'source_dataset': 'data'}


/*
 * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package javax.swing.plaf.synth;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.swing.JComponent;

/**
 * An immutable transient object containing contextual information about
 * a Region. A SynthContext should only be
 * considered valid for the duration
 * of the method it is passed to. In other words you should not cache
 * a SynthContext that is passed to you and expect it to
 * remain valid.
 *
 * @since 1.5
 * @author Scott Violet
 */
public class SynthContext {
    private static final Queue<SynthContext> queue = new ConcurrentLinkedQueue<>();

    private JComponent component;
    private Region region;
    private SynthStyle style;
    private int state;

    static SynthContext getContext(JComponent c, SynthStyle style, int state) {
        return getContext(c, SynthLookAndFeel.getRegion(c), style, state);
    }

    static SynthContext getContext(JComponent component,
                                   Region region, SynthStyle style,
                                   int state) {
        SynthContext context = queue.poll();
        if (context == null) {
            context = new SynthContext();
        }
        context.reset(component, region, style, state);
        return context;
    }

    static void releaseContext(SynthContext context) {
        queue.offer(context);
    }

    SynthContext() {
    }

    /**
     * Creates a SynthContext with the specified values. This is meant
     * for subclasses and custom UI implementors. You very rarely need to
     * construct a SynthContext, though some methods will take one.
     *
     * @param component JComponent
     * @param region Identifies the portion of the JComponent
     * @param style Style associated with the component
     * @param state State of the component as defined in SynthConstants.
     * @throws NullPointerException if component, region of style is null.
     */
    public SynthContext(JComponent component, Region region, SynthStyle style,
                        int state) {
        if (component == null || region == null || style == null) {
            throw new NullPointerException(
                "You must supply a non-null component, region and style");
        }
        reset(component, region, style, state);
    }

    /**
     * Returns the hosting component containing the region.
     *
     * @return Hosting Component
     */
    public JComponent getComponent() {
        return component;
    }

    /**
     * Returns the Region identifying this state.
     *
     * @return Region of the hosting component
     */
    public Region getRegion() {
        return region;
    }

    /**
     * A convenience method for getRegion().isSubregion().
     */
    boolean isSubregion() {
        return getRegion().isSubregion();
    }

    void setStyle(SynthStyle style) {
        this.style = style;
    }

    /**
     * Returns the style associated with this Region.
     *
     * @return SynthStyle associated with the region.
     */
    public SynthStyle getStyle() {
        return style;
    }

    void setComponentState(int state) {
        this.state = state;
    }

    /**
     * Returns the state of the widget, which is a bitmask of the
     * values defined in SynthConstants. A region will at least
     * be in one of
     * ENABLED, MOUSE_OVER, PRESSED
     * or DISABLED.
     *
     * @see SynthConstants
     * @return State of Component
     */
    public int getComponentState() {
        return state;
    }

    /**
     * Resets the state of the Context.
     */
    void reset(JComponent component, Region region, SynthStyle style,
               int state) {
        this.component = component;
        this.region = region;
        this.style = style;
        this.state = state;
    }

    void dispose() {
        this.component = null;
        this.style = null;
        releaseContext(this);
    }

    /**
     * Convenience method to get the Painter from the current SynthStyle.
     * This will NEVER return null.
     */
    SynthPainter getPainter() {
        SynthPainter painter = getStyle().getPainter(this);

        if (painter != null) {
            return painter;
        }
        return SynthPainter.NULL_PAINTER;
    }
}

{'repo_name': 'JetBrains/jdk8u_jdk', 'stars': '147', 'repo_language': 'Java', 'file_name': 'MacOSXNativeDispatcher.java', 'mime_type': 'text/x-java', 'hash': -2315925970249026845, 'source_dataset': 'data'}


/*
 * See the dyninst/COPYRIGHT file for copyright information.
 *
 * We provide the Paradyn Tools (below described as "Paradyn")
 * on an AS IS basis, and do not warrant its validity or performance.
 * We reserve the right to update, modify, or discontinue this
 * software at any time.  We shall have no obligation to supply such
 * updates or modifications or any other form of support to you.
 *
 * By your use of Paradyn, you understand and agree that we (or any
 * other person or entity with proprietary rights in Paradyn) are
 * under no obligation to provide either maintenance services,
 * update services, notices of latent defects, or correction of
 * defects for Paradyn.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "stackwalk/h/framestepper.h"
#include "stackwalk/h/frame.h"
#include "stackwalk/h/procstate.h"
#include "stackwalk/h/swk_errors.h"
#include "stackwalk/h/steppergroup.h"
#include "stackwalk/h/walker.h"
#include "stackwalk/src/dbgstepper-impl.h"
#include "stackwalk/src/linuxbsd-swk.h"
#include "stackwalk/src/libstate.h"
#include "common/h/dyntypes.h"
#include "common/h/VariableLocation.h"
#include "common/src/Types.h"
#include "dwarfFrameParser.h"
#include "dwarfHandle.h"

#if defined(WITH_SYMTAB_API)
#include "symtabAPI/h/Symtab.h"
#endif

using namespace Dyninst;
using namespace Stackwalker;
using namespace DwarfDyninst;

static std::map<std::string, DwarfFrameParser::Ptr> dwarf_info;

#include <sys/ucontext.h>
#include <stdarg.h>
#include "dwarf.h"
#include "elfutils/libdw.h"
#include "Elf_X.h"

static DwarfFrameParser::Ptr getAuxDwarfInfo(std::string s)
{
   static std::map<std::string, DwarfFrameParser::Ptr > dwarf_aux_info;

   std::map<std::string, DwarfFrameParser::Ptr >::iterator i = dwarf_aux_info.find(s);
   if (i != dwarf_aux_info.end())
      return i->second;

   SymReader *orig_reader = LibraryWrapper::getLibrary(s);
   if (!orig_reader) {
      sw_printf("[%s:%u] - Error.  Could not find elf handle for %s\n",
                FILE__, __LINE__, s.c_str());
      return DwarfFrameParser::Ptr();
   }
   Elf_X *orig_elf = (Elf_X *) orig_reader->getElfHandle();
   if (!orig_elf) {
      sw_printf("[%s:%u] - Error. Could not find elf handle for file %s\n",
                FILE__, __LINE__, s.c_str());
      dwarf_aux_info[s] = DwarfFrameParser::Ptr();
      return DwarfFrameParser::Ptr();
   }

   DwarfHandle::ptr dwarf = DwarfHandle::createDwarfHandle(s, orig_elf);
   assert(dwarf);
   sw_printf("[%s:%u] - Separate debug file used: %s\n",
           FILE__, __LINE__, dwarf->getDebugFilename().c_str());

   // MJMTODO - Need to check whether this is supposed to work or not
   // FIXME for ppc, if we ever support debug walking on ppc
   Architecture arch;
#if defined(arch_x86) || defined(arch_x86_64)
   if (orig_elf->wordSize() == 4)
      arch = Dyninst::Arch_x86;
   else
      arch = Dyninst::Arch_x86_64;
#elif defined(arch_aarch64)
    arch = Dyninst::Arch_aarch64;
#endif

   DwarfFrameParser::Ptr dresult = DwarfFrameParser::create(*dwarf->frame_dbg(), dwarf->origFile()->e_elfp(), arch);
   if(!dresult) return NULL;
   dwarf_aux_info[s] = dresult;
   return dresult;
}

DebugStepperImpl::DebugStepperImpl(Walker *w, DebugStepper *parent) :
   FrameStepper(w),
   last_addr_read(0),
   last_val_read(0),
   addr_width(0),
   parent_stepper(parent),
   cur_frame(NULL),
   depth_frame(NULL)
{
}

bool DebugStepperImpl::ReadMem(Address addr, void *buffer, unsigned size)
{
   bool result = getProcessState()->readMem(buffer, addr, size);

   last_addr_read = 0;
   if (!result)
      return false;
   if (size != addr_width)
      return false;

   last_addr_read = addr;
   if (addr_width == 4) {
      uint32_t v = *((uint32_t *) buffer);
      last_val_read = v;
   }
   else if (addr_width == 8) {
      uint64_t v = *((uint64_t *) buffer);
      last_val_read = v;
   }
   else {
      assert(0); //Unknown size
   }

   return true;
}

location_t DebugStepperImpl::getLastComputedLocation(unsigned long value)
{
   location_t loc;
   if (last_addr_read && last_val_read == value) {
      loc.val.addr = last_addr_read;
      loc.location = loc_address;
   }
   else {
      loc.val.addr = 0;
      loc.location = loc_unknown;
   }
   last_addr_read = 0;
   last_val_read = 0;
   return loc;
}

bool DebugStepperImpl::GetReg(MachRegister reg, MachRegisterVal &val)
{
   sw_printf("[%s:%u] Attempt to get value for reg %s\n", FILE__, __LINE__, reg.name().c_str());
   if (reg.isFramePointer()) {
      val = static_cast<MachRegisterVal>(depth_frame->getFP());
      return true;
   }

   if (reg.isStackPointer()) {
      val = static_cast<MachRegisterVal>(depth_frame->getSP());
      return true;
   }

   if (reg.isPC()) {
      val = static_cast<MachRegisterVal>(depth_frame->getRA());
      return true;
   }

   bool result = false;
   const Frame *prevDepthFrame = depth_frame;
   depth_frame = depth_frame->getPrevFrame();
   if (!depth_frame)
   {
      result = getProcessState()->getRegValue(reg, cur_frame->getThread(), val);
   }
#if defined(WITH_SYMTAB_API)
   else
   {
      Offset offset;
      void *symtab_v = NULL;
      std::string lib;
      depth_frame->getLibOffset(lib, offset, symtab_v);
      SymtabAPI::Symtab *symtab = (SymtabAPI::Symtab*) symtab_v;
      if (symtab)
      {
         result = symtab->getRegValueAtFrame(offset, reg, val, this);
      }
#if defined(arch_aarch64)
      if (!result) {
          sw_printf("Cast framestepper %p for frame %p to SigHandlerStepper at address %lx\n", prevDepthFrame->getStepper(), prevDepthFrame, prevDepthFrame->getRA());

          SigHandlerStepper * ss = dynamic_cast<SigHandlerStepper*> (prevDepthFrame->getStepper());
	  if (ss != NULL) {
	      sw_printf("[%s:%u] - Not the first frame, cannot find dbg information, and previous frame is a signal trampoline frame. Try to get x30 from ucontext as RA\n",
                FILE__, __LINE__);
              static     ucontext_t dummy_context;
	      static int lr_offset = (char*)&(dummy_context.uc_mcontext.regs[30]) - (char*)&dummy_context;
	      // This assumes that a ucontext_t is at the following offset from the top of the signal handler's stack.
	      static int ucontext_offset = 128;
	      const Frame * signal_frame = depth_frame;
	      if (signal_frame != NULL) {
	          int addr_size = 8;
	          Address lr_addr = signal_frame->getSP() + ucontext_offset + lr_offset;
		  result = getProcessState()->readMem(&val, lr_addr, addr_size);
	      sw_printf("[%s:%u] - readMem results %d, get %lx as RA\n",
                FILE__, __LINE__, result, val);

	      } else {
	      sw_printf("[%s:%u] - the signal trampoline frame does not have a parent frame\n",
                FILE__, __LINE__);
	      }
	  } else {
	      sw_printf("Cannot cast framestepper to SigHandlerStepper\n");
	  }
       }
#endif
   }
#endif

   depth_frame = prevDepthFrame;
   return result;
}

gcframe_ret_t DebugStepperImpl::getCallerFrame(const Frame &in, Frame &out)
{
   LibAddrPair lib;
   bool result;

   if (lookupInCache(in, out)) {
       result = getProcessState()->getLibraryTracker()->getLibraryAtAddr(out.getRA(), lib);
       if (result) {
           // Hit, and valid RA found
           return gcf_success;
       }
   }

   // This error check is duplicated in BottomOfStackStepper.
   // We should always call BOSStepper first; however, we need the
   // library for the debug stepper as well. If this becomes
   // a performance problem we can cache the library info in
   // the input frame.
   result = getProcessState()->getLibraryTracker()->getLibraryAtAddr(in.getRA(), lib);
   if (!result) {
      sw_printf("[%s:%u] - Stackwalking with PC at %lx, which is not found in any known libraries\n",
                FILE__, __LINE__, in.getRA());
      return gcf_not_me;
   }
   Address pc = in.getRA() - lib.second;
   sw_printf("[%s:%u] Dwarf-based stackwalking, using local address 0x%lx from 0x%lx - 0x%lx\n",
             FILE__, __LINE__, pc, in.getRA(), lib.second);
   if (in.getRALocation().location != loc_register && !in.nonCall()) {
      /**
       * If we're here, then our in.getRA() should be pointed at the
       * instruction following a call.  We could either use the
       * call instruction's debug info (pc - 1) or the following
       * instruction's debug info (pc) to continue the stackwalk.
       *
       * In most cases it doesn't matter.  Because of how DWARF debug
       * info is defined, the stack doesn't change between these two points.
       *
       * However, if the call is a non-returning call (e.g, a call to exit)
       * then the next instruction may not exist or may be part of a separate
       * block with different debug info.  In these cases we want to use the
       * debug info associated with the call.  So, we subtract 1 from the
       * pc to get at the call instruction.
       **/
      pc = pc - 1;
   }

   /**
    * Some system libraries on some systems have their debug info split
    * into separate files, usually in /usr/lib/debug/.  Check these
    * for DWARF debug info
    **/
   DwarfFrameParser::Ptr dauxinfo = getAuxDwarfInfo(lib.first);
   if (!dauxinfo || !dauxinfo->hasFrameDebugInfo()) {
      sw_printf("[%s:%u] - Library %s does not have stackwalking debug info\n",
                 FILE__, __LINE__, lib.first.c_str());
      return gcf_not_me;
   }

   bool isVsyscallPage = false;
#if defined(os_linux)
   sw_printf("ARM-debug: dump lib========================\n");
   sw_printf("%s\n", lib.first.c_str());
   sw_printf("ARM-debug: dump lib========================\n");
   isVsyscallPage = (strstr(lib.first.c_str(), "[vsyscall-") != NULL);
#endif

   sw_printf("[%s:%u] - Using DWARF debug file info for %s\n",
                   FILE__, __LINE__, lib.first.c_str());
   cur_frame = ∈
   gcframe_ret_t gcresult = getCallerFrameArch(pc, in, out, dauxinfo, isVsyscallPage);
   cur_frame = NULL;

   result = getProcessState()->getLibraryTracker()->getLibraryAtAddr(out.getRA(), lib);
   if (!result) return gcf_not_me;

   if (gcresult == gcf_success) {
      sw_printf("[%s:%u] - Success walking with DWARF aux file\n",
                FILE__, __LINE__);
      return gcf_success;
   }

   return gcresult;
}

void DebugStepperImpl::registerStepperGroup(StepperGroup *group)
{
   addr_width = group->getWalker()->getProcessState()->getAddressWidth();
   if (addr_width == 4)
      group->addStepper(parent_stepper, 0, 0xffffffff);
#if defined(arch_64bit)
   else if (addr_width == 8)
      group->addStepper(parent_stepper, 0, 0xffffffffffffffff);
#endif
   else
      assert(0 && "Unknown architecture word size");
}

unsigned DebugStepperImpl::getPriority() const
{
   return debugstepper_priority;
}

DebugStepperImpl::~DebugStepperImpl()
{
}

#if defined(arch_x86) || defined(arch_x86_64)
gcframe_ret_t DebugStepperImpl::getCallerFrameArch(Address pc, const Frame &in,
                                                   Frame &out, DwarfFrameParser::Ptr dinfo,
                                                   bool isVsyscallPage)
{
   MachRegisterVal frame_value, stack_value, ret_value;
   bool result;
   FrameErrors_t frame_error = FE_No_Error;

   addr_width = getProcessState()->getAddressWidth();

   depth_frame = cur_frame;

   result = dinfo->getRegValueAtFrame(pc, Dyninst::ReturnAddr,
                                      ret_value, this, frame_error);

   if (!result && frame_error == FE_No_Frame_Entry && isVsyscallPage) {
      //Work-around kernel bug.  The vsyscall page location was randomized, but
      // the debug info still has addresses from the old, pre-randomized days.
      // See if we get any hits by assuming the address corresponds to the
      // old PC.
      pc += 0xffffe000;
      result = dinfo->getRegValueAtFrame(pc, Dyninst::ReturnAddr,
                                         ret_value, this, frame_error);
   }
   if (!result) {
      sw_printf("[%s:%u] - Couldn't get return debug info at %lx, error: %u\n",
                FILE__, __LINE__, in.getRA(), frame_error);
      return gcf_not_me;
   }
   location_t ra_loc = getLastComputedLocation(ret_value);

   Dyninst::MachRegister frame_reg;
   if (addr_width == 4)
      frame_reg = x86::ebp;
   else
      frame_reg = x86_64::rbp;

   result = dinfo->getRegValueAtFrame(pc, frame_reg,
                                      frame_value, this, frame_error);
   if (!result) {
      sw_printf("[%s:%u] - Couldn't get frame debug info at %lx\n",
                 FILE__, __LINE__, in.getRA());
      return gcf_not_me;
   }
   location_t fp_loc = getLastComputedLocation(frame_value);

   result = dinfo->getRegValueAtFrame(pc, Dyninst::FrameBase,
                                      stack_value, this, frame_error);
   if (!result) {
      sw_printf("[%s:%u] - Couldn't get stack debug info at %lx\n",
                 FILE__, __LINE__, in.getRA());
      return gcf_not_me;
   }
   location_t sp_loc = getLastComputedLocation(stack_value);

   if (isVsyscallPage) {
      // RHEL6 has broken DWARF in the vsyscallpage; it has
      // a double deref for the stack pointer. We detect this
      // (as much as we can...) and ignore it
      if (stack_value < in.getSP()) {
         stack_value = 0;
         sp_loc.location = loc_unknown;
      }
   }

   Address MAX_ADDR;
   if (addr_width == 4) {
       MAX_ADDR = 0xffffffff;
   }
#if defined(arch_64bit)
   else if (addr_width == 8){
       MAX_ADDR = 0xffffffffffffffff;
   }
#endif
   else {
       assert(0 && "Unknown architecture word size");
   }

   if(ra_loc.val.addr > MAX_ADDR || fp_loc.val.addr > MAX_ADDR || sp_loc.val.addr > MAX_ADDR) return gcf_not_me;

   out.setRA(ret_value);
   out.setFP(frame_value);
   out.setSP(stack_value);
   out.setRALocation(ra_loc);
   out.setFPLocation(fp_loc);
   out.setSPLocation(sp_loc);

   addToCache(in, out);

   return gcf_success;
}

void DebugStepperImpl::addToCache(const Frame &cur, const Frame &caller) {
  const location_t &calRA = caller.getRALocation();

  const location_t &calFP = caller.getFPLocation();

  unsigned raDelta = (unsigned) -1;
  unsigned fpDelta = (unsigned) -1;
  unsigned spDelta = (unsigned) -1;

  if (calRA.location == loc_address) {
    raDelta = calRA.val.addr - cur.getSP();
  }

  if (calFP.location == loc_address) {
    fpDelta = calFP.val.addr - cur.getSP();
  }

  spDelta = caller.getSP() - cur.getSP();

  cache_[cur.getRA()] = cache_t(raDelta, fpDelta, spDelta);
}

bool DebugStepperImpl::lookupInCache(const Frame &cur, Frame &caller) {
  dyn_hash_map<Address,cache_t>::iterator iter = cache_.find(cur.getRA());
  if (iter == cache_.end()) {
      return false;
  }

  addr_width = getProcessState()->getAddressWidth();

  if (iter->second.ra_delta == (unsigned) -1) {
      return false;
  }
  if (iter->second.fp_delta == (unsigned) -1) {
    return false;
  }
  assert(iter->second.sp_delta != (unsigned) -1);

  Address MAX_ADDR;
   if (addr_width == 4) {
       MAX_ADDR = 0xffffffff;
   }
#if defined(arch_64bit)
   else if (addr_width == 8){
       MAX_ADDR = 0xffffffffffffffff;
   }
#endif
   else {
       assert(0 && "Unknown architecture word size");
       return false;
   }

  location_t RA;
  RA.location = loc_address;
  RA.val.addr = cur.getSP() + iter->second.ra_delta;
  RA.val.addr %= MAX_ADDR;

  location_t FP;
  FP.location = loc_address;
  FP.val.addr = cur.getSP() + iter->second.fp_delta;

  FP.val.addr %= MAX_ADDR;
  int buffer[10];

  caller.setRALocation(RA);
  ReadMem(RA.val.addr, buffer, addr_width);
  caller.setRA(last_val_read);

  caller.setFPLocation(FP);
  ReadMem(FP.val.addr, buffer, addr_width);
  caller.setFP(last_val_read);

  caller.setSP(cur.getSP() + iter->second.sp_delta);

  return true;
}

#endif

// for aarch64 architecure specifically
#if defined(arch_aarch64)
gcframe_ret_t DebugStepperImpl::getCallerFrameArch(Address pc, const Frame &in,
                                                   Frame &out, DwarfFrameParser::Ptr dinfo,
                                                   bool isVsyscallPage)
{
   MachRegisterVal frame_value, stack_value, ret_value;
   bool result;
   FrameErrors_t frame_error = FE_No_Error;

   addr_width = getProcessState()->getAddressWidth();

   depth_frame = cur_frame;

   sw_printf("\nDebugStepperImpl::getCallerFrameArch() calls getRegValueAtFrame()\n");
   result = dinfo->getRegValueAtFrame(pc, Dyninst::ReturnAddr,
   //result = dinfo->getRegValueAtFrame(pc, Dyninst::aarch64::x30,
                                      ret_value, this, frame_error);

   if (!result && frame_error == FE_No_Frame_Entry && isVsyscallPage) {
      //Work-around kernel bug.  The vsyscall page location was randomized, but
      // the debug info still has addresses from the old, pre-randomized days.
      // See if we get any hits by assuming the address corresponds to the
      // old PC.
      pc += 0xffffe000;
      result = dinfo->getRegValueAtFrame(pc, Dyninst::ReturnAddr,
                                         ret_value, this, frame_error);
   }
   if (!result) {
      sw_printf("[%s:%u] - Couldn't get return debug info at %lx, error: %u\n",
                FILE__, __LINE__, in.getRA(), frame_error);
      return gcf_not_me;
   }
   location_t ra_loc = getLastComputedLocation(ret_value);

   Dyninst::MachRegister frame_reg;
   frame_reg = Dyninst::aarch64::x29;

   sw_printf("\nDebugStepperImpl::getCallerFrameArch() calls getRegValueAtFrame()\n");
   result = dinfo->getRegValueAtFrame(pc, frame_reg,
                                      frame_value, this, frame_error);
   if (!result) {
      sw_printf("[%s:%u] - Couldn't get frame debug info at %lx\n",
                 FILE__, __LINE__, in.getRA());
      return gcf_not_me;
   }
   location_t fp_loc = getLastComputedLocation(frame_value);

   sw_printf("\nDebugStepperImpl::getCallerFrameArch() calls getRegValueAtFrame()\n");
   result = dinfo->getRegValueAtFrame(pc, Dyninst::FrameBase,
                                      stack_value, this, frame_error);
   if (!result) {
      sw_printf("[%s:%u] - Couldn't get stack debug info at %lx\n",
                 FILE__, __LINE__, in.getRA());
      return gcf_not_me;
   }
   location_t sp_loc = getLastComputedLocation(stack_value);

   if (isVsyscallPage) {
      // RHEL6 has broken DWARF in the vsyscallpage; it has
      // a double deref for the stack pointer. We detect this
      // (as much as we can...) and ignore it
      if (stack_value < in.getSP()) {
         stack_value = 0;
         sp_loc.location = loc_unknown;
      }
   }

   Address MAX_ADDR;
   if (addr_width == 4) {
       MAX_ADDR = 0xffffffff;
   }
   else if (addr_width == 8){
       MAX_ADDR = 0xffffffffffffffff;
   }
   else {
       assert(0 && "Unknown architecture word size");
   }

   if(ra_loc.val.addr > MAX_ADDR || fp_loc.val.addr > MAX_ADDR || sp_loc.val.addr > MAX_ADDR) return gcf_not_me;

   out.setRA(ret_value);
   out.setFP(frame_value);
   out.setSP(stack_value);
   out.setRALocation(ra_loc);
   out.setFPLocation(fp_loc);
   out.setSPLocation(sp_loc);

   addToCache(in, out);

   return gcf_success;
}

void DebugStepperImpl::addToCache(const Frame &cur, const Frame &caller) {
  const location_t &calRA = caller.getRALocation();

  const location_t &calFP = caller.getFPLocation();

  unsigned raDelta = (unsigned) -1;
  unsigned fpDelta = (unsigned) -1;
  unsigned spDelta = (unsigned) -1;

  if (calRA.location == loc_address) {
    raDelta = calRA.val.addr - cur.getSP();
  }

  if (calFP.location == loc_address) {
    fpDelta = calFP.val.addr - cur.getSP();
  }

  spDelta = caller.getSP() - cur.getSP();

  cache_[cur.getRA()] = cache_t(raDelta, fpDelta, spDelta);
}

bool DebugStepperImpl::lookupInCache(const Frame &cur, Frame &caller) {
  dyn_hash_map<Address,cache_t>::iterator iter = cache_.find(cur.getRA());
  if (iter == cache_.end()) {
      return false;
  }

  addr_width = getProcessState()->getAddressWidth();

  if (iter->second.ra_delta == (unsigned) -1) {
      return false;
  }
  if (iter->second.fp_delta == (unsigned) -1) {
    return false;
  }
  assert(iter->second.sp_delta != (unsigned) -1);

  Address MAX_ADDR;
   if (addr_width == 4) {
       assert(0);
       MAX_ADDR = 0xffffffff;
   }
   else if (addr_width == 8){
       MAX_ADDR = 0xffffffffffffffff;
   }
   else {
       assert(0 && "Unknown architecture word size");
       return false;
   }

  location_t RA;
  RA.location = loc_address;
  RA.val.addr = cur.getSP() + iter->second.ra_delta;
  RA.val.addr %= MAX_ADDR;

  location_t FP;
  FP.location = loc_address;
  FP.val.addr = cur.getSP() + iter->second.fp_delta;

  FP.val.addr %= MAX_ADDR;
  int buffer[10];

  caller.setRALocation(RA);
  ReadMem(RA.val.addr, buffer, addr_width);
  caller.setRA(last_val_read);

  caller.setFPLocation(FP);
  ReadMem(FP.val.addr, buffer, addr_width);
  caller.setFP(last_val_read);

  caller.setSP(cur.getSP() + iter->second.sp_delta);

  return true;
}
#endif
//end if defined aarch64

{'repo_name': 'dyninst/dyninst', 'stars': '376', 'repo_language': 'C', 'file_name': '2-Language.tex', 'mime_type': 'text/x-tex', 'hash': 172587987359871254, 'source_dataset': 'data'}


// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/***********************************************************************************
**
** GameConsole.cpp
**
** Copyright (C) August 2016 Hotride
**
************************************************************************************
*/
//----------------------------------------------------------------------------------
#include "stdafx.h"
//----------------------------------------------------------------------------------
CGameConsole g_GameConsole;
//----------------------------------------------------------------------------------
CGameConsole::CGameConsole()
    : CEntryText(128, 1000, 1000)
{
}
//----------------------------------------------------------------------------------
CGameConsole::~CGameConsole()
{
    WISPFUN_DEBUG("c170_f1");
    if (g_EntryPointer == this)
        g_EntryPointer = NULL;
}
//----------------------------------------------------------------------------------
void CGameConsole::Send()
{
    WISPFUN_DEBUG("c170_f2");
    Send(Text);
}
//----------------------------------------------------------------------------------
void CGameConsole::Send(wstring text, ushort defaultColor)
{
    WISPFUN_DEBUG("c170_f2.1");
    size_t len = text.length();

    if (len)
    {
        SPEECH_TYPE speechType = ST_NORMAL;
        ushort sendColor = g_ConfigManager.SpeechColor;
        int offset = 0;

        if (len > 1)
        {
            int member = -1;
            GAME_CONSOLE_TEXT_TYPE type = GCTT_NORMAL;
            IsSystemCommand(text.c_str(), len, member, type);

            if ((type != GCTT_NORMAL && len > 2) || type == GCTT_PARTY)
            {
                if (type == GCTT_YELL)
                {
                    speechType = ST_YELL;
                    offset = 2;
                }
                else if (type == GCTT_WHISPER)
                {
                    speechType = ST_WHISPER;
                    offset = 2;
                }
                else if (type == GCTT_EMOTE)
                {
                    text = text.replace(0, 2, L": *").append(L"*");
                    speechType = ST_EMOTE;
                    sendColor = g_ConfigManager.EmoteColor;
                    offset = 2;
                }
                else if (type == GCTT_GUILD)
                {
                    speechType = ST_GUILD_CHAT;
                    sendColor = g_ConfigManager.GuildMessageColor;
                    offset = 2;
                }
                else if (type == GCTT_ALLIANCE)
                {
                    sendColor = g_ConfigManager.AllianceMessageColor;
                    speechType = ST_ALLIANCE_CHAT;
                    offset = 2;
                }
                else if (type == GCTT_PARTY)
                {
                    uint serial = 0;
                    offset = 1;
                    sendColor = g_ConfigManager.PartyMessageColor;

                    if (member != -1)
                        serial = g_Party.Member[member].Serial;

                    if (g_Party.Leader != 0)
                        CPacketPartyMessage(text.c_str() + offset, len - offset, serial).Send();
                    else
                    {
                        string str = "Note to self: " + ToString(text.c_str() + offset);
                        g_Orion.CreateTextMessage(TT_SYSTEM, 0, 3, 0, str);
                    }

                    return;
                }
                else if (type == GCTT_PARTY_ACCEPT)
                {
                    if (g_Party.Inviter != 0 && g_Party.Leader == 0)
                    {
                        CPacketPartyAccept(g_Party.Inviter).Send();

                        g_Party.Leader = g_Party.Inviter;
                        g_Party.Inviter = 0;
                    }
                    else
                        g_Orion.CreateTextMessage(
                            TT_SYSTEM, 0, 3, 0, "No one has invited you to be in a party.");

                    return;
                }
                else if (type == GCTT_PARTY_DECLINE)
                {
                    if (g_Party.Inviter != 0 && g_Party.Leader == 0)
                    {
                        CPacketPartyDecline(g_Party.Inviter).Send();

                        g_Party.Leader = 0;
                        g_Party.Inviter = 0;
                    }
                    else
                        g_Orion.CreateTextMessage(
                            TT_SYSTEM, 0, 3, 0, "No one has invited you to be in a party.");

                    return;
                }
                else if (type == GCTT_PARTY_ADD)
                {
                    if (g_Party.Leader == 0 || g_Party.Leader == g_PlayerSerial)
                        CPacketPartyInviteRequest().Send();
                    else
                        g_Orion.CreateTextMessage(TT_SYSTEM, 0, 3, 0, "You are not party leader.");

                    return;
                }
                else if (type == GCTT_PARTY_LEAVE)
                {
                    if (g_Party.Leader != 0)
                    {
                        IFOR (i, 0, 10)
                        {
                            if (g_Party.Member[i].Serial != 0)
                                CPacketPartyRemoveRequest(g_Party.Member[i].Serial).Send();
                        }
                    }
                    else
                        g_Orion.CreateTextMessage(
                            TT_SYSTEM, 0xFFFFFFFF, 3, 0, "You are not in a party.");

                    return;
                }
            }
        }

        if (defaultColor)
            sendColor = defaultColor;

        CPacketUnicodeSpeechRequest(
            text.c_str() + offset, speechType, 3, sendColor, (puchar)g_Language.c_str())
            .Send();
    }
}
//----------------------------------------------------------------------------------
wstring CGameConsole::IsSystemCommand(
    const wchar_t *text, size_t &len, int &member, GAME_CONSOLE_TEXT_TYPE &type)
{
    WISPFUN_DEBUG("c170_f3");
    type = GCTT_NORMAL;
    wstring result = L"";

    if (*text == g_ConsolePrefix[GCTT_PARTY][0]) //Party
    {
        string lStr = ToString(text);
        const char *cText = lStr.c_str();

        char *ptr = (char *)cText + 1;

        while (ptr < cText + len && *ptr == ' ')
            ptr++;

        if (ptr < cText + len)
        {
            int i = 0;

            sscanf_s(ptr, "%i", &i);

            if (i > 0 && i < 11) //Party mebmer
            {
                char pmBuf[50] = { 0 };

                if (g_Party.Member[i - 1].Serial != 0)
                    sprintf_s(pmBuf, "Tell [%s]:", g_Party.Member[i - 1].GetName(i).c_str());
                else
                    sprintf_s(pmBuf, "Tell []:");

                result = ToWString(pmBuf);

                type = GCTT_PARTY;
                member = i - 1;
            }
        }

        if (type == GCTT_NORMAL && len >= 4 && len <= 8)
        {
            size_t lLen = 4;

            if (len > 4)
                lLen = len;

            char lBuf[10] = { 0 };

            memcpy(&lBuf[0], cText, lLen);

            _strlwr(lBuf);

            if (!memcmp(&lBuf[0], "/add", 4)) //Party add
                type = GCTT_PARTY_ADD;
            else if (
                (!memcmp(&lBuf[0], "/quit", 5)) ||
                (!memcmp(&lBuf[0], "/leave", 6))) //Party leave & quit
                type = GCTT_PARTY_LEAVE;
            else if (!memcmp(&lBuf[0], "/accept", 7)) //Party accept
                type = GCTT_PARTY_ACCEPT;
            else if (!memcmp(&lBuf[0], "/decline", 8)) //Party decline
                type = GCTT_PARTY_DECLINE;
        }

        if ((type == GCTT_PARTY_ADD || type == GCTT_PARTY_LEAVE || type == GCTT_PARTY_ACCEPT ||
             type == GCTT_PARTY_DECLINE) &&
            !result.length())
            result = L"Party:";

        if (type == GCTT_NORMAL && !result.length())
        {
            result = L"Party:";
            type = GCTT_PARTY;
        }
    }
    else if (!memcmp(&text[0], g_ConsolePrefix[GCTT_YELL].c_str(), 4)) //Yell
    {
        result = L"Yell:";
        type = GCTT_YELL;
    }
    else if (!memcmp(&text[0], g_ConsolePrefix[GCTT_WHISPER].c_str(), 4)) //Whisper
    {
        result = L"Whisper:";
        type = GCTT_WHISPER;
    }
    else if (!memcmp(&text[0], g_ConsolePrefix[GCTT_EMOTE].c_str(), 4)) //Emote
    {
        result = L"Emote:";
        type = GCTT_EMOTE;
    }
    else if (
        g_Player->Graphic == 0x03DB && (*text == L'=' || *text == g_ConsolePrefix[GCTT_C][0])) //C
    {
        result = L"C:";
        type = GCTT_C;
    }
    else if (!memcmp(&text[0], g_ConsolePrefix[GCTT_BROADCAST].c_str(), 4)) //Broadcast
    {
        result = L"Broadcast:";
        type = GCTT_BROADCAST;
    }
    else if (!memcmp(&text[0], g_ConsolePrefix[GCTT_GUILD].c_str(), 4)) //Guild
    {
        result = L"Guild:";
        type = GCTT_GUILD;
    }
    else if (!memcmp(&text[0], g_ConsolePrefix[GCTT_ALLIANCE].c_str(), 4)) //Alliance
    {
        result = L"Alliance:";
        type = GCTT_ALLIANCE;
    }

    return result;
}
//----------------------------------------------------------------------------------
void CGameConsole::DrawW(BYTE font, WORD color, int x, int y, TEXT_ALIGN_TYPE align, WORD flags)
{
    WISPFUN_DEBUG("c170_f4");
    int posOffset = 0;
    wstring wtext = Data();

    if (Changed || Color != color)
        FixMaxWidthW(font);

    size_t len = Length();
    const wchar_t *text = Data();

    if (len >= 2)
    {
        int member = 0;
        wstring sysStr = IsSystemCommand(text, len, member, m_Type);

        if (sysStr.length())
        {
            posOffset = g_FontManager.GetWidthW(font, sysStr);

            wchar_t trimPart[2] = L" ";
            *trimPart = *text;
            posOffset -= g_FontManager.GetWidthW(font, trimPart);

            sysStr += (text + 1);

            wtext = sysStr;
        }
    }

    if (Changed || Color != color)
    {
        CheckMaxWidthW(font, wtext);

        CreateTextureW(font, wtext, color, Width, align, flags);

        Changed = false;
        Color = color;
    }

    m_Texture.Draw(x, y);

    if (this == g_EntryPointer)
    {
        if (m_Position)
        {
            wtext.resize(m_Position);
            x += (g_FontManager.GetWidthW(font, wtext) + posOffset);
        }

        g_FontManager.DrawW(font, L"_", color, x, y, 30, 0, align, UOFONT_BLACK_BORDER);
    }
}
//----------------------------------------------------------------------------------
void CGameConsole::SaveConsoleMessage()
{
    WISPFUN_DEBUG("c170_f5");
    if (m_ConsoleStack[m_ConsoleSelectedIndex % MAX_CONSOLE_STACK_SIZE] != Text)
    {
        m_ConsoleStack[m_ConsoleStackCount % MAX_CONSOLE_STACK_SIZE] = Text;
        m_ConsoleStackCount++;

        if (m_ConsoleStackCount > 1100)
            m_ConsoleStackCount -= 1000;
    }

    m_ConsoleSelectedIndex = (m_ConsoleStackCount - 1) % MAX_CONSOLE_STACK_SIZE;
    m_PositionChanged = false;
}
//----------------------------------------------------------------------------------
void CGameConsole::ChangeConsoleMessage(bool next)
{
    WISPFUN_DEBUG("c170_f6");
    if (m_ConsoleStackCount)
    {
        if (m_PositionChanged)
        {
            if (next)
            {
                m_ConsoleSelectedIndex = (m_ConsoleSelectedIndex + 1) % MAX_CONSOLE_STACK_SIZE;

                if (m_ConsoleSelectedIndex >= m_ConsoleStackCount)
                    m_ConsoleSelectedIndex = 0;
            }
            else
            {
                m_ConsoleSelectedIndex--;

                if (m_ConsoleSelectedIndex < 0)
                    m_ConsoleSelectedIndex = (m_ConsoleStackCount - 1) % MAX_CONSOLE_STACK_SIZE;
            }
        }
        else if (next)
            m_ConsoleSelectedIndex = 0;

        SetText(m_ConsoleStack[m_ConsoleSelectedIndex]);
        SetPos((int)m_ConsoleStack[m_ConsoleSelectedIndex].length());
        m_PositionChanged = true;
    }
}
//----------------------------------------------------------------------------------
void CGameConsole::ClearStack()
{
    WISPFUN_DEBUG("c170_f7");
    m_ConsoleStack[0] = L"";
    m_ConsoleStackCount = 0;
    m_ConsoleSelectedIndex = 0;
    m_PositionChanged = false;
}
//----------------------------------------------------------------------------------

{'repo_name': 'Hotride/OrionUO', 'stars': '131', 'repo_language': 'C++', 'file_name': 'SDL_name.h', 'mime_type': 'text/x-c', 'hash': -1526664991322084830, 'source_dataset': 'data'}


<!DOCTYPE html>

{'repo_name': 'mozilla/gecko-dev', 'stars': '1901', 'repo_language': 'None', 'file_name': 'AddonManager.rst', 'mime_type': 'text/plain', 'hash': 3650425132493879854, 'source_dataset': 'data'}