/*-------------------------------------------------------------------------
 *
 * prepsecurity.c
 *	  Routines for preprocessing security barrier quals.
 *
 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  src/backend/optimizer/prep/prepsecurity.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "access/heapam.h"
#include "access/sysattr.h"
#include "catalog/heap.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/prep.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
#include "utils/rel.h"

typedef struct
{
	int			rt_index;		/* Index of security barrier RTE */
	int			sublevels_up;	/* Current nesting depth */
	Relation	rel;			/* RTE relation at rt_index */
	List	   *targetlist;		/* Targetlist for new subquery RTE */
	List	   *colnames;		/* Column names in subquery RTE */
	List	   *vars_processed; /* List of Vars already processed */
} security_barrier_replace_vars_context;

static void expand_security_qual(PlannerInfo *root, List *tlist, int rt_index,
					 RangeTblEntry *rte, Node *qual, bool targetRelation);

static void security_barrier_replace_vars(Node *node,
							  security_barrier_replace_vars_context *context);

static bool security_barrier_replace_vars_walker(Node *node,
							 security_barrier_replace_vars_context *context);

/*
 * expand_security_quals -
 *	  expands any security barrier quals on RTEs in the query rtable, turning
 *	  them into security barrier subqueries.
 *
 * Any given RTE may have multiple security barrier quals in a list, from which
 * we create a set of nested subqueries to isolate each security barrier from
 * the others, providing protection against malicious user-defined security
 * barriers.  The first security barrier qual in the list will be used in the
 * innermost subquery.
 *
 * In practice, the only RTEs that will have security barrier quals are those
 * that refer to tables with row-level security, or which are the target
 * relation of an update to an auto-updatable security barrier view.  RTEs
 * that read from a security barrier view will have already been expanded by
 * the rewriter.
 */
void
expand_security_quals(PlannerInfo *root, List *tlist)
{
	Query	   *parse = root->parse;
	int			rt_index;
	ListCell   *cell;

	/*
	 * Process each RTE in the rtable list.
	 *
	 * We only ever modify entries in place and append to the rtable, so it is
	 * safe to use a foreach loop here.
	 */
	rt_index = 0;
	foreach(cell, parse->rtable)
	{
		bool		targetRelation = false;
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(cell);

		rt_index++;

		if (rte->securityQuals == NIL)
			continue;

		/*
		 * Ignore any RTEs that aren't used in the query (such RTEs may be
		 * present for permissions checks).
		 */
		if (rt_index != parse->resultRelation &&
			!rangeTableEntry_used((Node *) parse, rt_index, 0))
			continue;

		/*
		 * If this RTE is the target then we need to make a copy of it before
		 * expanding it.  The unexpanded copy will become the new target, and
		 * the original RTE will be expanded to become the source of rows to
		 * update/delete.
		 */
		if (rt_index == parse->resultRelation)
		{
			RangeTblEntry *newrte = copyObject(rte);

			/*
			 * We need to let expand_security_qual know if this is the target
			 * relation, as it has additional work to do in that case.
			 *
			 * Capture that information here as we're about to replace
			 * parse->resultRelation.
			 */
			targetRelation = true;

			parse->rtable = lappend(parse->rtable, newrte);
			parse->resultRelation = list_length(parse->rtable);

			/*
			 * Wipe out any copied security barrier quals on the new target to
			 * prevent infinite recursion.
			 */
			newrte->securityQuals = NIL;

			/*
			 * There's no need to do permissions checks twice, so wipe out the
			 * permissions info for the original RTE (we prefer to keep the
			 * bits set on the result RTE).
			 */
			rte->requiredPerms = 0;
			rte->checkAsUser = InvalidOid;
			rte->selectedCols = NULL;
			rte->insertedCols = NULL;
			rte->updatedCols = NULL;

			/*
			 * For the most part, Vars referencing the original relation
			 * should remain as they are, meaning that they pull OLD values
			 * from the expanded RTE.  But in the RETURNING list and in any
			 * WITH CHECK OPTION quals, we want such Vars to represent NEW
			 * values, so change them to reference the new RTE.
			 */
			ChangeVarNodes((Node *) parse->returningList, rt_index,
						   parse->resultRelation, 0);

			ChangeVarNodes((Node *) parse->withCheckOptions, rt_index,
						   parse->resultRelation, 0);
		}

		/*
		 * Process each security barrier qual in turn, starting with the
		 * innermost one (the first in the list) and working outwards.
		 *
		 * We remove each qual from the list before processing it, so that its
		 * variables aren't modified by expand_security_qual.  Also we don't
		 * necessarily want the attributes referred to by the qual to be
		 * exposed by the newly built subquery.
		 */
		while (rte->securityQuals != NIL)
		{
			Node	   *qual = (Node *) linitial(rte->securityQuals);

			rte->securityQuals = list_delete_first(rte->securityQuals);

			ChangeVarNodes(qual, rt_index, 1, 0);
			expand_security_qual(root, tlist, rt_index, rte, qual,
								 targetRelation);
		}
	}
}

/*
 * expand_security_qual -
 *	  expand the specified security barrier qual on a query RTE, turning the
 *	  RTE into a security barrier subquery.
 */
static void
expand_security_qual(PlannerInfo *root, List *tlist, int rt_index,
					 RangeTblEntry *rte, Node *qual, bool targetRelation)
{
	Query	   *parse = root->parse;
	Oid			relid = rte->relid;
	Query	   *subquery;
	RangeTblEntry *subrte;
	RangeTblRef *subrtr;
	PlanRowMark *rc;
	security_barrier_replace_vars_context context;
	ListCell   *cell;

	/*
	 * There should only be 2 possible cases:
	 *
	 * 1. A relation RTE, which we turn into a subquery RTE containing all
	 * referenced columns.
	 *
	 * 2. A subquery RTE (either from a prior call to this function or from an
	 * expanded view).  In this case we build a new subquery on top of it to
	 * isolate this security barrier qual from any other quals.
	 */
	switch (rte->rtekind)
	{
		case RTE_RELATION:

			/*
			 * Turn the relation RTE into a security barrier subquery RTE,
			 * moving all permissions checks down into the subquery.
			 */
			subquery = makeNode(Query);
			subquery->commandType = CMD_SELECT;
			subquery->querySource = QSRC_INSTEAD_RULE;

			subrte = copyObject(rte);
			subrte->inFromCl = true;
			subrte->securityQuals = NIL;
			subquery->rtable = list_make1(subrte);

			subrtr = makeNode(RangeTblRef);
			subrtr->rtindex = 1;
			subquery->jointree = makeFromExpr(list_make1(subrtr), qual);
			subquery->hasSubLinks = checkExprHasSubLink(qual);

			rte->rtekind = RTE_SUBQUERY;
			rte->relid = InvalidOid;
			rte->subquery = subquery;
			rte->security_barrier = true;
			rte->inh = false;	/* must not be set for a subquery */

			/* the permissions checks have now been moved down */
			rte->requiredPerms = 0;
			rte->checkAsUser = InvalidOid;
			rte->selectedCols = NULL;
			rte->insertedCols = NULL;
			rte->updatedCols = NULL;

			/*
			 * Now deal with any PlanRowMark on this RTE by requesting a lock
			 * of the same strength on the RTE copied down to the subquery.
			 *
			 * Note that we can only push down user-defined quals if they are
			 * only using leakproof (and therefore trusted) functions and
			 * operators.  As a result, we may end up locking more rows than
			 * strictly necessary (and, in the worst case, we could end up
			 * locking all rows which pass the securityQuals).  This is
			 * currently documented behavior, but it'd be nice to come up with
			 * a better solution some day.
			 */
			rc = get_plan_rowmark(root->rowMarks, rt_index);
			if (rc != NULL)
			{
				if (rc->strength != LCS_NONE)
					applyLockingClause(subquery, 1, rc->strength,
									   rc->waitPolicy, false);
				root->rowMarks = list_delete_ptr(root->rowMarks, rc);
			}

			/*
			 * When we are replacing the target relation with a subquery, we
			 * need to make sure to add a locking clause explicitly to the
			 * generated subquery since there won't be any row marks against
			 * the target relation itself.
			 */
			if (targetRelation)
				applyLockingClause(subquery, 1, LCS_FORUPDATE,
								   LockWaitBlock, false);

			/*
			 * Replace any variables in the outer query that refer to the
			 * original relation RTE with references to columns that we will
			 * expose in the new subquery, building the subquery's targetlist
			 * as we go.  Also replace any references in the translated_vars
			 * lists of any appendrels.
			 */
			context.rt_index = rt_index;
			context.sublevels_up = 0;
			context.rel = heap_open(relid, NoLock);
			context.targetlist = NIL;
			context.colnames = NIL;
			context.vars_processed = NIL;

			security_barrier_replace_vars((Node *) parse, &context);
			security_barrier_replace_vars((Node *) tlist, &context);
			security_barrier_replace_vars((Node *) root->append_rel_list,
										  &context);

			heap_close(context.rel, NoLock);

			/* Now we know what columns the subquery needs to expose */
			rte->subquery->targetList = context.targetlist;
			rte->eref = makeAlias(rte->eref->aliasname, context.colnames);

			break;

		case RTE_SUBQUERY:

			/*
			 * Build a new subquery that includes all the same columns as the
			 * original subquery.
			 */
			subquery = makeNode(Query);
			subquery->commandType = CMD_SELECT;
			subquery->querySource = QSRC_INSTEAD_RULE;
			subquery->targetList = NIL;

			foreach(cell, rte->subquery->targetList)
			{
				TargetEntry *tle;
				Var		   *var;

				tle = (TargetEntry *) lfirst(cell);
				var = makeVarFromTargetEntry(1, tle);

				tle = makeTargetEntry((Expr *) var,
									  list_length(subquery->targetList) + 1,
									  pstrdup(tle->resname),
									  tle->resjunk);
				subquery->targetList = lappend(subquery->targetList, tle);
			}

			subrte = makeNode(RangeTblEntry);
			subrte->rtekind = RTE_SUBQUERY;
			subrte->subquery = rte->subquery;
			subrte->security_barrier = rte->security_barrier;
			subrte->eref = copyObject(rte->eref);
			subrte->inFromCl = true;
			subquery->rtable = list_make1(subrte);

			subrtr = makeNode(RangeTblRef);
			subrtr->rtindex = 1;
			subquery->jointree = makeFromExpr(list_make1(subrtr), qual);
			subquery->hasSubLinks = checkExprHasSubLink(qual);

			rte->subquery = subquery;
			rte->security_barrier = true;

			break;

		default:
			elog(ERROR, "invalid range table entry for security barrier qual");
	}
}

/*
 * security_barrier_replace_vars -
 *	  Apply security barrier variable replacement to an expression tree.
 *
 * This also builds/updates a targetlist with entries for each replacement
 * variable that needs to be exposed by the security barrier subquery RTE.
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
 * nodes in-place.  The given expression tree should have been copied
 * earlier to ensure that no unwanted side-effects occur!
 */
static void
security_barrier_replace_vars(Node *node,
							  security_barrier_replace_vars_context *context)
{
	/*
	 * Must be prepared to start with a Query or a bare expression tree; if
	 * it's a Query, go straight to query_tree_walker to make sure that
	 * sublevels_up doesn't get incremented prematurely.
	 */
	if (node && IsA(node, Query))
		query_tree_walker((Query *) node,
						  security_barrier_replace_vars_walker,
						  (void *) context, 0);
	else
		security_barrier_replace_vars_walker(node, context);
}

static bool
security_barrier_replace_vars_walker(Node *node,
							  security_barrier_replace_vars_context *context)
{
	if (node == NULL)
		return false;

	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;

		/*
		 * Note that the same Var may be present in different lists, so we
		 * need to take care not to process it multiple times.
		 */
		if (var->varno == context->rt_index &&
			var->varlevelsup == context->sublevels_up &&
			!list_member_ptr(context->vars_processed, var))
		{
			/*
			 * Found a matching variable. Make sure that it is in the subquery
			 * targetlist and map its attno accordingly.
			 */
			AttrNumber	attno;
			ListCell   *l;
			TargetEntry *tle;
			char	   *attname;
			Var		   *newvar;

			/* Search for the base attribute in the subquery targetlist */
			attno = InvalidAttrNumber;
			foreach(l, context->targetlist)
			{
				tle = (TargetEntry *) lfirst(l);
				attno++;

				Assert(IsA(tle->expr, Var));
				if (((Var *) tle->expr)->varattno == var->varattno &&
					((Var *) tle->expr)->varcollid == var->varcollid)
				{
					/* Map the variable onto this subquery targetlist entry */
					var->varattno = var->varoattno = attno;
					/* Mark this var as having been processed */
					context->vars_processed = lappend(context->vars_processed, var);
					return false;
				}
			}

			/* Not in the subquery targetlist, so add it. Get its name. */
			if (var->varattno < 0)
			{
				Form_pg_attribute att_tup;

				att_tup = SystemAttributeDefinition(var->varattno,
										   context->rel->rd_rel->relhasoids);
				attname = NameStr(att_tup->attname);
			}
			else if (var->varattno == InvalidAttrNumber)
			{
				attname = "wholerow";
			}
			else if (var->varattno <= context->rel->rd_att->natts)
			{
				Form_pg_attribute att_tup;

				att_tup = context->rel->rd_att->attrs[var->varattno - 1];
				attname = NameStr(att_tup->attname);
			}
			else
			{
				elog(ERROR, "invalid attribute number %d in security_barrier_replace_vars", var->varattno);
			}

			/* New variable for subquery targetlist */
			newvar = copyObject(var);
			newvar->varno = newvar->varnoold = 1;
			newvar->varlevelsup = 0;

			attno = list_length(context->targetlist) + 1;
			tle = makeTargetEntry((Expr *) newvar,
								  attno,
								  pstrdup(attname),
								  false);

			context->targetlist = lappend(context->targetlist, tle);

			context->colnames = lappend(context->colnames,
										makeString(pstrdup(attname)));

			/* Update the outer query's variable */
			var->varattno = var->varoattno = attno;

			/* Remember this Var so that we don't process it again */
			context->vars_processed = lappend(context->vars_processed, var);
		}
		return false;
	}

	if (IsA(node, Query))
	{
		/* Recurse into subselects */
		bool		result;

		context->sublevels_up++;
		result = query_tree_walker((Query *) node,
								   security_barrier_replace_vars_walker,
								   (void *) context, 0);
		context->sublevels_up--;
		return result;
	}

	return expression_tree_walker(node, security_barrier_replace_vars_walker,
								  (void *) context);
}

{'repo_name': 'ADBSQL/AntDB', 'stars': '178', 'repo_language': 'C', 'file_name': 'create_extension.sgml', 'mime_type': 'text/html', 'hash': -3730407208032713168, 'source_dataset': 'data'}


/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2010-2017 Oracle and/or its affiliates. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License.  You can
 * obtain a copy of the License at
 * https://oss.oracle.com/licenses/CDDL+GPL-1.1
 * or LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at LICENSE.txt.
 *
 * GPL Classpath Exception:
 * Oracle designates this particular file as subject to the "Classpath"
 * exception as provided by Oracle in the GPL Version 2 section of the License
 * file that accompanied this code.
 *
 * Modifications:
 * If applicable, add the following below the License Header, with the fields
 * enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyright [year] [name of copyright owner]"
 *
 * Contributor(s):
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package com.acme;

import javax.ejb.*;
import javax.annotation.*;

import org.omg.CORBA.ORB;

@Stateless
    @EJB(name="java:global/GS1", beanName="HelloSingleton", beanInterface=Hello.class)
public class HelloStateless implements HelloRemote {

    @EJB(name="java:app/env/AS1", beanName="HelloSingleton")
    private Hello h;

    @Resource(name="java:module/MORB1")
    private ORB orb;

    @EJB(name="lookupref1", lookup="java:app/env/AS1")
    private Hello lookupref1;

    @EJB(name="lookupref2", lookup="java:global/GS1")
    private Hello lookupref2;

    @EJB(name="lookupref3", lookup="java:module/HelloStateless!com.acme.HelloRemote")
    private HelloRemote lookupref3;

    // declare component-level dependency using fully-qualified
    // java:comp/env form.
    @Resource(name="java:comp/env/foo") SessionContext sessionCtx;

    @PostConstruct
    private void init() {
	System.out.println("HelloStateless::init()");
    }

    public String hello() {
	System.out.println("In HelloStateless::hello()");

	String appName = (String) sessionCtx.lookup("java:app/AppName");
	String moduleName = (String) sessionCtx.lookup("java:module/ModuleName");
	System.out.println("AppName = " + appName);
	System.out.println("ModuleName = " + moduleName);

	ORB orb1 = (ORB) sessionCtx.lookup("java:module/MORB1");
	ORB orb2 = (ORB) sessionCtx.lookup("java:module/env/MORB2");

	Hello s1 = (Hello) sessionCtx.lookup("java:global/" +
					   appName + "/" +
					   moduleName + "/" +
					   "HelloSingleton");

	Hello s2 = (Hello) sessionCtx.lookup("java:app/" +
							 moduleName + "/" +
							 "HelloSingleton");

	// Rely on default to resolve "java:comp/env/ declared resource
	SessionContext sc1 = (SessionContext)
	    sessionCtx.lookup("foo");

	SessionContext sc2 = (SessionContext)
	    sc1.lookup("java:comp/env/foo");

	Integer envEntry = (Integer)
	    sc1.lookup("java:app/env/value1");
	System.out.println("java:ap/env/value1 = " + envEntry);

	return "hello, world!\n";
    }

    @PreDestroy
    private void destroy() {
	System.out.println("HelloStateless::destroy()");
    }

}

{'repo_name': 'javaee/glassfish', 'stars': '707', 'repo_language': 'Java', 'file_name': 'build.properties', 'mime_type': 'text/plain', 'hash': 8209769360420362517, 'source_dataset': 'data'}


--TEST--
GMP operator overloading
--SKIPIF--
<?php if (!extension_loaded("gmp")) print "skip"; ?>
--FILE--
<?php

$a = gmp_init(42);
$b = gmp_init(17);

var_dump($a + $b);
var_dump($a + 17);
var_dump(42 + $b);

var_dump($a - $b);
var_dump($a - 17);
var_dump(42 - $b);

var_dump($a * $b);
var_dump($a * 17);
var_dump(42 * $b);

var_dump($a / $b);
var_dump($a / 17);
var_dump(42 / $b);
try {
    var_dump($a / 0);
} catch (\DivisionByZeroError $e) {
    echo $e->getMessage() . \PHP_EOL;
}

var_dump($a % $b);
var_dump($a % 17);
var_dump(42 % $b);
try {
    var_dump($a % 0);
} catch (\DivisionByZeroError $e) {
    echo $e->getMessage() . \PHP_EOL;
}

var_dump($a ** $b);
var_dump($a ** 17);
var_dump(42 ** $b);

var_dump($a | $b);
var_dump($a | 17);
var_dump(42 | $b);

var_dump($a & $b);
var_dump($a & 17);
var_dump(42 & $b);

var_dump($a ^ $b);
var_dump($a ^ 17);
var_dump(42 ^ $b);

var_dump($a << $b);
var_dump($a << 17);
var_dump(42 << $b);

var_dump($a >> 2);
var_dump(-$a >> 2);

try {
    $a << -1;
} catch (ValueError $exception) {
    echo $exception->getMessage() . "\n";
}

try {
    $a >> -1;
} catch (ValueError $exception) {
    echo $exception->getMessage() . "\n";
}

var_dump(~$a);
var_dump(-$a);
var_dump(+$a);

var_dump($a == $b);
var_dump($a != $b);
var_dump($a < $b);
var_dump($a <= $b);
var_dump($a > $b);
var_dump($a >= $b);

var_dump($a == $a);
var_dump($a != $a);

var_dump($a == 42);
var_dump($a != 42);
var_dump($a < 42);
var_dump($a <= 42);
var_dump($a > 42);
var_dump($a >= 42);

try {
    var_dump($a == new stdClass);
} catch (\TypeError $e) {
    echo $e->getMessage() . \PHP_EOL;
}

$a += 1;
var_dump($a);
$a -= 1;
var_dump($a);

var_dump(++$a);
var_dump($a++);
var_dump($a);

var_dump(--$a);
var_dump($a--);
var_dump($a);

// Test operator that was not overloaded

var_dump($a . $b);
var_dump($a . '17');
var_dump('42' . $b);

$a .= '17';
var_dump($a);

?>
--EXPECT--
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "25"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "25"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "25"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(3) "714"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(3) "714"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(3) "714"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(1) "2"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(1) "2"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(1) "2"
}
Division by zero
object(GMP)#4 (1) {
  ["num"]=>
  string(1) "8"
}
object(GMP)#4 (1) {
  ["num"]=>
  string(1) "8"
}
object(GMP)#4 (1) {
  ["num"]=>
  string(1) "8"
}
Modulo by zero
object(GMP)#3 (1) {
  ["num"]=>
  string(28) "3937657486715347520027492352"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(28) "3937657486715347520027492352"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(28) "3937657486715347520027492352"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(1) "0"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(1) "0"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(1) "0"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "59"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(7) "5505024"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(7) "5505024"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(7) "5505024"
}
object(GMP)#3 (1) {
  ["num"]=>
  string(2) "10"
}
object(GMP)#5 (1) {
  ["num"]=>
  string(3) "-11"
}
Shift must be greater than or equal to 0
Shift must be greater than or equal to 0
object(GMP)#5 (1) {
  ["num"]=>
  string(3) "-43"
}
object(GMP)#5 (1) {
  ["num"]=>
  string(3) "-42"
}
object(GMP)#5 (1) {
  ["num"]=>
  string(2) "42"
}
bool(false)
bool(true)
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
main(): Argument #2 must be of type GMP|string|int, stdClass given
object(GMP)#4 (1) {
  ["num"]=>
  string(2) "43"
}
object(GMP)#1 (1) {
  ["num"]=>
  string(2) "42"
}
object(GMP)#4 (1) {
  ["num"]=>
  string(2) "43"
}
object(GMP)#4 (1) {
  ["num"]=>
  string(2) "43"
}
object(GMP)#1 (1) {
  ["num"]=>
  string(2) "44"
}
object(GMP)#4 (1) {
  ["num"]=>
  string(2) "43"
}
object(GMP)#4 (1) {
  ["num"]=>
  string(2) "43"
}
object(GMP)#1 (1) {
  ["num"]=>
  string(2) "42"
}
string(4) "4217"
string(4) "4217"
string(4) "4217"
string(4) "4217"

{'repo_name': 'php/php-src', 'stars': '27767', 'repo_language': 'C', 'file_name': 'echo.inc', 'mime_type': 'text/x-php', 'hash': -8983299163553739256, 'source_dataset': 'data'}


/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#ifndef BERRYCONTRIBUTIONITEM_H
#define BERRYCONTRIBUTIONITEM_H

#include "berryIContributionItem.h"

#include <org_blueberry_ui_qt_Export.h>

namespace berry {

/**
 * An abstract base implementation for contribution items.
 */
class BERRY_UI_QT ContributionItem : public IContributionItem
{

public:

  berryObjectMacro(ContributionItem);

  enum Mode {
    DEFAULT = 0x00,

    /**
     * Mode bit: Show text on tool items or buttons, even if an image is
     * present. If this mode bit is not set, text is only shown on tool items if
     * there is no image present.
     */
    MODE_FORCE_TEXT = 0x01
  };
  Q_DECLARE_FLAGS(Modes, Mode)

  enum Style {

    /**
     * A push button tool item or menu item.
     */
    STYLE_PUSH = 0x01,

    /**
     * A checked tool item or menu item.
     */
    STYLE_CHECK = 0x02,

    /**
     * A radio-button style menu item.
     */
    STYLE_RADIO = 0x04,

    /**
     * A ToolBar pulldown item.
     */
    STYLE_PULLDOWN = 0x08
  };

  /**
   * The default implementation of this IContributionItem
   * method does nothing. Subclasses may override.
   */
  void Fill(QStatusBar* parent) override;

  /**
   * The default implementation of this IContributionItem
   * method does nothing. Subclasses may override.
   */
  void Fill(QMenu* menu, QAction* before) override;

  /**
   * The default implementation of this IContributionItem
   * method does nothing. Subclasses may override.
   */
  void Fill(QMenuBar* menu, QAction* before) override;

  /**
   * The default implementation of this IContributionItem
   * method does nothing. Subclasses may override.
   */
  void Fill(QToolBar* parent, QAction* before) override;

  /**
   * The default implementation of this IContributionItem
   * method does nothing. Subclasses may override.
   */
  void SaveWidgetState() override;

  /*
   * Method declared on IContributionItem.
   */
  QString GetId() const override;

  /**
   * Returns the parent contribution manager, or null if this
   * contribution item is not currently added to a contribution manager.
   *
   * @return the parent contribution manager, or null
   */
  IContributionManager *GetParent() const;

  /**
   * The default implementation of this IContributionItem
   * method returns false. Subclasses may override.
   */
  bool IsDirty() const override;

  /**
   * The default implementation of this IContributionItem
   * method returns true. Subclasses may override.
   */
  bool IsEnabled() const override;

  /**
   * The default implementation of this IContributionItem
   * method returns false. Subclasses may override.
   */
  bool IsDynamic() const override;

  /**
   * The default implementation of this IContributionItem
   * method returns false. Subclasses may override.
   */
  bool IsGroupMarker() const override;

  /**
   * The default implementation of this IContributionItem
   * method returns false. Subclasses may override.
   */
  bool IsSeparator() const override;

  /**
   * The default implementation of this IContributionItem
   * method returns the value recorded in an internal state variable,
   * which is true by default. setVisible
   * should be used to change this setting.
   */
  bool IsVisible() const override;

  /**
   * The default implementation of this IContributionItem
   * method stores the value in an internal state variable,
   * which is true by default.
   */
  void SetVisible(bool visible) override;

  /**
   * Returns a string representation of this contribution item
   * suitable only for debugging.
   */
  QString ToString() const override;

  /**
   * The default implementation of this IContributionItem
   * method does nothing. Subclasses may override.
   */
  void Update() override;

  /*
   * Method declared on IContributionItem.
   */
  void SetParent(IContributionManager* parent) override;

  /**
   * The ContributionItem implementation of this
   * method declared on IContributionItem does nothing.
   * Subclasses should override to update their state.
   */
  void Update(const QString& id) override;

  /**
   * The ID for this contribution item. It should be set once either in the
   * constructor or using this method.
   *
   * @param itemId
   * @see #getId()
   */
  void SetId(const QString& itemId);

protected:

  /**
   * Creates a contribution item with a null id.
   * Calls this(String) with null.
   */
  ContributionItem();

  /**
   * Creates a contribution item with the given (optional) id.
   * The given id is used to find items in a contribution manager,
   * and for positioning items relative to other items.
   *
   * @param id the contribution item identifier, or null
   */
  ContributionItem(const QString& id);

private:

  /**
   * The identifier for this contribution item, of null if none.
   */
  QString id;

  /**
   * Indicates this item is visible in its manager; true
   * by default.
   */
  bool visible;

  /**
   * The parent contribution manager for this item
   */
  IContributionManager* parent;
};

}

#endif // BERRYCONTRIBUTIONITEM_H

{'repo_name': 'MITK/MITK', 'stars': '322', 'repo_language': 'C++', 'file_name': 'Overview.dox', 'mime_type': 'text/html', 'hash': 1157805706303535106, 'source_dataset': 'data'}


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Stop. haml time</title>

This is a title!

Lorem ipsum dolor sit amet, consectetur adipisicing elit

Cigarettes!

Man alive!

Slippers

Shoes

Bathrobe

Coffee

This is some text that's in a pre block!
      Let's see what happens when it's rendered! What about now, since we're on a new line?

{'repo_name': 'entp/seinfeld', 'stars': '117', 'repo_language': 'Ruby', 'file_name': 'show.haml', 'mime_type': 'text/html', 'hash': 1533929855172089008, 'source_dataset': 'data'}


const Command = require('../../structures/commands/AutoReply');

module.exports = class UnflipCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'unflip',
			group: 'auto',
			memberName: 'unflip',
			description: 'Unflips a flipped table.',
			patterns: [/\(╯°□°）╯︵ ┻━┻/i]
		});
	}

	generateText() {
		return '┬─┬ ノ( ゜-゜ノ)';
	}
};

{'repo_name': 'dragonfire535/xiao', 'stars': '154', 'repo_language': 'JavaScript', 'file_name': 'cleverbot.js', 'mime_type': 'text/plain', 'hash': -7942534730265144481, 'source_dataset': 'data'}


<?php

/*
 * This file is part of Psy Shell.
 *
 * (c) 2012-2018 Justin Hileman
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Psy\TabCompletion\Matcher;

/**
 * A constant name tab completion Matcher.
 *
 * This matcher provides completion for all defined constants.
 *
 * @author Marc Garcia <markcial@gmail.com>
 */
class ConstantsMatcher extends AbstractMatcher
{
    /**
     * {@inheritdoc}
     */
    public function getMatches(array $tokens, array $info = [])
    {
        $const = $this->getInput($tokens);

        return \array_filter(\array_keys(\get_defined_constants()), function ($constant) use ($const) {
            return AbstractMatcher::startsWith($const, $constant);
        });
    }

    /**
     * {@inheritdoc}
     */
    public function hasMatched(array $tokens)
    {
        $token     = \array_pop($tokens);
        $prevToken = \array_pop($tokens);

        switch (true) {
            case self::tokenIs($prevToken, self::T_NEW):
            case self::tokenIs($prevToken, self::T_NS_SEPARATOR):
                return false;
            case self::hasToken([self::T_OPEN_TAG, self::T_STRING], $token):
            case self::isOperator($token):
                return true;
        }

        return false;
    }
}

{'repo_name': 'wonderkun/CTF_web', 'stars': '527', 'repo_language': 'PHP', 'file_name': 'READMD.md', 'mime_type': 'text/x-python', 'hash': 6451030558789067672, 'source_dataset': 'data'}


/* Copyright (c) Colorado School of Mines, 1997.*/
/* All rights reserved.                       */

/* SUSORT: $Revision: 1.24 $ ; $Date: 1996/09/18 19:47:27 $	*/

#include "su.h"
#include "segy.h"
#include <signal.h>

/*********************** self documentation **********************/
char *sdoc[] = {
" 								",
" SUSORT - sort on any segy header keywords			",
" 								",
" susort <stdin >stdout [[+-]key1 [+-]key2 ...]			",
" 								",
" Susort supports any number of (secondary) keys with either	",
" ascending (+, the default) or descending (-) directions for 	",
" each.  The default sort key is cdp.				",
" 								",
" Note:	Only the following types of input/output are supported	",
"	Disk input --> any output				",
"	Pipe input --> Disk output				",
" 								",
" Note: If the the CWP_TMPDIR environment variable is set use	",
"	its value for the path; else use tmpfile()		",
" 								",
" Example:							",
" To sort traces by cdp gather and within each gather		",
" by offset with both sorts in ascending order:			",
" 								",
" 	susort <INDATA >OUTDATA cdp offset			",
" 								",
" Caveat: In the case of Pipe input a temporary file is made	",
"	to hold the ENTIRE data set.  This temporary is		",
"	either an actual disk file (usually in /tmp) or in some	",
"	implementations, a memory buffer.  It is left to the	",
"	user to be SENSIBLE about how big a file to pipe into	",
"	susort relative to the user's computer.			",
" 								",
NULL};

/* Credits:
 *	SEP: Einar, Stew
 *	CWP: Shuki, Jack
 *        : Zhiming
 *
 * Caveats:
 *	Since the algorithm depends on sign reversal of the key value
 *	to obtain a descending sort, the most significant figure may
 *	be lost for unsigned data types.  The old SEP support for tape
 *	input was removed in version 1.16---version 1.15 is in the
 *	Portability directory for those who may want to input SU data
 *	stored on tape.
 *
 */
/**************** end self doc ***********************************/

#define NTRSTEP	1024	/* realloc() increment measured in traces */

segychdr ch;
segybhdr bh;
segy tr;
static int nkey;	/* number of keys to sort on	*/
static String type;	/* header key types		*/

/* Prototypes */
Value negval(String type, Value val);   /* reverse sign of value	*/
int cmp_list();				/* qsort comparison function	*/
static void closefiles(void);		/* signal handler		*/

/* Globals (so can trap signal) defining temporary disk files */
char tracefile[BUFSIZ];	/* filename for trace storage file	*/
FILE *tracefp;		/* fp for trace storage file		*/

int
main(int argc, char **argv)
{
	static Value *val_list;	/* a list of the key values for each    */
				/* trace with each group headed by the	*/
				/* trace number of that trace		*/
	static int *index;	/* header key indices			*/
  	static bool *up;	/* sort direction (+ = up = ascending)	*/
	register Value *vptr;	/* location pointer for val_list	*/
	int ngroup;		/* size of unit in val_list (nkey + 1)	*/
	int nv;			/* number of groups in val_list		*/
	int nvsize;		/* size of group in val_list		*/
  	Value val;		/* value of a keyword			*/
	long ntr;		/* number of traces from gettr		*/
	long itr;		/* index of trace (0,1,2,...)		*/
	filetype ftypein;	/* filetype of stdin			*/
	filetype ftypeout;	/* filetype of stdout			*/
	int nsegy;		/* number of bytes on the trace		*/
	int ispipe=0;	/* ftypein == PIPE ?			*/
	int isdisk=0;	/* ftypein == DISK ?			*/
	char *tmpdir;		/* directory path for tmp files		*/
	int istmpdir=0;/* true for user given path		*/

	long long loffset;
	int i;

	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);

	/* Look for user-supplied tmpdir form environment */
	if (!(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
	if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
		err("you can't write in %s (or it doesn't exist)", tmpdir);

	/* The algorithm requires stdin to be rewound and */
	/* random access to either stdin or stdout.    */
	ftypein = filestat(STDIN);
	ftypeout = filestat(STDOUT);
	if( ftypein == DISK ) isdisk = 1;
	if( ftypein == PIPE || ftypein == FIFO ) ispipe = 1;

	if( ispipe == 0 && isdisk ==0 ) isdisk = 1;

	if (ispipe && ftypeout != DISK)
		err("OK IO types are: DISK->ANYTHING, PIPE->DISK");

	/* If pipe, prepare temporary file to hold data */
	if (ispipe==1) {
		if (STREQ(tmpdir,"")) {
			tracefp = etempfile(NULL);
		} else {	/* user-supplied tmpdir from environment */
			tracefp = etempfile(tmpdir);
		}
	}
	/* Set number of sort keys */
	if (argc == 1) nkey = 1; /* no explicit keys: default cdp key */
	else  nkey = argc - 1;   /* one or more explicit keys */

	/* Allocate lists for key indices, sort directions and key types */
	index = ealloc1int(nkey);
  	up = (bool *) ealloc1(nkey, sizeof(bool));
	type = (char *) ealloc1(nkey, sizeof(char));

	/* Initialize index, type and up */
	if (argc == 1) {
		index[0] = getindex("cdp");
		up[0] = true;
		type[0] = 'l';
	} else {
		for (i = 0; i < nkey; ++i) {
			switch (**++argv) { /* sign char of next arg */
			case '+':
				up[i] = true;
				++*argv;   /* discard sign char in arg */
			break;
			case '-':
				up[i] = false;
				++*argv;   /* discard sign char in arg */
			break;
			default:
				up[i] = true;
			break;
			}
			index[i] = getindex(*argv);
			type[i] = hdtype(*argv)[0]; /* need single char */
		}
	}

	/* Allocate list of trace numbers + key values */
	ngroup = nkey + 1;
	nvsize = ngroup*sizeof(Value);
	nv = NTRSTEP;  /* guess at required number */
	val_list = (Value *) ealloc1(nv, nvsize);
	vptr = val_list;

	/* allow large file access */
	fseek64(stdin,0,1);
	fseek64(stdout,0,1);
	if(ispipe==1) fseek64(tracefp,0,1);

	/* Run through traces once to collect header values */
	ntr = 0;
	if (!(nsegy = gettr(&tr)))  err("can't get first trace");

	do {
		itr = ntr++;
		/* realloc if out of room */
		if (0 == (ntr % NTRSTEP)) {
			nv += NTRSTEP;
			val_list = (Value *) erealloc(val_list, nv*nvsize);
			vptr = val_list + itr * ngroup;
		}

		/* enter trace index in list and then key values */
		vptr++->l = itr;	/* insert number and advance */

	 	for (i = 0; i < nkey; ++i) {
			gethval(&tr, index[i], &val);
			*vptr++ = up[i] ? val : negval(type + i, val);
				/* negative values give reverse sort */
	 	}

		if (ispipe==1) efwrite((char *)&tr, 1, nsegy, tracefp);
	} while (gettr(&tr));

	if (ispipe==1)  rewind(tracefp);
	else /* disk */	  rewind(stdin);

	/* Sort the headers values */
	qsort(val_list, ntr, nvsize, cmp_list);

	if (isdisk==1) {
		/* run through sorted list and write output sequentially */

		for (i = 0; i < ntr; ++i) {

			itr = val_list[i*ngroup].l;
			gtra64(&tr, itr);
			/*
			tr.tracl = tr.tracr = i + 1;
			*/
			puttr(&tr);
		}
	} else /* pipe */ {
		/* invert permutation and read input sequentially */
		for (i = 0; i < ntr; ++i) {
			itr = val_list[i*ngroup].l;
			val_list[itr*ngroup + 1].l = i;
	        }
		for (i = 0; i < ntr; ++i) {
			itr = val_list[i*ngroup + 1].l;
			efread(&tr, 1, nsegy, tracefp);
			/*
			tr.tracl = tr.tracr = itr + 1;
			*/
			loffset = itr;
			loffset = loffset * nsegy;
			fseek64(stdout, itr*nsegy, SEEK_SET);
			fwrite(&tr, 1, nsegy, stdout);
		}
	}

	/* Clean up */
	if (ispipe==1) {
		efclose(tracefp);
	}

	return EXIT_SUCCESS;
}

/* Comparison routine for qsort */
int cmp_list(register Value *a, register Value *b)
{
	register int i;
	Value va, vb;
	int compare;

	/* Can order as soon as any components are unequal */
	for (i = 0; i < nkey; ++i) {
		va = *++a; vb = *++b; /* advance and dereference */
		if ((compare = valcmp(type + i, va, vb)))
			return compare;
        }
        return 0;
}

/* Reverse sign of value */
Value negval(String type, Value val)
{
	switch (*type) {
	case 'h':
		val.h = -val.h;
	break;
	case 'u':
		val.u = (short) -val.u;
	break;
	case 'l':
		val.l = -val.l;
	break;
	case 'v':
		val.u = (long) -val.u;
	break;
	case 'i':
		val.i = -val.i;
	break;
	case 'p':
		val.p = (int) -val.p;
	break;
	case 'f':
		val.f = -val.f;
	break;
	case 'd':
		val.d = -val.d;
	break;
	default: err("%d: mysterious type %s", __LINE__, type);
	}

	return val;
}

/* for graceful interrupt termination */
static void closefiles(void)
{
	efclose(tracefp);
	eremove(tracefile);
	exit(EXIT_FAILURE);
}

{'repo_name': 'JohnWStockwellJr/SeisUnix', 'stars': '153', 'repo_language': 'C', 'file_name': 'tetramod', 'mime_type': 'text/plain', 'hash': 9058689032865352588, 'source_dataset': 'data'}


/* Editor Settings: expandtabs and use 4 spaces for indentation
 * ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
 * -*- mode: c, c-basic-offset: 4 -*- */

/*
 * Copyright © BeyondTrust Software 2004 - 2019
 * All rights reserved.
 *
 * 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.
 *
 * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
 * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
 * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
 * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
 * NOTWITHSTANDING THE ABOVE NOTICE.  IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
 * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
 * BEYONDTRUST AT beyondtrust.com/contact
 */

#ifndef __DJ_ITF_H__
#define __DJ_ITF_H__

#ifdef __cplusplus
extern "C" {
#endif

typedef struct __DOMAIN_JOIN_INFO
{
    char* pszName;
    char* pszDnsDomain;
    char* pszDomainName;      /* Null if not joined  */
    char* pszDomainShortName; /* Null if not joined  */
    char* pszLogFilePath;     /* Null if not logging */
    char* pszOU;              /* Null if not joined  */

} DOMAIN_JOIN_INFO, *PDOMAIN_JOIN_INFO;

typedef struct __DOMAIN_JOIN_ERROR
{

    int  code;
    char* pszShortError;
    char* pszLongError;

} DOMAIN_JOIN_ERROR, *PDOMAIN_JOIN_ERROR;

typedef int (*PFNJoinDomain)(
                const char*         pszDomainName,
                const char*         pszOU,
                const char*         pszUsername,
                const char*         pszPassword,
                short               bNoHosts,
                PDOMAIN_JOIN_ERROR* ppError
                );

typedef int (*PFNLeaveDomain)(
                const char*         pszUsername,
                const char*         pszPassword,
                PDOMAIN_JOIN_ERROR* ppError
                );

typedef int (*PFNSetComputerName)(
                const char*         pszComputerName,
                const char*         pszDomainName,
                PDOMAIN_JOIN_ERROR* ppError
                );

typedef int (*PFNQueryInformation)(
                PDOMAIN_JOIN_INFO*  ppDomainJoinInfo,
                PDOMAIN_JOIN_ERROR* ppError
                );

typedef int (*PFNIsDomainNameResolvable)(
                const char*         pszDomainName,
                short*              pbIsResolvable,
                PDOMAIN_JOIN_ERROR* ppszError
                );

typedef void (*PFNFreeDomainJoinInfo)(
                PDOMAIN_JOIN_INFO pDomainJoinInfo
                );

typedef void (*PFNFreeDomainJoinError)(
                PDOMAIN_JOIN_ERROR pError
                );

#ifdef __cplusplus
}
#endif

typedef struct __DJ_API_FUNCTION_TABLE
{
    PFNJoinDomain             pfnJoinDomain;
    PFNLeaveDomain            pfnLeaveDomain;
    PFNSetComputerName        pfnSetComputerName;
    PFNQueryInformation       pfnQueryInformation;
    PFNIsDomainNameResolvable pfnIsDomainNameResolvable;
    PFNFreeDomainJoinInfo     pfnFreeDomainJoinInfo;
    PFNFreeDomainJoinError    pfnFreeDomainJoinError;

} DJ_API_FUNCTION_TABLE, *PDJ_API_FUNCTION_TABLE;

#define DJ_INITIALIZE_JOIN_INTERFACE "DJInitJoinInterface"

typedef int (*PFNInitJoinInterface)(
                 PDJ_API_FUNCTION_TABLE* ppFuncTable
                 );

int
DJInitJoinInterface(
    PDJ_API_FUNCTION_TABLE* ppFuncTable
    );

#define DJ_SHUTDOWN_JOIN_INTERFACE   "DJShutdownJoinInterface"

typedef void (*PFNShutdownJoinInterface)(
                PDJ_API_FUNCTION_TABLE pFuncTable
                );

void
DJShutdownJoinInterface(
    PDJ_API_FUNCTION_TABLE pFuncTable
    );

#endif /* __DJ_ITF_H__ */

{'repo_name': 'BeyondTrust/pbis-open', 'stars': '280', 'repo_language': 'C', 'file_name': 'com_err.h', 'mime_type': 'text/x-c', 'hash': 2862489253833184637, 'source_dataset': 'data'}


<meta charset="UTF-8">
<title>GAFinalResponse.toGenericMessage - tock</title>
<link rel="stylesheet" href="../../../style.css">

tock / ai.tock.bot.connector.ga.model.response / GAFinalResponse / toGenericMessage

toGenericMessage

fun toGenericMessage(): GenericMessage? (source)

{'repo_name': 'theopenconversationkit/tock', 'stars': '129', 'repo_language': 'Kotlin', 'file_name': 'MongoCacheData_Serializer.kt', 'mime_type': 'text/plain', 'hash': -8098904818837682349, 'source_dataset': 'data'}


using FakeItEasy;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.Collections.Generic;

namespace FakeXrmEasy
{
    public partial class XrmFakedContext : IXrmContext
    {
        public XrmFakedWorkflowContext GetDefaultWorkflowContext()
        {
            var userId = CallerId?.Id ?? Guid.NewGuid();
            Guid businessUnitId = BusinessUnitId?.Id ?? Guid.NewGuid();

            return new XrmFakedWorkflowContext
            {
                Depth = 1,
                IsExecutingOffline = false,
                MessageName = "Create",
                UserId = userId,
                BusinessUnitId = businessUnitId,
                InitiatingUserId = userId,
                InputParameters = new ParameterCollection(),
                OutputParameters = new ParameterCollection(),
                SharedVariables = new ParameterCollection(),
                PreEntityImages = new EntityImageCollection(),
                PostEntityImages = new EntityImageCollection()
            };
        }

        /// <summary>
        /// Executes a code activity against this context
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public IDictionary<string, object> ExecuteCodeActivity<T>(Dictionary<string, object> inputs, T instance = null)
            where T : CodeActivity, new()
        {
            var wfContext = GetDefaultWorkflowContext();
            return this.ExecuteCodeActivity(wfContext, inputs, instance);
        }

        public IDictionary<string, object> ExecuteCodeActivity<T>(Entity primaryEntity, Dictionary<string, object> inputs = null, T instance = null)
            where T : CodeActivity, new()
        {
            var wfContext = GetDefaultWorkflowContext();
            wfContext.PrimaryEntityId = primaryEntity.Id;
            wfContext.PrimaryEntityName = primaryEntity.LogicalName;

            if (inputs == null)
            {
                inputs = new Dictionary<string, object>();
            }

            return this.ExecuteCodeActivity(wfContext, inputs, instance);
        }

        /// <summary>
        /// Executes a code activity passing the primary entity
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public IDictionary<string, object> ExecuteCodeActivity<T>(XrmFakedWorkflowContext wfContext, Dictionary<string, object> inputs = null, T instance = null)
            where T : CodeActivity, new()
        {
            var debugText = "";
            try
            {
                debugText = "Creating instance..." + Environment.NewLine;
                if (instance == null)
                {
                    instance = new T();
                }
                var invoker = new WorkflowInvoker(instance);
                debugText += "Invoker created" + Environment.NewLine;
                debugText += "Adding extensions..." + Environment.NewLine;
                invoker.Extensions.Add<ITracingService>(() => TracingService);
                invoker.Extensions.Add<IWorkflowContext>(() => wfContext);
                invoker.Extensions.Add(() =>
                {
                    var fakedServiceFactory = A.Fake<IOrganizationServiceFactory>();
                    A.CallTo(() => fakedServiceFactory.CreateOrganizationService(A<Guid?>._)).ReturnsLazily((Guid? g) => GetOrganizationService());
                    return fakedServiceFactory;
                });

                debugText += "Adding extensions...ok." + Environment.NewLine;
                debugText += "Invoking activity..." + Environment.NewLine;

                if (inputs == null)
                {
                    inputs = new Dictionary<string, object>();
                }

                return invoker.Invoke(inputs);
            }
            catch (TypeLoadException exception)
            {
                var typeName = exception.TypeName != null ? exception.TypeName : "(null)";
                throw new TypeLoadException($"When loading type: {typeName}.{exception.Message}in domain directory: {AppDomain.CurrentDomain.BaseDirectory}\nDebug={debugText}");
            }
        }
    }
}

{'repo_name': 'jordimontana82/fake-xrm-easy', 'stars': '182', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': 6374221036019222354, 'source_dataset': 'data'}


# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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.

"""Script to compute and store the learned representation for Cifar10/100.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
from absl import app
import numpy as np
import tensorflow.compat.v1 as tf

from uncertainties.sources.cifar.cifar_input_python import load_data
from uncertainties.sources.cifar.network_cifar import NetworkCifar

# TO BE CHANGED, baseroute folder

PATH_MODEL = 'baseroute/models/cifar100/model'
DATA_PATH = 'baseroute/data/cifar100_data/cifar-100-python/'

def main(argv):
  """Main function."""

  del argv

  dataset = load_data(distorted=True, data_path=DATA_PATH, dataset='cifar100')
  (x_train_distorted, _), (x_test_distorted, _) = dataset
  dataset = load_data(distorted=False, data_path=DATA_PATH, dataset='cifar100')
  (x_train, _), (x_test, _) = dataset
  model = NetworkCifar()
  features = model.features(x_train)
  str_file = 'features_ll_train.npy'
  data_path = os.path.join(PATH_MODEL, str_file)
  with tf.gfile.Open(data_path, 'wb') as f:
    np.save(f, features)
  features = model.features(x_train_distorted)
  str_file = 'features_ll_train_distorted.npy'
  data_path = os.path.join(PATH_MODEL, str_file)
  with tf.gfile.Open(data_path, 'wb') as f:
    np.save(f, features)
  features = model.features(x_test)
  str_file = 'features_ll_test.npy'
  data_path = os.path.join(PATH_MODEL, str_file)
  with tf.gfile.Open(data_path, 'wb') as f:
    np.save(f, features)
  features = model.features(x_test_distorted)
  str_file = 'features_ll_test_distorted.npy'
  data_path = os.path.join(PATH_MODEL, str_file)
  with tf.gfile.Open(data_path, 'wb') as f:
    np.save(f, features)

if __name__ == '__main__':
  app.run(main)

{'repo_name': 'google-research/google-research', 'stars': '11478', 'repo_language': 'Jupyter Notebook', 'file_name': 'location.pytxt', 'mime_type': 'text/plain', 'hash': 4888338421329024998, 'source_dataset': 'data'}


Here is the reference code for the Binary Heap Implementation. Make sure to refer to the video lecture for the full explanation!

**The basic operations we will implement for our binary heap are as follows:**

* BinaryHeap() creates a new, empty, binary heap.

* insert(k) adds a new item to the heap.

* findMin() returns the item with the minimum key value, leaving item in the heap.

* delMin() returns the item with the minimum key value, removing the item from the heap.

* isEmpty() returns true if the heap is empty, false otherwise.

* size() returns the number of items in the heap.

* buildHeap(list) builds a new heap from a list of keys.

if self.heapList[i] < self.heapList[i // 2]:

self.heapList[i // 2] = self.heapList[i]

if self.heapList[i] > self.heapList[mc]:

if self.heapList[i*2] < self.heapList[i*2+1]:

{'repo_name': 'jmportilla/Python-for-Algorithms--Data-Structures--and-Interviews', 'stars': '1437', 'repo_language': 'Jupyter Notebook', 'file_name': 'String Compression -checkpoint.ipynb', 'mime_type': 'text/plain', 'hash': -1231147429851695926, 'source_dataset': 'data'}


<?php

class Swift_Mime_AttachmentAcceptanceTest extends \PHPUnit_Framework_TestCase
{
    private $_contentEncoder;
    private $_cache;
    private $_grammar;
    private $_headers;

    protected function setUp()
    {
        $this->_cache = new Swift_KeyCache_ArrayKeyCache(
            new Swift_KeyCache_SimpleKeyCacheInputStream()
            );
        $factory = new Swift_CharacterReaderFactory_SimpleCharacterReaderFactory();
        $this->_contentEncoder = new Swift_Mime_ContentEncoder_Base64ContentEncoder();

        $headerEncoder = new Swift_Mime_HeaderEncoder_QpHeaderEncoder(
            new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8')
            );
        $paramEncoder = new Swift_Encoder_Rfc2231Encoder(
            new Swift_CharacterStream_ArrayCharacterStream($factory, 'utf-8')
            );
        $this->_grammar = new Swift_Mime_Grammar();
        $this->_headers = new Swift_Mime_SimpleHeaderSet(
            new Swift_Mime_SimpleHeaderFactory($headerEncoder, $paramEncoder, $this->_grammar)
            );
    }

    public function testDispositionIsSetInHeader()
    {
        $attachment = $this->_createAttachment();
        $attachment->setContentType('application/pdf');
        $attachment->setDisposition('inline');
        $this->assertEquals(
            'Content-Type: application/pdf'."\r\n".
            'Content-Transfer-Encoding: base64'."\r\n".
            'Content-Disposition: inline'."\r\n",
            $attachment->toString()
            );
    }

    public function testDispositionIsAttachmentByDefault()
    {
        $attachment = $this->_createAttachment();
        $attachment->setContentType('application/pdf');
        $this->assertEquals(
            'Content-Type: application/pdf'."\r\n".
            'Content-Transfer-Encoding: base64'."\r\n".
            'Content-Disposition: attachment'."\r\n",
            $attachment->toString()
            );
    }

    public function testFilenameIsSetInHeader()
    {
        $attachment = $this->_createAttachment();
        $attachment->setContentType('application/pdf');
        $attachment->setFilename('foo.pdf');
        $this->assertEquals(
            'Content-Type: application/pdf; name=foo.pdf'."\r\n".
            'Content-Transfer-Encoding: base64'."\r\n".
            'Content-Disposition: attachment; filename=foo.pdf'."\r\n",
            $attachment->toString()
            );
    }

    public function testSizeIsSetInHeader()
    {
        $attachment = $this->_createAttachment();
        $attachment->setContentType('application/pdf');
        $attachment->setSize(12340);
        $this->assertEquals(
            'Content-Type: application/pdf'."\r\n".
            'Content-Transfer-Encoding: base64'."\r\n".
            'Content-Disposition: attachment; size=12340'."\r\n",
            $attachment->toString()
            );
    }

    public function testMultipleParametersInHeader()
    {
        $attachment = $this->_createAttachment();
        $attachment->setContentType('application/pdf');
        $attachment->setFilename('foo.pdf');
        $attachment->setSize(12340);
        $this->assertEquals(
            'Content-Type: application/pdf; name=foo.pdf'."\r\n".
            'Content-Transfer-Encoding: base64'."\r\n".
            'Content-Disposition: attachment; filename=foo.pdf; size=12340'."\r\n",
            $attachment->toString()
            );
    }

    public function testEndToEnd()
    {
        $attachment = $this->_createAttachment();
        $attachment->setContentType('application/pdf');
        $attachment->setFilename('foo.pdf');
        $attachment->setSize(12340);
        $attachment->setBody('abcd');
        $this->assertEquals(
            'Content-Type: application/pdf; name=foo.pdf'."\r\n".
            'Content-Transfer-Encoding: base64'."\r\n".
            'Content-Disposition: attachment; filename=foo.pdf; size=12340'."\r\n".
            "\r\n".
            base64_encode('abcd'),
            $attachment->toString()
            );
    }

    protected function _createAttachment()
    {
        $entity = new Swift_Mime_Attachment(
            $this->_headers,
            $this->_contentEncoder,
            $this->_cache,
            $this->_grammar
            );

        return $entity;
    }
}

{'repo_name': 'bestmomo/laravel5-example', 'stars': '1201', 'repo_language': 'HTML', 'file_name': 'ie10-viewport-bug-workaround.js', 'mime_type': 'text/plain', 'hash': -9296410468812701, 'source_dataset': 'data'}


package gyro.lang;

import org.antlr.v4.runtime.Token;

public class EscapeException extends RuntimeException {

    private final String escape;
    private final Token token;

    public EscapeException(String escape, Token token) {
        this.escape = escape;
        this.token = token;
    }

    public Token getToken() {
        return token;
    }

    @Override
    public String getMessage() {
        return String.format("@|bold %s|@ isn't a valid escape character!", escape);
    }

}

{'repo_name': 'perfectsense/gyro', 'stars': '123', 'repo_language': 'Java', 'file_name': 'TestResource.java', 'mime_type': 'text/x-java', 'hash': -4394459070915022136, 'source_dataset': 'data'}


<?php

final class PholioMockThumbGridView extends AphrontView {

  private $mock;

  public function setMock(PholioMock $mock) {
    $this->mock = $mock;
    return $this;
  }

  public function render() {
    $mock = $this->mock;

    $all_images = $mock->getImages();
    $all_images = mpull($all_images, null, 'getPHID');

    $history = mpull($all_images, 'getReplacesImagePHID', 'getPHID');

    $replaced = array();
    foreach ($history as $phid => $replaces_phid) {
      if ($replaces_phid) {
        $replaced[$replaces_phid] = true;
      }
    }

    // Figure out the columns. Start with all the active images.
    $images = mpull($mock->getActiveImages(), null, 'getPHID');

    // Now, find deleted images: obsolete images which were not replaced.
    foreach ($mock->getImages() as $image) {
      if (!$image->getIsObsolete()) {
        // Image is current.
        continue;
      }

      if (isset($replaced[$image->getPHID()])) {
        // Image was replaced.
        continue;
      }

      // This is an obsolete image which was not replaced, so it must be
      // a deleted image.
      $images[$image->getPHID()] = $image;
    }

    $cols = array();
    $depth = 0;
    foreach ($images as $image) {
      $phid = $image->getPHID();

      $col = array();

      // If this is a deleted image, null out the final column.
      if ($image->getIsObsolete()) {
        $col[] = null;
      }

      $col[] = $phid;
      while ($phid && isset($history[$phid])) {
        $col[] = $history[$phid];
        $phid = $history[$phid];
      }

      $cols[] = $col;
      $depth = max($depth, count($col));
    }

    $grid = array();
    $jj = $depth;
    for ($ii = 0; $ii < $depth; $ii++) {
      $row = array();
      if ($depth == $jj) {
        $row[] = phutil_tag(
          'th',
          array(
            'valign' => 'middle',
            'class' => 'pholio-history-header',
          ),
          pht('Current Revision'));
      } else {
        $row[] = phutil_tag('th', array(), null);
      }
      foreach ($cols as $col) {
        if (empty($col[$ii])) {
          $row[] = phutil_tag('td', array(), null);
        } else {
          $thumb = $this->renderThumbnail($all_images[$col[$ii]]);
          $row[] = phutil_tag('td', array(), $thumb);
        }
      }
      $grid[] = phutil_tag('tr', array(), $row);
      $jj--;
    }

    $grid = phutil_tag(
      'table',
      array(
        'id' => 'pholio-mock-thumb-grid',
        'class' => 'pholio-mock-thumb-grid',
      ),
      $grid);

    $grid = id(new PHUIBoxView())
      ->addClass('pholio-mock-thumb-grid-container')
      ->appendChild($grid);

    return id(new PHUIObjectBoxView())
      ->setHeaderText(pht('Mock History'))
      ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
      ->appendChild($grid);
  }

  private function renderThumbnail(PholioImage $image) {
    $thumbfile = $image->getFile();

    $preview_key = PhabricatorFileThumbnailTransform::TRANSFORM_THUMBGRID;
    $xform = PhabricatorFileTransform::getTransformByKey($preview_key);
    Javelin::initBehavior('phabricator-tooltips');

    $attributes = array(
      'class' => 'pholio-mock-thumb-grid-image',
      'src' => $thumbfile->getURIForTransform($xform),
    );

    if ($image->getFile()->isViewableImage()) {
      $dimensions = $xform->getTransformedDimensions($thumbfile);
      if ($dimensions) {
        list($x, $y) = $dimensions;
        $attributes += array(
          'width' => $x,
          'height' => $y,
          'style' => 'top: '.floor((100 - $y) / 2).'px',
        );
      }
    } else {
      // If this is a PDF or a text file or something, we'll end up using a
      // generic thumbnail which is always sized correctly.
      $attributes += array(
        'width' => 100,
        'height' => 100,
      );
    }

    $tag = phutil_tag('img', $attributes);

    $classes = array('pholio-mock-thumb-grid-item');
    if ($image->getIsObsolete()) {
      $classes[] = 'pholio-mock-thumb-grid-item-obsolete';
    }

    $inline_count = null;
    if ($image->getInlineComments()) {
      $inline_count[] = phutil_tag(
        'span',
        array(
          'class' => 'pholio-mock-thumb-grid-comment-count',
        ),
        pht('%s', phutil_count($image->getInlineComments())));
    }

    return javelin_tag(
      'a',
      array(
        'sigil' => 'mock-thumbnail has-tooltip',
        'class' => implode(' ', $classes),
        'href' => '#',
        'meta' => array(
          'imageID' => $image->getID(),
          'tip' => $image->getName(),
          'align' => 'N',
        ),
      ),
      array(
        $tag,
        $inline_count,
      ));
  }

}

{'repo_name': 'phacility/phabricator', 'stars': '11612', 'repo_language': 'PHP', 'file_name': 'jsShrink.php', 'mime_type': 'text/x-php', 'hash': -1525159120327005266, 'source_dataset': 'data'}


/*
 * This file is part of budgie-desktop
 *
 * Copyright © 2015-2019 Budgie Desktop Developers
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */

const string MIXER_NAME = "Budgie Volume Control";

public class SoundIndicator : Gtk.Bin {
	/** Current image to display */
	public Gtk.Image widget { protected set; public get; }

	/** Our mixer */
	public Gvc.MixerControl mixer { protected set ; public get ; }

	public uint32 unmuted_volume_val = 0;

	/** Default stream */
	private Gvc.MixerStream? stream;

	/** EventBox for popover management */
	public Gtk.EventBox? ebox;

	/** GtkPopover in which to show a volume control */
	public Budgie.Popover popover;

	/** Display scale for le volume controls */
	private Gtk.Scale volume_scale;

	private double step_size;
	private ulong notify_id;

	/** Track the scale value_changed to prevent cross-noise */
	private ulong scale_id;

	public SoundIndicator() {
		// Start off with at least some icon until we connect to pulseaudio */
		widget = new Gtk.Image.from_icon_name("audio-volume-muted-symbolic", Gtk.IconSize.MENU);
		ebox = new Gtk.EventBox();
		ebox.add(widget);
		ebox.margin = 0;
		ebox.border_width = 0;
		add(ebox);

		mixer = new Gvc.MixerControl(MIXER_NAME);
		mixer.state_changed.connect(on_state_change);
		mixer.default_sink_changed.connect(on_sink_changed);
		mixer.open();

		/* Sort out our popover */
		this.create_sound_popover();

		this.get_style_context().add_class("sound-applet");
		this.popover.get_style_context().add_class("sound-popover");

		/* Catch scroll wheel events */
		ebox.add_events(Gdk.EventMask.SCROLL_MASK);
		ebox.add_events(Gdk.EventMask.BUTTON_RELEASE_MASK);
		ebox.scroll_event.connect(on_scroll_event);
		ebox.button_release_event.connect(on_button_release_event);
		show_all();
	}

	private bool on_button_release_event(Gdk.EventButton e) {
		if (e.button == Gdk.BUTTON_MIDDLE) { // Middle click
			/**
			 * You're probably wonder "hey, why aren't you using set_is_muted and get_is_muted"?
			 * Great question. It doesn't work for toggling these values. Simple.
			 */
			bool is_muted = stream.get_volume() == 0;

			if (is_muted) { // If we're muted
				stream.set_volume(unmuted_volume_val); // Used our old value
			} else {
				stream.set_volume(0); // Set to 0
			}

			Gvc.push_volume(stream);
		} else {
			return Gdk.EVENT_PROPAGATE;
		}

		return Gdk.EVENT_STOP;
	}

	/**
	 * Create the GtkPopover to display on primary click action, with an adjustable
	 * scale
	 */
	private void create_sound_popover() {
		popover = new Budgie.Popover(ebox);
		Gtk.Box? main_box = new Gtk.Box(Gtk.Orientation.VERTICAL, 0);
		main_box.border_width = 6;
		Gtk.Box? popover_box = new Gtk.Box(Gtk.Orientation.HORIZONTAL, 0);
		main_box.pack_start(popover_box, false, false, 0);
		popover.add(main_box);
		Gtk.Button? sub_button = new Gtk.Button.from_icon_name("list-remove-symbolic", Gtk.IconSize.BUTTON);
		Gtk.Button? plus_button = new Gtk.Button.from_icon_name("list-add-symbolic", Gtk.IconSize.BUTTON);

		/* - button */
		popover_box.pack_start(sub_button, false, false, 1);
		sub_button.clicked.connect(()=> {
			adjust_volume_increment(-step_size);
		});

		volume_scale = new Gtk.Scale.with_range(Gtk.Orientation.HORIZONTAL, 0, 100, 1);
		popover_box.pack_start(volume_scale, false, false, 0);

		/* Hook up the value_changed event */
		scale_id = volume_scale.value_changed.connect(on_scale_changed);

		/* + button */
		popover_box.pack_start(plus_button, false, false, 1);
		plus_button.clicked.connect(()=> {
			adjust_volume_increment(+step_size);
		});

		/* Refine visual appearance of the scale.. */
		volume_scale.set_draw_value(false);
		volume_scale.set_size_request(140, -1);

		/* Flat buttons only pls :) */
		sub_button.get_style_context().add_class("flat");
		sub_button.get_style_context().add_class("image-button");
		plus_button.get_style_context().add_class("flat");
		plus_button.get_style_context().add_class("image-button");

		/* Focus ring is ugly and unnecessary */
		sub_button.set_can_focus(false);
		plus_button.set_can_focus(false);
		volume_scale.set_can_focus(false);
		volume_scale.set_inverted(false);

		var sep = new Gtk.Separator(Gtk.Orientation.HORIZONTAL);
		main_box.pack_start(sep, false, false, 1);

		var button = new Gtk.Button.with_label(_("Sound settings"));
		button.get_child().set_halign(Gtk.Align.START);
		button.get_style_context().add_class(Gtk.STYLE_CLASS_FLAT);
		button.clicked.connect(open_sound_settings);
		main_box.pack_start(button, false, false, 0);

		popover.get_child().show_all();
	}

	void on_sink_changed(uint id) {
		set_default_mixer();
	}

	void set_default_mixer() {
		if (stream != null) {
			SignalHandler.disconnect(stream, notify_id);
		}

		stream = mixer.get_default_sink();
		notify_id = stream.notify.connect(on_notify);
		update_volume();
	}

	void on_notify(Object? o, ParamSpec? p) {
		if (p.name == "volume" || p.name == "is-muted") {
			update_volume();
		}
	}

	/**
	 * Called when something changes on the mixer, i.e. we connected
	 * This is where we hook into the stream for changes
	 */
	protected void on_state_change(uint new_state) {
		if (new_state == Gvc.MixerControlState.READY) {
			set_default_mixer();
		}
	}

	/**
	 * Update from scroll events. turn volume up + down.
	 */
	protected bool on_scroll_event(Gdk.EventScroll event) {
		return_val_if_fail(stream != null, false);

		uint32 vol = stream.get_volume();
		var orig_vol = vol;

		switch (event.direction) {
			case Gdk.ScrollDirection.UP:
				vol += (uint32)step_size;
				break;
			case Gdk.ScrollDirection.DOWN:
				vol -= (uint32)step_size;
				// uint. im lazy :p
				if (vol > orig_vol) {
					vol = 0;
				}
				break;
			default:
				// Go home, you're drunk.
				return false;
		}

		/* Ensure sanity + amp capability */
		var max_amp = mixer.get_vol_max_amplified();
		var norm = mixer.get_vol_max_norm();
		if (max_amp < norm) {
			max_amp = norm;
		}

		if (vol > max_amp) {
			vol = (uint32)max_amp;
		}

		/* Prevent amplification using scroll on sound indicator */
		if (vol >= norm) {
			vol = (uint32)norm;
		}

		SignalHandler.block(volume_scale, scale_id);
		if (stream.set_volume(vol)) {
			Gvc.push_volume(stream);
		}
		SignalHandler.unblock(volume_scale, scale_id);

		return true;
	}

	/**
	 * Update our icon when something changed (volume/mute)
	 */
	protected void update_volume() {
		var vol_norm = mixer.get_vol_max_norm();
		var vol = stream.get_volume();

		/* Same maths as computed by volume.js in gnome-shell, carried over
		 * from C->Vala port of budgie-panel */
		int n = (int) Math.floor(3*vol/vol_norm)+1;
		string image_name;

		// Work out an icon
		if (stream.get_is_muted() || vol <= 0) {
			image_name = "audio-volume-muted-symbolic";
		} else {
			switch (n) {
				case 1:
					image_name = "audio-volume-low-symbolic";
					break;
				case 2:
					image_name = "audio-volume-medium-symbolic";
					break;
				default:
					image_name = "audio-volume-high-symbolic";
					break;
			}
		}
		widget.set_from_icon_name(image_name, Gtk.IconSize.MENU);

		var vol_max = mixer.get_vol_max_amplified();

		// Each scroll increments by 5%, much better than units..
		step_size = vol_max / 20;

		// This usually goes up to about 150% (152.2% on mine though.)
		var pct = ((float)vol / (float)vol_norm)*100;
		var ipct = (uint)pct;
		widget.set_tooltip_text(@"$ipct%");

		/* We're ignoring anything beyond our vol_norm.. */
		SignalHandler.block(volume_scale, scale_id);
		volume_scale.set_range(0, vol_norm);
		if (vol > vol_norm) {
			volume_scale.set_value(vol);
		} else {
			volume_scale.set_value(vol);
		}
		volume_scale.get_adjustment().set_page_increment(step_size);
		SignalHandler.unblock(volume_scale, scale_id);

		show_all();
		queue_draw();

		if (stream.get_volume() != 0) { // If we haven't muted
			unmuted_volume_val = stream.get_volume(); // Get our new volume
		}
	}

	/**
	 * The scale changed value - update the stream volume to match
	 */
	private void on_scale_changed() {
		if (stream == null || mixer == null) {
			return;
		}
		double scale_value = volume_scale.get_value();

		/* Avoid recursion ! */
		SignalHandler.block(volume_scale, scale_id);
		if (stream.set_volume((uint32)scale_value)) {
			Gvc.push_volume(stream);
		}
		SignalHandler.unblock(volume_scale, scale_id);
	}

	/**
	 * Adjust the volume by a given +/- increment and bounds limit it
	 */
	private void adjust_volume_increment(double increment) {
		if (stream == null || mixer == null) {
			return;
		}
		int32 vol = (int32)stream.get_volume();
		var max_norm = mixer.get_vol_max_norm();
		vol += (int32)increment;

		if (vol < 0) {
			vol = 0;
		} else if (vol > max_norm) {
			vol = (int32) max_norm;
		}

		SignalHandler.block(volume_scale, scale_id);
		if (stream.set_volume((uint32)vol)) {
			Gvc.push_volume(stream);
		}
		SignalHandler.unblock(volume_scale, scale_id);
	}

	void open_sound_settings() {
		popover.hide();

		var app_info = new DesktopAppInfo("gnome-sound-panel.desktop");

		if (app_info == null) {
			return;
		}

		try {
			app_info.launch(null, null);
		} catch (Error e) {
			message("Unable to launch gnome-sound-panel.desktop: %s", e.message);
		}
	}
}

{'repo_name': 'solus-project/budgie-desktop', 'stars': '2143', 'repo_language': 'Vala', 'file_name': 'README', 'mime_type': 'text/plain', 'hash': -3956087048684452589, 'source_dataset': 'data'}


--disable_warnings
DROP TABLE IF EXISTS t1;
--enable_warnings
CREATE TABLE t1(c1 CHAR(1) NULL, c2 CHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='a';
SELECT COUNT(*) FROM t1 WHERE c1='a';
DROP TABLE t1;
CREATE TABLE t1(c1 CHAR(1) NULL, c2 CHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='b';
SELECT COUNT(*) FROM t1 WHERE c1='b';
DROP TABLE t1;
CREATE TABLE t1(c1 CHAR(1) NULL, c2 CHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='c';
SELECT COUNT(*) FROM t1 WHERE c1='c';
DROP TABLE t1;
CREATE TABLE t1(c1 CHAR(1) NULL, c2 CHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='d';
SELECT COUNT(*) FROM t1 WHERE c1='d';
DROP TABLE t1;
CREATE TABLE t1(c1 CHAR(1) NULL, c2 CHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='e';
SELECT COUNT(*) FROM t1 WHERE c1='e';
DROP TABLE t1;
CREATE TABLE t1(c1 CHAR(1) NULL, c2 CHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='f';
SELECT COUNT(*) FROM t1 WHERE c1='f';
DROP TABLE t1;
CREATE TABLE t1(c1 CHAR(1) NULL, c2 CHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='y';
SELECT COUNT(*) FROM t1 WHERE c1='y';
DROP TABLE t1;
CREATE TABLE t1(c1 VARCHAR(1) NULL, c2 VARCHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='a';
SELECT COUNT(*) FROM t1 WHERE c1='a';
DROP TABLE t1;
CREATE TABLE t1(c1 VARCHAR(1) NULL, c2 VARCHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='b';
SELECT COUNT(*) FROM t1 WHERE c1='b';
DROP TABLE t1;
CREATE TABLE t1(c1 VARCHAR(1) NULL, c2 VARCHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='c';
SELECT COUNT(*) FROM t1 WHERE c1='c';
DROP TABLE t1;
CREATE TABLE t1(c1 VARCHAR(1) NULL, c2 VARCHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='d';
SELECT COUNT(*) FROM t1 WHERE c1='d';
DROP TABLE t1;
CREATE TABLE t1(c1 VARCHAR(1) NULL, c2 VARCHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='e';
SELECT COUNT(*) FROM t1 WHERE c1='e';
DROP TABLE t1;
CREATE TABLE t1(c1 VARCHAR(1) NULL, c2 VARCHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='f';
SELECT COUNT(*) FROM t1 WHERE c1='f';
DROP TABLE t1;
CREATE TABLE t1(c1 VARCHAR(1) NULL, c2 VARCHAR(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='y';
SELECT COUNT(*) FROM t1 WHERE c1='y';
DROP TABLE t1;
CREATE TABLE t1(c1 BINARY(1) NULL, c2 BINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='a';
SELECT COUNT(*) FROM t1 WHERE c1='a';
DROP TABLE t1;
CREATE TABLE t1(c1 BINARY(1) NULL, c2 BINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='b';
SELECT COUNT(*) FROM t1 WHERE c1='b';
DROP TABLE t1;
CREATE TABLE t1(c1 BINARY(1) NULL, c2 BINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='c';
SELECT COUNT(*) FROM t1 WHERE c1='c';
DROP TABLE t1;
CREATE TABLE t1(c1 BINARY(1) NULL, c2 BINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='d';
SELECT COUNT(*) FROM t1 WHERE c1='d';
DROP TABLE t1;
CREATE TABLE t1(c1 BINARY(1) NULL, c2 BINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='e';
SELECT COUNT(*) FROM t1 WHERE c1='e';
DROP TABLE t1;
CREATE TABLE t1(c1 BINARY(1) NULL, c2 BINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='f';
SELECT COUNT(*) FROM t1 WHERE c1='f';
DROP TABLE t1;
CREATE TABLE t1(c1 BINARY(1) NULL, c2 BINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='y';
SELECT COUNT(*) FROM t1 WHERE c1='y';
DROP TABLE t1;
CREATE TABLE t1(c1 VARBINARY(1) NULL, c2 VARBINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='a';
SELECT COUNT(*) FROM t1 WHERE c1='a';
DROP TABLE t1;
CREATE TABLE t1(c1 VARBINARY(1) NULL, c2 VARBINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='b';
SELECT COUNT(*) FROM t1 WHERE c1='b';
DROP TABLE t1;
CREATE TABLE t1(c1 VARBINARY(1) NULL, c2 VARBINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='c';
SELECT COUNT(*) FROM t1 WHERE c1='c';
DROP TABLE t1;
CREATE TABLE t1(c1 VARBINARY(1) NULL, c2 VARBINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='d';
SELECT COUNT(*) FROM t1 WHERE c1='d';
DROP TABLE t1;
CREATE TABLE t1(c1 VARBINARY(1) NULL, c2 VARBINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='e';
SELECT COUNT(*) FROM t1 WHERE c1='e';
DROP TABLE t1;
CREATE TABLE t1(c1 VARBINARY(1) NULL, c2 VARBINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='f';
SELECT COUNT(*) FROM t1 WHERE c1='f';
DROP TABLE t1;
CREATE TABLE t1(c1 VARBINARY(1) NULL, c2 VARBINARY(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='y';
SELECT COUNT(*) FROM t1 WHERE c1='y';
DROP TABLE t1;
CREATE TABLE t1(c1 BLOB(1) NULL, c2 BLOB(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='a';
SELECT COUNT(*) FROM t1 WHERE c1='a';
DROP TABLE t1;
CREATE TABLE t1(c1 BLOB(1) NULL, c2 BLOB(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='b';
SELECT COUNT(*) FROM t1 WHERE c1='b';
DROP TABLE t1;
CREATE TABLE t1(c1 BLOB(1) NULL, c2 BLOB(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='c';
SELECT COUNT(*) FROM t1 WHERE c1='c';
DROP TABLE t1;
CREATE TABLE t1(c1 BLOB(1) NULL, c2 BLOB(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='d';
SELECT COUNT(*) FROM t1 WHERE c1='d';
DROP TABLE t1;
CREATE TABLE t1(c1 BLOB(1) NULL, c2 BLOB(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='e';
SELECT COUNT(*) FROM t1 WHERE c1='e';
DROP TABLE t1;
CREATE TABLE t1(c1 BLOB(1) NULL, c2 BLOB(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='f';
SELECT COUNT(*) FROM t1 WHERE c1='f';
DROP TABLE t1;
CREATE TABLE t1(c1 BLOB(1) NULL, c2 BLOB(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='y';
SELECT COUNT(*) FROM t1 WHERE c1='y';
DROP TABLE t1;
CREATE TABLE t1(c1 TEXT(1) NULL, c2 TEXT(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='a';
SELECT COUNT(*) FROM t1 WHERE c1='a';
DROP TABLE t1;
CREATE TABLE t1(c1 TEXT(1) NULL, c2 TEXT(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='b';
SELECT COUNT(*) FROM t1 WHERE c1='b';
DROP TABLE t1;
CREATE TABLE t1(c1 TEXT(1) NULL, c2 TEXT(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='c';
SELECT COUNT(*) FROM t1 WHERE c1='c';
DROP TABLE t1;
CREATE TABLE t1(c1 TEXT(1) NULL, c2 TEXT(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='d';
SELECT COUNT(*) FROM t1 WHERE c1='d';
DROP TABLE t1;
CREATE TABLE t1(c1 TEXT(1) NULL, c2 TEXT(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='e';
SELECT COUNT(*) FROM t1 WHERE c1='e';
DROP TABLE t1;
CREATE TABLE t1(c1 TEXT(1) NULL, c2 TEXT(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='f';
SELECT COUNT(*) FROM t1 WHERE c1='f';
DROP TABLE t1;
CREATE TABLE t1(c1 TEXT(1) NULL, c2 TEXT(1) NULL, c3 INT NULL);
--source suite/engines/funcs/t/data1.inc
SELECT COUNT(*) FROM t1;
SELECT COUNT(*) FROM t1 WHERE c2='y';
SELECT COUNT(*) FROM t1 WHERE c1='y';
DROP TABLE t1;

{'repo_name': 'MariaDB/server', 'stars': '3422', 'repo_language': 'C++', 'file_name': 'auth_ed25519.test', 'mime_type': 'text/plain', 'hash': 6469178702058353215, 'source_dataset': 'data'}


---
permalink: /docs/service-internals
---

# Teaclave Service Internals

Teaclave Service is one of the most important abstractions in the platform.
Basically, the Teaclave FaaS platform is the combination of different functional
services and connected through trusted channels. The Teaclave services include
authentication service, frontend service, management service, storage service,
access control service, scheduler service, and execution service. They play
different roles in the system.

To understand the design and internal implementation of these services, we need
to discuss in these sections: RPC and protocol, app-enclave structure, and
the attestation mechanism.

## RPC and Protocols

We use Protocol Buffers (version 3) to define messages and RPC interfaces of the
Teaclave services. For example, the authentication service has this definition.

```proto
message UserLoginRequest {
  string id = 1;
  string password = 2;
}

message UserLoginResponse {
  string token = 1;
}

service TeaclaveAuthenticationApi {
  rpc UserLogin (UserLoginRequest) returns (UserLoginResponse);
}
```

This means that the authentication service (for the API endpoint) has an RPC
interface called "`UserLogin`", which takes a "`UserLoginRequest`" message with
`id` and `password` inside (in string type) and reply a "`UserLoginResponse`"
message with `token` inside (in string type).

With this definition, the build system will help to generate utility functions,
traits, and structures for clients to send RPC requests, and for service to
implement functions of handling requests. This is done by a build time tool
called [`proto_gen`](https://github.com/apache/incubator-teaclave/tree/master/services/proto/proto_gen).

There is another layer in the `teaclave_proto` crate to help convert protobuf's
simple data type to Rust's more concise data type. For example, a URL is defined
in the string type in protobuf, while in Rust we can use the `Url` struct to
store a URL.

For more protocol definitions for other services, please see proto files in
the [`proto` directory](https://github.com/apache/incubator-teaclave/tree/master/services/proto/src/proto).

## Service Implementation Structure

A service in Teaclave consists of two parts: the app (untrusted) part and the
enclave (trusted) part. The app part is responsible for managing the service,
launching and terminating the enclave part, while the enclave part is to serve
RPC requests from clients (or other services) through trusted channels, execute
logic, and process data in the trusted execution environment.

### App (Untrusted)

Basically, the app part of a service does the followings:

- Load the runtime configuration from the config file.
- Create a service launcher: prepare the binder and set the serialized config as
  an input.
- Start the service enclave (*ecall* to the trusted enclave part).
- Misc: register signal handlers so that the app/enclave can respond to some
  signals.

### Enclave (Trusted)

Typically, a service's implementation in the enclave part contains two important
structs and one trait. Let's take the frontend service as an example.

- `TeaclaveFrontendService` (struct): Define properties or configurations along
  with the lifetime of the service. For example, the frontend service needs to
  hold clients (with established trusted channels) to communicate with the
  authentication service and management service.
- `TeaclaveFrontendError` (struct): Define errors that may occur in this
  service, authentication error, for example.
  - `TeaclaveFrontend` (trait Define): functions (requests) the service needs to
  handle. The trait will be automatically derived from definitions in the
  ProtoBuf file and can be imported from the `teaclave_proto` crate.

You will see some `#[handle_ecall]` annotations on functions and the
`register_ecall_handler` macro to help with the function registration.
The lifecycle of a Teaclave service consists of enclave initialized, service
started, and enclave finalized, which will invoke the corresponding command
handlers - `InitEnclave`, `StartService`, and `FinalizeEnclave`.

The start service function is the entry point of an enclave service. Here are
steps to prepare and start serving requests.

- Initialize the attestation config and make a remote attestation.
- With the endorsed attestation report, initialize an attested TLS config.
- Initialize a TLS server with TLS config and listening address.
- If needed, initialize service endpoints this service wants to connect. For
  example, the frontend service needs to connect to the authentication service
  and management service.
- Start the service (with endpoint handlers) and begin to serve requests.

Here is a code snippet from authentication service in the enclave part:

```rust
let api_listen_address = config.api_endpoints.authentication.listen_address;
let attestation_config = AttestationConfig::from_teaclave_config(&config)?;
let attested_tls_config = RemoteAttestation::new(attestation_config)
    .generate_and_endorse()?
    .attested_tls_config()
    .ok_or_else(|| anyhow!("cannot get attested TLS config"))?;
let server_config = SgxTrustedTlsServerConfig::from_attested_tls_config(attested_tls_config)?;

let mut server = SgxTrustedTlsServer::<
    TeaclaveAuthenticationApiResponse,
    TeaclaveAuthenticationApiRequest,
>::new(addr, server_config);

let service = api_service::TeaclaveAuthenticationApiService::new(db_client, jwt_secret);

match server.start(service) {}
```

## Topology

These services are communicating through RPC with remote attestation. Here is a
topological graph illustrating connections between services.

```
clients => authentication <-+       +----> storage <----+
                            |       |                   |
clients => frontend ----------> management            scheduler <-- execution
                                    |
                                    +--> access_control

                                                  =>      api endpoint connections
                                                  -> internal endpoint connections
```

## Attestation in Services

To explain the usages of remote attestation mechanism in services, we need to
consider two different scenarios: 1) the service wants to serve RPC requests
from clients, 2) the service wants to connect and send requests to other
services.

For the first scenario, the endorsed attestation report is used for creating the
trusted TLS server, so that clients can attest the service's report to verify
the platform. In the meantime, if the service wants to attest clients (a.k.a.,
establishing mutual attestation), we need to get the accepted enclave attributes
from the *enclave info* first to create the trusted TLS server. By this, the
server can also attest clients' attestation reports and only accept expected
connections.

You may find code like the following to get the accepted enclave attributes for
mutual attestation:

```rust
let enclave_info = EnclaveInfo::verify_and_new(...)?;
let accepted_enclave_attrs: Vec<teaclave_types::EnclaveAttr> = AUTHENTICATION_INBOUND_SERVICES
    .iter()
    .map(|service| match enclave_info.get_enclave_attr(service) {...})
    .collect::<Result<_>>()?;

...

let server_config = SgxTrustedTlsServerConfig::from_attested_tls_config(attested_tls_config)?
    .attestation_report_verifier(
    accepted_enclave_attrs,
    AS_ROOT_CA_CERT,
    verifier::universal_quote_verifier,
)?;
```

For the second scenario, the report is used to create a trusted TLS channel so
that the client can present its report when establishing the channel. Also, the
server's report will be verified.

## Customize a Standalone Service

For most cases, we suggest using the Teaclave platform as a whole for security
and functionality concerns. However, you may want to customize a TEE service
using Teaclave's existing capabilities under our service framework. For
instance, the execution service can be used as a standalone TEE Python executor,
and the storage service can be used as a secure database as well.

To customize Teaclave services as a standalone one, you need to first think
about the interfaces exposed to clients, that is the definitions in protobuf.
For example, for a key-value database, we have defined `Get`, `Put` and `Delete`
interfaces.

Additionally, if you are using it as a standalone TEE service, the attestation
mechanism needs to be "one-way attestation" accordingly. That is, only clients
can establish trusted channels and attest the service's identity and platform
status, but service cannot attest clients.

{'repo_name': 'apache/incubator-teaclave', 'stars': '305', 'repo_language': 'Rust', 'file_name': 'teaclave.py', 'mime_type': 'text/x-python', 'hash': -5430341615219406117, 'source_dataset': 'data'}