text:
namespace NLog.LayoutRenderers
{
    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Globalization;
    using System.Reflection;
    using System.Text;
    using NLog.Config;

    /// <summary>
    /// The information about the running process.
    /// </summary>
    [LayoutRenderer("processinfo")]
    public class ProcessInfoLayoutRenderer : LayoutRenderer
    {
        private Process process;

        private PropertyInfo propertyInfo;

        /// <summary>
        /// Initializes a new instance of the <see cref="ProcessInfoLayoutRenderer" /> class.
        /// </summary>
        public ProcessInfoLayoutRenderer()
        {
            this.Property = ProcessInfoProperty.Id;
        }

        /// <summary>
        /// Gets or sets the property to retrieve.
        /// </summary>
        /// <docgen category='Rendering Options' order='10' />
        [DefaultValue("Id"), DefaultParameter]
        public ProcessInfoProperty Property { get; set; }

        /// <summary>
        /// Initializes the layout renderer.
        /// </summary>
        protected override void InitializeLayoutRenderer()
        {
            base.InitializeLayoutRenderer();
            this.propertyInfo = typeof(Process).GetProperty(this.Property.ToString());
            if (this.propertyInfo == null)
            {
                throw new ArgumentException("Property '" + this.propertyInfo + "' not found in System.Diagnostics.Process");
            }

            this.process = Process.GetCurrentProcess();
        }

        /// <summary>
        /// Closes the layout renderer.
        /// </summary>
        protected override void CloseLayoutRenderer()
        {
            if (this.process != null)
            {
                this.process.Close();
                this.process = null;
            }

            base.CloseLayoutRenderer();
        }

        /// <summary>
        /// Renders the selected process information.
        /// </summary>
        /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
        /// <param name="logEvent">Logging event.</param>
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            if (this.propertyInfo != null)
            {
                builder.Append(Convert.ToString(this.propertyInfo.GetValue(this.process, null), CultureInfo.InvariantCulture));
            }
        }
    }
}

#endif


text:
// -------------------------------------------------------------------------- \\
// File: Mailbox.js                                                           \\
// Module: MailModel                                                          \\
// Requires: API                                                              \\
// -------------------------------------------------------------------------- \\

/*global O, JMAP */

'use strict';

( function ( JMAP ) {

const loc = O.loc;
const i18n = O.i18n;
const Class = O.Class;
const RecordArray = O.RecordArray;
const LocalQuery = O.LocalQuery;
const Record = O.Record;
const attr = Record.attr;
const ValidationError = O.ValidationError;
const REQUIRED = ValidationError.REQUIRED;
const TOO_LONG = ValidationError.TOO_LONG;

const connection = JMAP.mail;
const makeSetRequest = JMAP.Connection.makeSetRequest;

// ---

const roleSortOrder = {
    inbox: 1,
    snoozed: 2,
    archive: 3,
    drafts: 4,
    xtemplates: 5,
    sent: 6,
    junk: 7,
    trash: 8,
    all: 9,
};

const bySortOrderRoleOrName = function ( a, b ) {
    return (
        a.sortOrder - b.sortOrder
    ) || (
        ( roleSortOrder[ a.role ] || 99 ) -
        ( roleSortOrder[ b.role ] || 99 )
    ) || (
        i18n.compare( a.name, b.name )
    ) || (
        a.id < b.id ? -1 : 1
    );
};

const Mailbox = Class({

    Extends: Record,

    name: attr( String, {
        defaultValue: '',
        validate: function ( propValue/*, propKey, record*/ ) {
            if ( !propValue ) {
                return new ValidationError( REQUIRED,
                    loc( 'S_LABEL_REQUIRED' )
                );
            }
            if ( propValue.length > 256 ) {
                return new ValidationError( TOO_LONG,
                    loc( 'S_MAIL_ERROR_MAX_CHARS', 256 )
                );
            }
            return null;
        }
    }),

    parent: Record.toOne({
        // Type: Mailbox,
        key: 'parentId',
        defaultValue: null,
        willSet: function ( propValue, propKey, record ) {
            if ( propValue ) {
                record.set( 'accountId', propValue.get( 'accountId' ) );
            }
            return true;
        },
    }),

    role: attr( String, {
        defaultValue: null
    }),

    sortOrder: attr( Number, {
        defaultValue: 10
    }),

    // ---

    isSubscribed: attr( Boolean, {
        defaultValue: true,
    }),

    myRights: attr( Object, {
        defaultValue: {
            mayReadItems: true,
            mayAddItems: true,
            mayRemoveItems: true,
            maySetSeen: true,
            maySetKeywords: true,
            mayCreateChild: true,
            mayRename: true,
            mayDelete: true,
            maySubmit: true,
            mayAdmin: true,
        },
        noSync: true
    }),

    mayAddItems: function () {
        return this.get( 'myRights' ).mayAddItems &&
            this.get( 'role' ) !== 'snoozed';
    }.property( 'role', 'myRights' ),

    // ---

    totalEmails: attr( Number, {
        defaultValue: 0,
        noSync: true
    }),
    unreadEmails: attr( Number, {
        defaultValue: 0,
        noSync: true
    }),
    totalThreads: attr( Number, {
        defaultValue: 0,
        noSync: true
    }),
    unreadThreads: attr( Number, {
        defaultValue: 0,
        noSync: true
    }),

    // ---

    displayName: function () {
        return this.get( 'name' );
    }.property( 'name' ),

    subfolders: function () {
        var storeKey = this.get( 'storeKey' );
        var store = this.get( 'store' );
        var accountId = this.get( 'accountId' );
        return storeKey ?
            store.getAll( Mailbox,
                function ( data ) {
                    return data.accountId === accountId &&
                        data.parentId === storeKey;
                },
                bySortOrderRoleOrName
            ) :
            new RecordArray( store, Mailbox, [] );
    }.property().nocache(),

    depth: function () {
        var parent = this.get( 'parent' );
        return parent ? parent.get( 'depth' ) + 1 : 0;
    }.property( 'parent' ),

    depthDidChange: function ( _, __, oldDepth ) {
        if ( oldDepth !== this.get( 'depth' ) ) {
            this.get( 'subfolders' ).forEach( function ( mailbox ) {
                mailbox.computedPropertyDidChange( 'depth' );
            });
        }
    }.observes( 'depth' ),

    // ---

    moveTo: function ( dest, where ) {
        var sub = ( where === 'sub' );
        var parent = sub ? dest : dest.get( 'parent' );
        var accountId = dest.get( 'accountId' );
        var siblings = parent ?
                parent.get( 'subfolders' ) :
                this.get( 'store' ).getQuery( 'rootMailboxes-' + accountId,
                LocalQuery, {
                    Type: Mailbox,
                    where: function ( data ) {
                        return !data.parentId && data.accountId === accountId &&
                            data.role !== 'xnotes';
                    },
                    sort: bySortOrderRoleOrName,
                });
        var index = sub ? 0 :
                siblings.indexOf( dest ) + ( where === 'next' ? 1 : 0 );
        var prev = index ? siblings.getObjectAt( index - 1 ) : null;
        var next = siblings.getObjectAt( index );
        var prevSortOrder = prev ? prev.get( 'sortOrder' ) : 0;
        var nextSortOrder = next ? next.get( 'sortOrder' ) : ( index + 2 ) * 32;
        var i, p, l, folder;

        if ( nextSortOrder - prevSortOrder < 2 ) {
            for ( i = 0, p = 32, l = siblings.get( 'length' );
                    i < l; i += 1, p += 32 ) {
                folder = siblings.getObjectAt( i );
                if ( folder !== this ) {
                    folder.set( 'sortOrder', p );
                    if ( folder === prev ) {
                        p += 32;
                    }
                }
            }
            if ( prev ) { prevSortOrder = prev.get( 'sortOrder' ); }
            if ( next ) { nextSortOrder = next.get( 'sortOrder' ); }
        }
        this.set( 'parent', parent || null )
            .set( 'sortOrder', ( nextSortOrder + prevSortOrder ) >> 1 );
    },

    // ---

    destroy: function () {
        // Check ACL
        if ( this.get( 'myRights' ).mayDelete ) {
            // Destroy dependent records
            this.get( 'subfolders' ).forEach( function ( folder ) {
                folder.destroy();
            });
            Mailbox.parent.destroy.call( this );
        }
    },
});
Mailbox.__guid__ = 'Mailbox';
Mailbox.dataGroup = 'urn:ietf:params:jmap:mail';

Mailbox.prototype.parent.Type = Mailbox;

Mailbox.noChildRole = {
    snoozed: true,
    junk: true,
    trash: true,
};

// ---

connection.ignoreCountsForMailboxIds = null;
connection.fetchIgnoredMailboxes = function () {
    var idToMailbox = connection.ignoreCountsForMailboxIds;
    if ( idToMailbox ) {
        Object.values( idToMailbox ).forEach( function ( mailbox ) {
            mailbox.fetch();
        });
    }
    connection.ignoreCountsForMailboxIds = null;
};

// ---

connection.handle( Mailbox, {

    precedence: 0,

    fetch: 'Mailbox',

    refresh: function ( accountId, ids, state ) {
        var get = 'Mailbox/get';
        if ( ids ) {
            this.callMethod( get, {
                accountId: accountId,
                ids: ids,
                properties: [
                    'totalEmails', 'unreadEmails',
                    'totalThreads', 'unreadThreads',
                ],
            });
        } else {
            var changes = 'Mailbox/changes';
            this.callMethod( changes, {
                accountId: accountId,
                sinceState: state,
            });
            var methodId = this.getPreviousMethodId();
            this.callMethod( get, {
                accountId: accountId,
                '#ids': {
                    resultOf: methodId,
                    name: changes,
                    path: '/created',
                },
            });
            this.callMethod( get, {
                accountId: accountId,
                '#ids': {
                    resultOf: methodId,
                    name: changes,
                    path: '/updated',
                },
                '#properties': {
                    resultOf: methodId,
                    name: changes,
                    path: '/updatedProperties',
                },
            });
        }
    },

    commit: function ( change ) {
        var args = makeSetRequest( change, false );
        args.onDestroyRemoveEmails = true;
        this.callMethod( 'Mailbox/set', args );
    },

    // ---

    'Mailbox/get': function ( args, _, reqArgs ) {
        const isAll = ( reqArgs.ids === null );
        const ignoreCounts = this.ignoreCountsForMailboxIds;
        if ( ignoreCounts && args.list ) {
            const accountId = args.accountId;
            args.list.forEach( function ( item ) {
                var mailbox = ignoreCounts[ accountId + '/' + item.id ];
                if ( mailbox ) {
                    item.totalThreads = mailbox.get( 'totalThreads' );
                    item.unreadEmails = mailbox.get( 'unreadEmails' );
                    item.totalEmails = mailbox.get( 'totalEmails' );
                    item.unreadThreads = mailbox.get( 'unreadThreads' );
                }
            });
        }
        this.didFetch( Mailbox, args, isAll );
    },

    'Mailbox/changes': function ( args ) {
        const hasDataForChanged = true;
        this.didFetchUpdates( Mailbox, args, hasDataForChanged );
        if ( args.hasMoreChanges ) {
            this.fetchMoreChanges( args.accountId, Mailbox );
        }
    },

    'error_Mailbox/changes_cannotCalculateChanges': function ( _, __, reqArgs ) {
        var accountId = reqArgs.accountId;
        // All our data may be wrong. Refetch everything.
        this.fetchAllRecords( accountId, Mailbox );
    },

    'Mailbox/set': function ( args ) {
        this.didCommit( Mailbox, args );
    },
});
Mailbox.roleSortOrder = roleSortOrder;
Mailbox.bySortOrderRoleOrName = bySortOrderRoleOrName;

// --- Export

JMAP.Mailbox = Mailbox;

}( JMAP ) );

redpajama_set_name: RedPajamaGithub


text:
#ifndef MICROBLAZE_EXCEPTIONS_H
#define MICROBLAZE_EXCEPTIONS_H
#include "vmi/vmiAttrs.h"
#include "microblazeStructure.h"

//
// Take an MMU storage exception
//
void microblazeMMUStorageException(
    microblazeP         microblaze,
    microblazeTLBAction action,
    Uns32               va,
    Bool                DIZ
);

void microblazeTLBMissException(
    microblazeP         microblaze,
    microblazeTLBAction action,
    Uns32               va
);

void microblazeStreamExceptionCB(vmiProcessorP processor, Uns32 insn, Uns32 e, Uns32 d, Uns32 fsl, Uns32 rB, Uns32 rD);
void microblazehwExceptionCB(vmiProcessorP processor, TYPE_SPR_ESR ESR);
void microblazeInstallPorts(microblazeP microblaze);
void microblazeRegisterInit (microblazeP microblaze);
void microblazeMaskEnable(Uns32 *mask, Bool Enable, Uns32 left, Uns32 right);
void microblazeCheckExceptions(microblazeP microblaze);
void microblazeProcessReset(vmiProcessorP processor);
void microblazeProcessInterrupt(vmiProcessorP processor);
void microblazeDoException(microblazeP microblaze);

#endif // MICROBLAZE_EXCEPTIONS_H


text:
package org.i3xx.util.ctree.func;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The wildcards are replaced by the path name of the configuration node.
 *
 * name-1 '.' name-2 '.' name-3 '[' path-1 '-' '>' path-2 ']'
 *
 * Types of path-1 and path-2
 * part1.part2 => part1.part2
 * part1.* => part1.name-2
 * *.part2 => name-1.part2
 * *.* => name-1.name-2
 *
 * @author Stefan
 * @see read-links.conf for excemples
 */
public class WildcardResolver implements IResolver {

	Logger logger = LoggerFactory.getLogger(WildcardResolver.class);

	protected String destName;
	protected boolean resolved;
	protected boolean finished;

	public WildcardResolver(String destName) {
		this.destName = destName;
		resolved = false;
		finished = false;
	}

	/* (non-Javadoc)
	 * @see com.i3xx.util.ctree.IResolver#resolve(com.i3xx.util.ctree.IVarNode)
	 */
	public void resolve(IVarNode node) {

		//if(destName.startsWith("data.object.agreement")){
		//	Println.debug("AGR::"+node.getValue()+" op="+node.getOp()+" left="+node.getLeft()+" right="+node.getRight()+" resolve="+(!(!node.isLeaf() || node.getValue()==null || node.getOp()!=VarNode.OP.REPLACE)));
		//}
		if(logger.isDebugEnabled())
			logger.debug("AGR::{} op={} left={} right={} resolve={}",
					node.getValue(), node.getOp(), node.getLeft(), node.getRight(),
					(!(!node.isLeaf() || node.getValue()==null || node.getOp()!=VarNode.OP.REPLACE)));

		//needs a valid leaf node and an operator REPLACE
		if(node.isLeaf() || node.getOp()!=VarNode.OP.REPLACE || !node.getRight().isLeaf())
			return;

		String fullName = node.getRight().getValue();

		String[] paths = destName.split("\\.");
		String[] parts = fullName.split("\\.");

		//wCard is the highest index of a part containing '*'
		int wCard = 0;
		for(int i=0;i<parts.length;i++) {
			String part = parts[i];
			if( part.contains("*") )
				wCard = i;
		}//for

		for(int i=0;i<parts.length;i++){
			String part = parts[i];
			//paths is too short - cannot match
			if(i==paths.length){
				logger.trace("#0 {}",fullName);
				printName(parts, node.getRight());
				finished = false;
				return;
			}

			String path = paths[i];
			if(part.equals(path)){
				logger.trace("#1 part:{}, path{}, destName:{}", part, path, destName);
				continue;
			}else if( part.contains("*") ){
				logger.trace("#2 part:{}, path:{}, destName:{}", part, path, destName);
				parts[i] = path;
				continue;
			}else if( i<wCard ){
				//not the last part
				logger.trace("#3 part:{}, path:{}, destName:{}", part, path, destName);
				continue;
			}else{
				//doesn't match
				logger.trace("#4 part:{}, path:{}, destName:{}", part, path, destName);
				printName(parts, node.getRight());

				//last part is not equals
				if(i==(parts.length-1))
					break;

				finished = false;
				return;
			}
		}
		//match until last element in part and path
		//the function is done

		//Println.debug("--"+node.toString());
		resolved = true;
		finished = true;

		node.setOp(null);
		node.setLeft(null);
		node.setRight(null);
		printName(parts, node);
	}

	/* (non-Javadoc)
	 * @see com.i3xx.util.ctree.IResolver#resolved()
	 */
	public boolean resolved() {
		return resolved;
	}

	/* (non-Javadoc)
	 * @see com.i3xx.util.ctree.IResolver#finished()
	 */
	public boolean finished() {
		return finished;
	}

	/**
	 * @param parts
	 * @param node
	 */
	private void printName(String[] parts, IVarNode node) {
		//create new key string :: part [ '.' part ]*
		StringBuffer buf = new StringBuffer();
		for(String part:parts){
			buf.append('.');
			buf.append(part);
		}
		buf.deleteCharAt(0);

		node.setValue( buf.toString() );
	}
}


text:
#include <system.hh>

#include "print.h"
#include "xact.h"
#include "post.h"
#include "account.h"
#include "session.h"
#include "report.h"

namespace ledger {

namespace {
  bool post_has_simple_amount(const post_t& post)
  {
    // Is the amount the result of a computation, i.e., it wasn't
    // explicit specified by the user?
    if (post.has_flags(POST_CALCULATED))
      return false;

    // Is the amount still empty?  This shouldn't be true by this point,
    // but we check anyway for safety.
    if (post.amount.is_null())
      return false;

    // Is the amount a complex expression.  If so, the first 'if' should
    // have triggered.
    if (post.amount_expr)
      return false;

    // Is there a balance assignment?  If so, don't elide the amount as
    // that can change the semantics.
    if (post.assigned_amount)
      return false;

    // Does it have an explicitly specified cost (i.e., one that wasn't
    // calculated for the user)?  If so, don't elide the amount!
    if (post.cost && ! post.has_flags(POST_COST_CALCULATED))
      return false;

    return true;
  }

  void print_note(std::ostream&     out,
                  const string&     note,
                  const bool        note_on_next_line,
                  const std::size_t columns,
                  const std::size_t prior_width)
  {
    // The 3 is for two spaces and a semi-colon before the note.
    if (note_on_next_line ||
        (columns > 0 &&
         (columns <= prior_width + 3 ||
          note.length() > columns - (prior_width + 3))))
      out << "\n    ;";
    else
      out << "  ;";

    bool need_separator = false;
    for (const char * p = note.c_str(); *p; p++) {
      if (*p == '\n') {
        need_separator = true;
      } else {
        if (need_separator) {
          out << "\n    ;";
          need_separator = false;
        }
        out << *p;
      }
    }
  }

  void print_xact(report_t& report, std::ostream& out, xact_t& xact)
  {
    format_type_t          format_type = FMT_WRITTEN;
    optional<const char *> format;

    if (report.HANDLED(date_format_)) {
      format_type = FMT_CUSTOM;
      format      = report.HANDLER(date_format_).str().c_str();
    }

    std::ostringstream buf;

    buf << format_date(item_t::use_aux_date ?
                       xact.date() : xact.primary_date(),
                       format_type, format);
    if (! item_t::use_aux_date && xact.aux_date())
      buf << '=' << format_date(*xact.aux_date(),
                                format_type, format);
    buf << ' ';

    buf << (xact.state() == item_t::CLEARED ? "* " :
            (xact.state() == item_t::PENDING ? "! " : ""));

    if (xact.code)
      buf << '(' << *xact.code << ") ";

    buf << xact.payee;

    string leader = buf.str();
    out << leader;

    std::size_t columns =
      (report.HANDLED(columns_) ?
       lexical_cast<std::size_t>(report.HANDLER(columns_).str()) : 80);

    if (xact.note)
      print_note(out, *xact.note, xact.has_flags(ITEM_NOTE_ON_NEXT_LINE),
                 columns, unistring(leader).length());
    out << '\n';

    if (xact.metadata) {
      foreach (const item_t::string_map::value_type& data, *xact.metadata) {
        if (! data.second.second) {
          out << "    ; ";
          if (data.second.first)
            out << data.first << ": " << *data.second.first;
          else
            out << ':' << data.first << ":";
          out << '\n';
        }
      }
    }

    std::size_t count = xact.posts.size();
    std::size_t index = 0;

    foreach (post_t * post, xact.posts) {
      index++;

      if (! report.HANDLED(generated) &&
          (post->has_flags(ITEM_TEMP | ITEM_GENERATED) &&
           ! post->has_flags(POST_ANONYMIZED)))
        continue;

      out << "    ";

      std::ostringstream pbuf;

      if (xact.state() == item_t::UNCLEARED)
        pbuf << (post->state() == item_t::CLEARED ? "* " :
                (post->state() == item_t::PENDING ? "! " : ""));

      if (post->has_flags(POST_VIRTUAL)) {
        if (post->has_flags(POST_MUST_BALANCE))
          pbuf << '[';
        else
          pbuf << '(';
      }

      pbuf << post->account->fullname();

      if (post->has_flags(POST_VIRTUAL)) {
        if (post->has_flags(POST_MUST_BALANCE))
          pbuf << ']';
        else
          pbuf << ')';
      }

      unistring name(pbuf.str());

      std::size_t account_width =
        (report.HANDLED(account_width_) ?
         lexical_cast<std::size_t>(report.HANDLER(account_width_).str()) : 36);

      if (account_width < name.length())
        account_width = name.length();

      if (! post->has_flags(POST_CALCULATED) || report.HANDLED(generated)) {
        out << name.extract();
        std::string::size_type slip =
          (static_cast<std::string::size_type>(account_width) -
           static_cast<std::string::size_type>(name.length()));

        std::size_t amount_width =
          (report.HANDLED(amount_width_) ?
           lexical_cast<std::size_t>(report.HANDLER(amount_width_).str()) :
           12);
        string amt;
        if (post->amount_expr) {
          std::ostringstream amt_str;
          justify(amt_str, post->amount_expr->text(), (int)amount_width, true);
          amt = amt_str.str();
        }
        else if (count == 2 && index == 2 &&
                 post_has_simple_amount(*post) &&
                 post_has_simple_amount(*(*xact.posts.begin())) &&
                 ((*xact.posts.begin())->amount.commodity() ==
                  post->amount.commodity())) {
          // If there are two postings and they both simple amount, and
          // they are both of the same commodity, don't bother printing
          // the second amount as it's always just an inverse of the
          // first.
        }
        else {
          std::ostringstream amt_str;
          value_t(post->amount).print(amt_str, static_cast<int>(amount_width),
                                      -1, AMOUNT_PRINT_RIGHT_JUSTIFY |
                                      (report.HANDLED(generated) ? 0 :
                                       AMOUNT_PRINT_NO_COMPUTED_ANNOTATIONS));
          amt = amt_str.str();
        }

        string trimmed_amt(amt);
        trim_left(trimmed_amt);
        std::string::size_type amt_slip =
          (static_cast<std::string::size_type>(amt.length()) -
           static_cast<std::string::size_type>(trimmed_amt.length()));

        std::ostringstream amtbuf;
        if (slip + amt_slip < 2)
          amtbuf << string(2 - (slip + amt_slip), ' ');
        amtbuf << amt;

        if (post->given_cost &&
            ! post->has_flags(POST_CALCULATED | POST_COST_CALCULATED)) {
          std::string cost_op;
          if (post->has_flags(POST_COST_IN_FULL))
            cost_op = "@@";
          else
            cost_op = "@";
          if (post->has_flags(POST_COST_VIRTUAL))
            cost_op = "(" + cost_op + ")";

          if (post->has_flags(POST_COST_IN_FULL))
            amtbuf << " " << cost_op << " " << post->given_cost->abs();
          else
            amtbuf << " " << cost_op << " "
                   << (*post->given_cost / post->amount).abs();
        }

        if (post->assigned_amount)
          amtbuf << " = " << *post->assigned_amount;

        string trailer = amtbuf.str();
        if (! trailer.empty()) {
          if (slip > 0) {
            out.width(static_cast<std::streamsize>(slip));
            out << ' ';
          }
          out << trailer;

          account_width += unistring(trailer).length();
        }
      } else {
        out << pbuf.str();
      }

      if (post->note)
        print_note(out, *post->note, post->has_flags(ITEM_NOTE_ON_NEXT_LINE),
                   columns, 4 + account_width);
      out << '\n';
    }
  }
}

void print_xacts::title(const string&)
{
  if (first_title) {
    first_title = false;
  } else {
    std::ostream& out(report.output_stream);
    out << '\n';
  }
}

void print_xacts::flush()
{
  std::ostream& out(report.output_stream);

  bool first = true;
  foreach (xact_t * xact, xacts) {
    if (first)
      first = false;
    else
      out << '\n';

    if (print_raw) {
      print_item(out, *xact);
      out << '\n';
    } else {
      print_xact(report, out, *xact);
    }
  }

  out.flush();
}

void print_xacts::operator()(post_t& post)
{
  if (! post.has_xdata() ||
      ! post.xdata().has_flags(POST_EXT_DISPLAYED)) {
    if (xacts_present.find(post.xact) == xacts_present.end()) {
      xacts_present.insert(xacts_present_map::value_type(post.xact, true));
      xacts.push_back(post.xact);
    }
    post.xdata().add_flags(POST_EXT_DISPLAYED);
  }
}

} // namespace ledger


text:
<?php

namespace Assely\Field\Support;

trait MayHaveChildren
{
    /**
     * Field children fields.
     *
     * @var \Assely\Field\Field[]
     */
    protected $children;

    /**
     * Set field children fields.
     *
     * @param \Assely\Field\Field[] $fields
     * @return self
     */
    public function children($fields)
    {
        $this->getChildren()->mergeSchema($fields);

        return $this;
    }

    /**
     * There are any children?
     *
     * @return bool
     */
    public function hasChildren()
    {
        return  ! empty($this->getChildren()->getSchema());
    }

    /**
     * Gets the value of children.
     *
     * @return \Assely\Field\FieldsCollection
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Sets the value of children.
     *
     * @param \Assely\Field\FieldsCollection $children
     *
     * @return self
     */
    public function setChildren($children)
    {
        $this->children = $children;

        return $this;
    }
}


text:
'use strict'

const { expect } = require('chai')

const splitter = require('../lib/splitter')

describe('Splitter', () => {
  it('should export a function', () => {
    expect(splitter).to.be.a('function')
  })

  it('should contain static method', () => {
    expect(splitter.isConfigurationValid).to.be.a('function')
  })
})


text:
package org.wso2.carbon.identity.user.store.configuration.deployer;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.deployment.AbstractDeployer;
import org.apache.axis2.deployment.DeploymentException;
import org.apache.axis2.deployment.repository.util.DeploymentFileData;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.ant.util.FileUtils;
import org.wso2.carbon.base.api.ServerConfigurationService;
import org.wso2.carbon.identity.user.store.configuration.deployer.exception.UserStoreConfigurationDeployerException;
import org.wso2.carbon.identity.user.store.configuration.deployer.internal.UserStoreConfigComponent;
import org.wso2.carbon.identity.user.store.configuration.deployer.util.UserStoreConfigurationConstants;
import org.wso2.carbon.identity.user.store.configuration.deployer.util.UserStoreUtil;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.common.UserStoreDeploymentManager;

import javax.xml.stream.XMLStreamException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * This is to deploy a new User Store Management Configuration file dropped or created at repository/deployment/server/userstores
 * or repository/tenant/<>tenantId</>/userstores. Whenever a new file with .xml extension is added/deleted or a modification is done to
 * an existing file, deployer will automatically update the existing realm configuration org.wso2.carbon.identity.user.store.configuration
 * according to the new file.
 */
public class UserStoreConfigurationDeployer extends AbstractDeployer {

    private static Log log = LogFactory.getLog(UserStoreConfigurationDeployer.class);

    private AxisConfiguration axisConfig;

    public void init(ConfigurationContext configurationContext) {
        log.info("User Store Configuration Deployer initiated.");
        this.axisConfig = configurationContext.getAxisConfiguration();

    }

    /**
     * Trigger deploying of new org.wso2.carbon.identity.user.store.configuration file
     *
     * @param deploymentFileData information about the user store org.wso2.carbon.identity.user.store.configuration
     * @throws org.apache.axis2.deployment.DeploymentException
     *          for any errors
     */
    public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
        ServerConfigurationService config =
                UserStoreConfigComponent.getServerConfigurationService();

        if(config == null){
            return;
        }
        String absolutePath = deploymentFileData.getAbsolutePath();
        String ext = FilenameUtils.getExtension(absolutePath);

        if(UserStoreConfigurationConstants.ENC_EXTENSION.equalsIgnoreCase(ext)){
            try {
                UserStoreUtil.initializeKeyStore();
                OMElement secondaryStoreDocument = UserStoreUtil.initializeOMElement(absolutePath);
                UserStoreUtil.updateSecondaryUserStore(secondaryStoreDocument);

                int index = absolutePath.lastIndexOf(".");
                if(index != 1 ){
                    String encFileName = absolutePath.substring(0, index+1) + UserStoreConfigurationConstants.XML_EXTENSION;
                    OutputStream outputStream;
                    outputStream = new FileOutputStream(encFileName);
                    secondaryStoreDocument.serialize(outputStream);

                    File file = new File(absolutePath);
                    if(file.exists()){
                        FileUtils.delete(file);
                    }
                }
                return;
            } catch (UserStoreConfigurationDeployerException e) {
                String errMsg = "Secondary user store processing failed while processing "+absolutePath;
                throw new DeploymentException(errMsg,e);
            } catch (FileNotFoundException e) {
                String errMsg = "Secondary user store File path "+absolutePath + " is invalid";
                throw new DeploymentException(errMsg,e);
            } catch (XMLStreamException e) {
                String errMsg = "Unexpected xml processing errors while trying to update file "
                        +absolutePath;
                throw new DeploymentException(errMsg,e);
            } catch (UserStoreException e) {
                String errMsg = "Error while initializing key store";
                throw new DeploymentException(errMsg,e);
            }
        }

        UserStoreDeploymentManager userStoreDeploymentManager = new UserStoreDeploymentManager();
        userStoreDeploymentManager.deploy(deploymentFileData.getAbsolutePath());
  }

    /**
     * Trigger un-deploying of a deployed file. Removes the deleted user store from chain
     *
     * @param fileName: domain name --> file name
     * @throws org.apache.axis2.deployment.DeploymentException
     *          for any errors
     */
    public void undeploy(String fileName) throws DeploymentException {

        if(fileName != null){
            String ext = FilenameUtils.getExtension(fileName);
            if(!UserStoreConfigurationConstants.ENC_EXTENSION.equalsIgnoreCase(ext)){
                UserStoreDeploymentManager userStoreDeploymentManager = new UserStoreDeploymentManager();
                userStoreDeploymentManager.undeploy(fileName);
            }
        }
    }

    public void setDirectory(String s) {

    }

    public void setExtension(String s) {

    }
}


text:
<?php

/*
 * To change this objectType, choose Tools | Templates
 * and open the objectType in the editor.
 */

/**
 * Description of objectquery
 *
 * @author deepwinter1
 */
class Graph_ObjectQuery {

   public $attributes;

   public function initWithArray($attributes){
      $this->attributes['label'] = null;
      $this->attributes['objectTypeFilter'] = null;
      $this->attributes['where'] = null;
      $this->attributes['from'] = null;
      $this->attributes['slug'] = null;

      foreach($attributes as $key=>$value){
         $this->attributes[$key] = $value;
      }
   }

   public function initWithXml($xml) {
      $this->attributes['label'] = $xml->getAttribute('label');
      $this->attributes['objectTypeFilter'] = $xml->getAttribute('objectTypeFilter');
      $this->attributes['where'] = $xml->getAttribute('where');
      $this->attributes['from'] = $xml->getAttribute('from');
      $this->attributes['slug'] = $xml->getAttribute('slug');
   }

   public function run($parentId = null){

     $objects = Graph::object();

			//apply slug filter
			if($this->attributes['slug']){
				$objects->where('slug', '=', $this->attributes['slug']);
			}

      //apply optional parent filter
      if ($from = $this->attributes['from'] ) { //
				if($from != 'all'){
					if ($from == 'parent') {
						$objects->latticeChildrenFilter($parentId);
					} else {
						$from = Graph::object($from);
						$objects->latticeChildrenFilter($from->id);
					}
					$objects->order_by('objectrelationships.sortorder');
				}
      }

      //apply optional objectType filter
      $objects = $objects->objectTypeFilter($this->attributes['objectTypeFilter']);

      //apply optional SQL where filter
      if ($where = $this->attributes['where']) { //
         $objects->where($where);
      }

      $objects->publishedFilter();
      $objects = $objects->find_all();

      $items = array();
      foreach ($objects as $includeObject) {
         $itemsData = $includeObject->getContent();
         $items[] = $itemsData;
      }
      return $items;

   }
}

?>


text:
from django.utils.safestring import mark_safe
from menus.menu_pool import menu_pool
from cms.menu_bases import CMSAttachMenu
from menus.base import NavigationNode
from categories.models import Category

class BiddersSubMenu(CMSAttachMenu):
    name = "Bidder SubMenu"

    def get_nodes(self, request):
        nodes = []

        for cat in Category.objects.all():
            node = NavigationNode(
                mark_safe(cat.name),
                cat.get_absolute_url(),
                cat.id
            )
            nodes.append(node)

        return nodes

menu_pool.register_menu(BiddersSubMenu)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml.Schema;

///
/// Set of classes that contain the Agenda server's XML data model.
///

namespace IndicoInterface.NET
{
    namespace IndicoDataModel
    {
        public class iconf
        {
            public string ID; // The ID of the conference.
            public string category; // The category of the actual guy.
            public string title; // Title of the conference.

            public string startDate; // Date when this meeting starts.
            public string endDate; // Date when this meeting ends.

            [XmlElementAttribute("contribution", Form = XmlSchemaForm.Unqualified)]
            public contribution[] contribution; // The contributions.

            [XmlElementAttribute("session", Form = XmlSchemaForm.Unqualified)]
            public session[] session; // Sessions in a conference.

            [XmlElementAttribute("material", Form = XmlSchemaForm.Unqualified)]
            public material[] material; // The material associated with the meeting overall!

            public string _deprecated; // If this data format has been depreciated
        }

        public class session
        {
            public string ID; // ID of the session
            public string title; // title of the session.

            public string startDate; // Time when this thing starts
            public string endDate; // When it will end.

            [XmlElementAttribute("contribution", Form = XmlSchemaForm.Unqualified)]
            public contribution[] contribution; // Contributions in this session.

            [XmlElementAttribute("material", Form = XmlSchemaForm.Unqualified)]
            public material[] material; // Material associated directly with this session
        }

        public class contribution
        {
            public string ID; // ID of the guy.
            public string title; // Title of presentation.
            public string startDate; // Start time of the presentation.
            public string endDate; // When it is supposed to end.
            [XmlElementAttribute("material", Form = XmlSchemaForm.Unqualified)]
            public material[] material; // The material associated with the stuff!
            [XmlElementAttribute("speakers", Form = XmlSchemaForm.Unqualified)]
            public speaker[] speakers;
            [XmlElementAttribute("subcontribution", Form = XmlSchemaForm.Unqualified)]
            public contribution[] subcontributions;
        }

        public class speaker
        {
            [XmlElementAttribute("user", Form = XmlSchemaForm.Unqualified)]
            public userInfo[] users;
        }

        public class userInfo
        {
            public userName name;
        }

        public class userName
        {
            [XmlAttributeAttribute("first")]
            public string first;
            [XmlAttributeAttribute("middle")]
            public string middle;
            [XmlAttributeAttribute("last")]
            public string last;
        }

        public class material
        {
            public string ID; // What is the type
            public string title; // What type of material is this called?
            public string link; // A link to something external for this talk (or whatever).
            public string pdf; // A direct link to a PDF - some agenda servers seem to put this up (!?).
            public string ps; // A direct link to a ps - some agenda servers seem to put this up (!?).
            public string pptx; // A direct link to a pptx - some agenda servers seem to put this up (!?).
            public string ppt; // A direct link to a ppt - some agenda servers seem to put this up (!?).

            public materialFileCollection files; // The file contents
        }

        public class materialFileCollection
        {
            [XmlElementAttribute("file", Form = XmlSchemaForm.Unqualified)]
            public materialFile[] file; // The material associated with the stuff!
        }

        public class materialFile
        {
            public string name; // Name of the file.
            public string type; // The type of the file.
            public string url; // URL where we can get the file.
        }
    }
}


text:
extern alias wpf;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace Granular.Host.Wpf.Render
{
    public class WpfGeometryRenderResource : IGeometryRenderResource
    {
        public wpf::System.Windows.Media.Geometry Geometry { get { return geometryGroup; } }

        private Transform transform;
        public Transform Transform
        {
            get { return transform; }
            set
            {
                if (transform == value)
                {
                    return;
                }

                transform = value;
                geometryGroup.Transform = ((WpfTransformRenderResource)transform.GetRenderResource(factory)).Transform;
            }
        }

        private string data;
        public string Data
        {
            get { return data; }
            set
            {
                if (data == value)
                {
                    return;
                }

                data = value;
                geometryGroup.Children.Clear();
                geometryGroup.Children.Add(wpf::System.Windows.Media.Geometry.Parse(data));
            }
        }

        private WpfRenderElementFactory factory;
        private WpfValueConverter converter;
        private wpf::System.Windows.Media.GeometryGroup geometryGroup;

        public WpfGeometryRenderResource(WpfRenderElementFactory factory, WpfValueConverter converter)
        {
            this.factory = factory;
            this.converter = converter;

            geometryGroup = new wpf::System.Windows.Media.GeometryGroup();
        }
    }
}


text:
package org.kaazing.k3po.driver.internal.netty.bootstrap.http;

import static java.lang.String.format;
import static org.jboss.netty.channel.Channels.fireChannelClosed;
import static org.jboss.netty.channel.Channels.fireChannelDisconnected;
import static org.jboss.netty.channel.Channels.fireChannelInterestChanged;
import static org.jboss.netty.channel.Channels.fireChannelUnbound;
import static org.jboss.netty.channel.Channels.fireExceptionCaught;
import static org.jboss.netty.channel.Channels.fireMessageReceived;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.SWITCHING_PROTOCOLS;
import static org.kaazing.k3po.driver.internal.netty.channel.Channels.fireInputShutdown;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;

public class HttpClientChannelSource extends HttpChannelHandler {

    private HttpClientChannel httpClientChannel;

    public void setHttpChannel(HttpClientChannel httpClientChannel) {
        assert this.httpClientChannel == null;
        this.httpClientChannel = httpClientChannel;
    }

    @Override
    protected void httpMessageReceived(ChannelHandlerContext ctx, MessageEvent e, HttpResponse httpResponse) throws Exception {
        HttpChannelConfig httpChildConfig = httpClientChannel.getConfig();
        httpChildConfig.setStatus(httpResponse.getStatus());
        httpChildConfig.setVersion(httpResponse.getProtocolVersion());
        httpChildConfig.getReadHeaders().set(httpResponse.headers());

        if (httpResponse.getStatus().getCode() == SWITCHING_PROTOCOLS.getCode()) {
            Channel transport = ctx.getChannel();
            ChannelPipeline pipeline = transport.getPipeline();
            pipeline.remove(HttpRequestEncoder.class);

            boolean readable = httpClientChannel.isReadable();
            if (!readable) {
                httpClientChannel.setReadable(true);
                fireChannelInterestChanged(httpClientChannel);
            }

            // propagate any remaining bytes out of replaying decoder (after channel is marked as readable)
            ChannelHandlerContext httpDecoderCtx = pipeline.getContext(HttpResponseDecoder.class);
            HttpResponseDecoder httpDecoder = (HttpResponseDecoder) httpDecoderCtx.getHandler();
            httpDecoder.replace(format("%s.noop", httpDecoderCtx.getName()), NOOP_HANDLER);
        }
        else {
            ChannelBuffer content = httpResponse.getContent();
            boolean readable = httpClientChannel.isReadable();
            if (!readable) {
                httpClientChannel.setReadable(true);
                fireChannelInterestChanged(httpClientChannel);
            }

            if (content.readable()) {
                fireMessageReceived(httpClientChannel, content);
            }

            if (!httpResponse.isChunked()) {
                HttpClientChannel httpClientChannel = this.httpClientChannel;
                this.httpClientChannel = null;
                fireInputShutdown(httpClientChannel);

                boolean wasConnected = httpClientChannel.isConnected();
                boolean wasBound = httpClientChannel.isBound();
                if (httpClientChannel.setClosed()) {
                    if (wasConnected) {
                        fireChannelDisconnected(httpClientChannel);
                    }
                    if (wasBound) {
                        fireChannelUnbound(httpClientChannel);
                    }
                    fireChannelClosed(httpClientChannel);
                }
            }
        }
    }

    @Override
    protected void httpMessageReceived(ChannelHandlerContext ctx, MessageEvent e, HttpChunk httpChunk) throws Exception {
        ChannelBuffer content = httpChunk.getContent();
        if (content.readable()) {
            fireMessageReceived(httpClientChannel, content);
        }

        boolean last = httpChunk.isLast();
        if (last) {
            HttpClientChannel httpClientChannel = this.httpClientChannel;
            if (httpChunk instanceof HttpChunkTrailer) {
                HttpHeaders trailingHeaders = ((HttpChunkTrailer) httpChunk).trailingHeaders();
                httpClientChannel.getConfig().getReadTrailers().set(trailingHeaders);
            }
            this.httpClientChannel = null;
            fireInputShutdown(httpClientChannel);

            if (httpClientChannel.setClosed()) {
                fireChannelDisconnected(httpClientChannel);
                fireChannelUnbound(httpClientChannel);
                fireChannelClosed(httpClientChannel);
            }
        }
    }

    @Override
    protected void httpMessageReceived(ChannelHandlerContext ctx, MessageEvent e, ChannelBuffer message) throws Exception {
        if (message.readable()) {
            // after 101 switching protocols
            fireMessageReceived(httpClientChannel, message);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        if (httpClientChannel != null) {
            HttpClientChannel httpClientChannel = this.httpClientChannel;
            this.httpClientChannel = null;
            if (httpClientChannel.setClosed()) {
                fireExceptionCaught(httpClientChannel, e.getCause());
                fireChannelClosed(httpClientChannel);
            }
        }

        Channel channel = ctx.getChannel();
        channel.close();
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        if (httpClientChannel != null) {
            HttpChannelConfig httpClientConfig = httpClientChannel.getConfig();
            HttpResponseStatus httpStatus = httpClientConfig.getStatus();
            int httpStatusCode = (httpStatus != null) ? httpStatus.getCode() : 0;
            if (httpStatusCode == SWITCHING_PROTOCOLS.getCode()) {
                if (httpClientChannel.setClosed()) {
                    fireChannelDisconnected(httpClientChannel);
                    fireChannelUnbound(httpClientChannel);
                    fireChannelClosed(httpClientChannel);
                }
            }
            else {
                ChannelException exception = new ChannelException("transport closed unexpectedly");
                exception.fillInStackTrace();
                fireExceptionCaught(httpClientChannel, exception);
            }
        }
    }

    @Sharable
    private static class NoopChannelHandler extends SimpleChannelHandler {
    }

    private static final ChannelHandler NOOP_HANDLER = new NoopChannelHandler();
}


text:
use anyhow::{bail, Context, Error};
use rpassword::prompt_password;
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;

use std::{env, str::FromStr};

/// Default name of the environment variable with a master key passphrase.
pub const DEFAULT_MASTER_PASS_ENV_VAR: &str = "EXONUM_MASTER_PASS";

/// A wrapper around `String` which securely erases itself on drop.
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Passphrase(String);

impl Drop for Passphrase {
    fn drop(&mut self) {
        self.0.zeroize();
    }
}

impl Passphrase {
    /// Creates new passphrase
    #[must_use]
    pub const fn new(passphrase: String) -> Self {
        Self(passphrase)
    }

    /// Reads the passphrase from stdin.
    pub fn read_from_tty(prompt: &str) -> Result<Self, Error> {
        Ok(Self(prompt_password(prompt)?))
    }

    /// Returns true if the passphrase is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns byte representation of the passphrase.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }
}

/// Passphrase input method.
///
/// Defaults to `Terminal`.
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum PassInputMethod {
    /// Prompt passphrase from terminal.
    Terminal,
    /// Get passphrase from the environment variable with given name.
    ///
    /// Default value is `EXONUM_MASTER_PASS`.
    /// Defaults are used if `None` is provided.
    EnvVariable(Option<String>),
    /// Passphrase is passed as a command line parameter.
    CmdLineParameter(Passphrase),
}

impl Default for PassInputMethod {
    fn default() -> Self {
        Self::Terminal
    }
}

/// Determines the usage of the passphrase received from user.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PassphraseUsage {
    /// The user will be asked to enter the sane passphrase twice. Empty passphrase is not allowed.
    ///
    /// Unlimited tries are allowed.
    SettingUp,
    /// The user will be asked for a passphrase only once.
    Using,
}

impl PassInputMethod {
    /// Get passphrase using selected method.
    /// Details of this process differs for different secret key types and whether we run node
    /// or generate config files.
    pub fn get_passphrase(self, usage: PassphraseUsage) -> Result<Passphrase, Error> {
        match self {
            Self::Terminal => {
                let prompt = "Enter master key passphrase: ";
                match usage {
                    PassphraseUsage::SettingUp => prompt_passphrase(prompt),
                    PassphraseUsage::Using => Passphrase::read_from_tty(prompt),
                }
            }
            Self::EnvVariable(name) => {
                let variable_name = name.unwrap_or_else(|| DEFAULT_MASTER_PASS_ENV_VAR.to_string());
                let passphrase = env::var(&variable_name).with_context(|| {
                    format!("Failed to get password from env variable {}", variable_name)
                })?;
                Ok(Passphrase(passphrase))
            }
            Self::CmdLineParameter(pass) => Ok(pass),
        }
    }
}

impl FromStr for PassInputMethod {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Ok(Self::default());
        }

        if s == "stdin" {
            return Ok(Self::Terminal);
        }

        if s.starts_with("env") {
            let env_var = s.split(':').nth(1).map(String::from);
            return Ok(Self::EnvVariable(env_var));
        }

        if s.starts_with("pass") {
            let pass = s.split(':').nth(1).unwrap_or_default();
            return Ok(Self::CmdLineParameter(Passphrase(pass.to_owned())));
        }

        bail!("Failed to parse passphrase input method")
    }
}

/// Prompt user for a passphrase. The user must enter the passphrase twice.
/// Passphrase must not be empty.
fn prompt_passphrase(prompt: &str) -> Result<Passphrase, Error> {
    loop {
        let password = Passphrase::read_from_tty(prompt)?;
        if password.is_empty() {
            eprintln!("Passphrase must not be empty. Try again.");
            continue;
        }

        let confirmation = Passphrase::read_from_tty("Enter same passphrase again: ")?;

        if password == confirmation {
            return Ok(password);
        }
        eprintln!("Passphrases do not match. Try again.");
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::{PassInputMethod, Passphrase};

    #[test]
    fn test_pass_input_method_parse() {
        let correct_cases = vec![
            ("", <PassInputMethod as Default>::default()),
            ("", PassInputMethod::Terminal),
            ("stdin", PassInputMethod::Terminal),
            ("env", PassInputMethod::EnvVariable(None)),
            (
                "env:VAR",
                PassInputMethod::EnvVariable(Some("VAR".to_owned())),
            ),
            (
                "pass",
                PassInputMethod::CmdLineParameter(Passphrase("".to_owned())),
            ),
            (
                "pass:PASS",
                PassInputMethod::CmdLineParameter(Passphrase("PASS".to_owned())),
            ),
        ];

        for (inp, out) in correct_cases {
            let method = <PassInputMethod as FromStr>::from_str(inp);
            assert!(method.is_ok());
            assert_eq!(method.unwrap(), out);
        }
    }
}


text:
XHPRof: Test EventDispatcher Argument Functions
Author: beberlei
--FILE--
<?php

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Zend\EventManager\EventManager;
use Doctrine\Common\EventManager as DoctrineEventManager;

include_once dirname(__FILE__).'/common.php';
include_once dirname(__FILE__).'/qafooprofiler_027_classes.php';

class Mage
{
    static public function dispatchEvent($eventName, $params)
    {
    }
}

class Enlight_Event_EventManager
{
    public function filter($event, $value, $args) {}
    public function notify($event, $args) {}
    public function notifyUntil($event, $args) {}
}

function do_action($name, $params) {
}
function apply_filters($name, $params) {
}
function drupal_alter($name, $args) {
}

qafooprofiler_enable(0, array('argument_functions' => array(
    'Symfony\\Component\\EventDispatcher\\EventDispatcher::dispatch',
    'Zend\\EventManager\\EventManager::trigger',
    'Doctrine\\Common\\EventManager::dispatchEvent',
    'Enlight_Event_EventManager::filter',
    'Enlight_Event_EventManager::notify',
    'Enlight_Event_EventManager::notifyUntil',
    'Mage::dispatchEvent',
    'do_action',
    'apply_filters',
    'drupal_alter',
)));

$dispatcher = new EventDispatcher();
$dispatcher->dispatch('foo', new Event());
$dispatcher->dispatch('bar', new Event());

$manager = new EventManager();
$manager->trigger("baz", new \stdClass, array());

$doctrine = new DoctrineEventManager();
$doctrine->dispatchEvent('event', new Event());

$enlight = new Enlight_Event_EventManager();
$enlight->filter("foo", 1234, new Event());
$enlight->notify("bar", new Event());
$enlight->notifyUntil("baz", new Event());

Mage::dispatchEvent('zoomzoom', array());

do_action("foo", array("foo" => "bar"));
apply_filters("foo", array("foo" => "bar"));
drupal_alter("foo", 1, 2, 3, 4);

print_canonical(qafooprofiler_disable());
--EXPECT--
main()                                  : ct=       1; wt=*;
main()==>Doctrine\Common\EventManager::dispatchEvent#event: ct=       1; wt=*;
main()==>Enlight_Event_EventManager::filter#foo: ct=       1; wt=*;
main()==>Enlight_Event_EventManager::notify#bar: ct=       1; wt=*;
main()==>Enlight_Event_EventManager::notifyUntil#baz: ct=       1; wt=*;
main()==>Mage::dispatchEvent#zoomzoom   : ct=       1; wt=*;
main()==>Symfony\Component\EventDispatcher\EventDispatcher::dispatch#bar: ct=       1; wt=*;
main()==>Symfony\Component\EventDispatcher\EventDispatcher::dispatch#foo: ct=       1; wt=*;
main()==>Zend\EventManager\EventManager::trigger#baz: ct=       1; wt=*;
main()==>apply_filters#foo              : ct=       1; wt=*;
main()==>do_action#foo                  : ct=       1; wt=*;
main()==>drupal_alter#foo               : ct=       1; wt=*;
main()==>qafooprofiler_disable          : ct=       1; wt=*;


text:
package org.apache.maven.plugins.war.packaging;

import java.io.File;
import java.io.IOException;

import org.apache.maven.model.Resource;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.war.Overlay;
import org.apache.maven.plugins.war.util.PathSet;
import org.apache.maven.shared.filtering.MavenFilteringException;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.StringUtils;

/**
 * Handles the project own resources, that is: <ul
The list of web resources, if any

The content of the
 * webapp directory if it exists

The custom deployment descriptor(s), if any

The content of the
 * classes directory if it exists

The dependencies of the project

 *
 * @author Stephane Nicoll
 * @version $Id$
 */
public class WarProjectPackagingTask
    extends AbstractWarPackagingTask
{
    private final Resource[] webResources;

    private final File webXml;

    private final File containerConfigXML;

    private final String id;

    private Overlay currentProjectOverlay;

    /**
     * @param webResources {@link #webResources}
     * @param webXml {@link #webXml}
     * @param containerConfigXml {@link #containerConfigXML}
     * @param currentProjectOverlay {@link #currentProjectOverlay}
     */
    public WarProjectPackagingTask( Resource[] webResources, File webXml, File containerConfigXml,
                                    Overlay currentProjectOverlay )
    {
        if ( webResources != null )
        {
            this.webResources = webResources;
        }
        else
        {
            this.webResources = new Resource[0];
        }
        this.webXml = webXml;
        this.containerConfigXML = containerConfigXml;
        this.currentProjectOverlay = currentProjectOverlay;
        this.id = currentProjectOverlay.getId();
    }

    /**
     * {@inheritDoc}
     */
    public void performPackaging( WarPackagingContext context )
        throws MojoExecutionException, MojoFailureException
    {

        context.getLog().info( "Processing war project" );
        // Prepare the INF directories
        File webinfDir = new File( context.getWebappDirectory(), WEB_INF_PATH );
        webinfDir.mkdirs();
        File metainfDir = new File( context.getWebappDirectory(), META_INF_PATH );
        metainfDir.mkdirs();

        handleWebResources( context );

        handeWebAppSourceDirectory( context );

        // Debug mode: dump the path set for the current build
        PathSet pathSet = context.getWebappStructure().getStructure( "currentBuild" );
        context.getLog().debug( "Dump of the current build pathSet content -->" );
        for ( String path : pathSet )
        {
            context.getLog().debug( path );
        }
        context.getLog().debug( "-- end of dump --" );

        handleDeploymentDescriptors( context, webinfDir, metainfDir );

        handleClassesDirectory( context );

        handleArtifacts( context );
    }

    /**
     * Handles the web resources.
     *
     * @param context the packaging context
     * @throws MojoExecutionException if a resource could not be copied
     */
    protected void handleWebResources( WarPackagingContext context )
        throws MojoExecutionException
    {
        for ( Resource resource : webResources )
        {

            // MWAR-246
            if ( resource.getDirectory() == null )
            {
                throw new MojoExecutionException( "The <directory> tag is missing from the <resource> tag." );
            }

            if ( !( new File( resource.getDirectory() ) ).isAbsolute() )
            {
                resource.setDirectory( context.getProject().getBasedir() + File.separator + resource.getDirectory() );
            }

            // Make sure that the resource directory is not the same as the webappDirectory
            if ( !resource.getDirectory().equals( context.getWebappDirectory().getPath() ) )
            {

                try
                {
                    copyResources( context, resource );
                }
                catch ( IOException e )
                {
                    throw new MojoExecutionException( "Could not copy resource [" + resource.getDirectory() + "]", e );
                }
            }
        }
    }

    /**
     * Handles the webapp sources.
     *
     * @param context the packaging context
     * @throws MojoExecutionException if the sources could not be copied
     */
    protected void handeWebAppSourceDirectory( WarPackagingContext context )
        throws MojoExecutionException
    {
        // CHECKSTYLE_OFF: LineLength
        if ( !context.getWebappSourceDirectory().exists() )
        {
            context.getLog().debug( "webapp sources directory does not exist - skipping." );
        }
        else if ( !context.getWebappSourceDirectory().getAbsolutePath().equals( context.getWebappDirectory().getPath() ) )
        {
            context.getLog().info( "Copying webapp resources [" + context.getWebappSourceDirectory() + "]" );
            final PathSet sources =
                getFilesToIncludes( context.getWebappSourceDirectory(), context.getWebappSourceIncludes(),
                                    context.getWebappSourceExcludes(), context.isWebappSourceIncludeEmptyDirectories() );

            try
            {
                copyFiles( id, context, context.getWebappSourceDirectory(), sources, false );
            }
            catch ( IOException e )
            {
                throw new MojoExecutionException( "Could not copy webapp sources ["
                    + context.getWebappDirectory().getAbsolutePath() + "]", e );
            }
        }
        // CHECKSTYLE_ON: LineLength
    }

    /**
     * Handles the webapp artifacts.
     *
     * @param context the packaging context
     * @throws MojoExecutionException if the artifacts could not be packaged
     */
    protected void handleArtifacts( WarPackagingContext context )
        throws MojoExecutionException
    {
        ArtifactsPackagingTask task =
            new ArtifactsPackagingTask( context.getProject().getArtifacts(), currentProjectOverlay );
        task.performPackaging( context );
    }

    /**
     * Handles the webapp classes.
     *
     * @param context the packaging context
     * @throws MojoExecutionException if the classes could not be packaged
     */
    protected void handleClassesDirectory( WarPackagingContext context )
        throws MojoExecutionException
    {
        ClassesPackagingTask task = new ClassesPackagingTask( currentProjectOverlay );
        task.performPackaging( context );
    }

    /**
     * Handles the deployment descriptors, if specified. Note that the behavior here is slightly different since the
     * customized entry always win, even if an overlay has already packaged a web.xml previously.
     *
     * @param context the packaging context
     * @param webinfDir the web-inf directory
     * @param metainfDir the meta-inf directory
     * @throws MojoFailureException if the web.xml is specified but does not exist
     * @throws MojoExecutionException if an error occurred while copying the descriptors
     */
    protected void handleDeploymentDescriptors( WarPackagingContext context, File webinfDir, File metainfDir )
        throws MojoFailureException, MojoExecutionException
    {
        try
        {
            if ( webXml != null && StringUtils.isNotEmpty( webXml.getName() ) )
            {
                if ( !webXml.exists() )
                {
                    throw new MojoFailureException( "The specified web.xml file '" + webXml + "' does not exist" );
                }

                // Making sure that it won't get overlayed
                context.getWebappStructure().registerFileForced( id, WEB_INF_PATH + "/web.xml" );

                if ( context.isFilteringDeploymentDescriptors() )
                {
                    context.getMavenFileFilter().copyFile( webXml, new File( webinfDir, "web.xml" ), true,
                                                           context.getFilterWrappers(), getEncoding( webXml ) );
                }
                else
                {
                    copyFile( context, webXml, new File( webinfDir, "web.xml" ), "WEB-INF/web.xml", true );
                }
            }
            else
            {
                // the webXml can be the default one
                File defaultWebXml = new File( context.getWebappSourceDirectory(), WEB_INF_PATH + "/web.xml" );
                // if exists we can filter it
                if ( defaultWebXml.exists() && context.isFilteringDeploymentDescriptors() )
                {
                    context.getWebappStructure().registerFile( id, WEB_INF_PATH + "/web.xml" );
                    context.getMavenFileFilter().copyFile( defaultWebXml, new File( webinfDir, "web.xml" ), true,
                                                           context.getFilterWrappers(), getEncoding( defaultWebXml ) );
                }
            }

            if ( containerConfigXML != null && StringUtils.isNotEmpty( containerConfigXML.getName() ) )
            {
                String xmlFileName = containerConfigXML.getName();

                context.getWebappStructure().registerFileForced( id, META_INF_PATH + "/" + xmlFileName );

                if ( context.isFilteringDeploymentDescriptors() )
                {
                    context.getMavenFileFilter().copyFile( containerConfigXML, new File( metainfDir, xmlFileName ),
                                                           true, context.getFilterWrappers(),
                                                           getEncoding( containerConfigXML ) );
                }
                else
                {
                    copyFile( context, containerConfigXML, new File( metainfDir, xmlFileName ), "META-INF/"
                        + xmlFileName, true );
                }
            }
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( "Failed to copy deployment descriptor", e );
        }
        catch ( MavenFilteringException e )
        {
            throw new MojoExecutionException( "Failed to copy deployment descriptor", e );
        }
    }

    /**
     * Copies webapp webResources from the specified directory.
     *
     * @param context the WAR packaging context to use
     * @param resource the resource to copy
     * @throws IOException if an error occurred while copying the resources
     * @throws MojoExecutionException if an error occurred while retrieving the filter properties
     */
    public void copyResources( WarPackagingContext context, Resource resource )
        throws IOException, MojoExecutionException
    {
        if ( !context.getWebappDirectory().exists() )
        {
            context.getLog().warn( "Not copying webapp webResources [" + resource.getDirectory()
                                       + "]: webapp directory [" + context.getWebappDirectory().getAbsolutePath()
                                       + "] does not exist!" );
        }

        context.getLog().info( "Copying webapp webResources [" + resource.getDirectory() + "] to ["
                                   + context.getWebappDirectory().getAbsolutePath() + "]" );
        String[] fileNames = getFilesToCopy( resource );
        for ( String fileName : fileNames )
        {
            String targetFileName = fileName;
            if ( resource.getTargetPath() != null )
            {
                // TODO make sure this thing is 100% safe
                // MWAR-129 if targetPath is only a dot <targetPath>.</targetPath> or ./
                // and the Resource is in a part of the warSourceDirectory the file from sources will override this
                // that's we don't have to add the targetPath yep not nice but works
                if ( !StringUtils.equals( ".", resource.getTargetPath() )
                    && !StringUtils.equals( "./", resource.getTargetPath() ) )
                {
                    targetFileName = resource.getTargetPath() + File.separator + targetFileName;
                }
            }
            if ( resource.isFiltering() && !context.isNonFilteredExtension( fileName ) )
            {
                copyFilteredFile( id, context, new File( resource.getDirectory(), fileName ), targetFileName );
            }
            else
            {
                copyFile( id, context, new File( resource.getDirectory(), fileName ), targetFileName );
            }
        }
    }

    /**
     * Returns a list of filenames that should be copied over to the destination directory.
     *
     * @param resource the resource to be scanned
     * @return the array of filenames, relative to the sourceDir
     */
    private String[] getFilesToCopy( Resource resource )
    {
        // CHECKSTYLE_OFF: LineLength
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir( resource.getDirectory() );
        if ( resource.getIncludes() != null && !resource.getIncludes().isEmpty() )
        {
            scanner.setIncludes( (String[]) resource.getIncludes().toArray( new String[resource.getIncludes().size()] ) );
        }
        else
        {
            scanner.setIncludes( DEFAULT_INCLUDES );
        }
        if ( resource.getExcludes() != null && !resource.getExcludes().isEmpty() )
        {
            scanner.setExcludes( (String[]) resource.getExcludes().toArray( new String[resource.getExcludes().size()] ) );
        }

        scanner.addDefaultExcludes();

        scanner.scan();

        return scanner.getIncludedFiles();
        // CHECKSTYLE_ON: LineLength
    }
}


text:
using ExtendedXmlSerializer.Core;

namespace ExtendedXmlSerializer.Samples.Introduction
{
	public sealed class Run : ICommand<object>
	{
		public static Run Default { get; } = new Run();
		Run() {}

		public void Execute(object parameter)
		{
			Create.Default.Execute(null);
			Type.Default.Execute(null);
			Member.Default.Execute(null);
		}
	}
}


text:
//
//  XKWebViewController.h
//  百思不得姐
//
//  Created by MD313  on 15/9/7.
//  Copyright (c) 2015年 xiaokai. All rights reserved.
//

#import <UIKit/UIKit.h>
@class XKSquare;

@interface XKWebViewController : UIViewController

@property(nonatomic,strong) XKSquare *square;/**< 模型数据 */

@end


text:
<?php

namespace Phwoolcon\Tests\Integration\Http;

use Phwoolcon\Exception\HttpClientException;
use Phwoolcon\Http\Client;
use Phwoolcon\Tests\Helper\TestCase;

class ClientTest extends TestCase
{
    /**
     * @var Client
     */
    protected $client;

    public function setUp()
    {
        parent::setUp();
        Client::register($this->di);
        $this->client = Client::getInstance();
    }

    public function testGet()
    {
        $client = $this->client;

        $url = 'https://phwoolcon.org/';
        $response = Client::get($url);
        $this->assertNotEmpty($response);
        $this->assertNotEmpty($headers = $client->getLastResponseHeaders());
        $this->assertArrayHasKey('content-type', $headers);
        $this->assertEquals(200, $client->getLastResponseCode());
        $this->assertEquals($url, $client->getLastRequest()['url']);
        $this->assertEquals($response, $client->getLastResponse());

        $url = 'https://phwoolcon.org/catalog';
        $response = Client::get($url, ['state' => 'closed']);
        $this->assertNotEmpty($response);
        $this->assertNotEmpty($headers = $client->getLastResponseHeaders());
        $this->assertArrayHasKey('content-type', $headers);
        $this->assertEquals(200, $client->getLastResponseCode());
        $this->assertEquals($url, $client->getLastRequest()['url']);
        $this->assertEquals($response, $client->getLastResponse());
    }

    public function testHead()
    {
        $client = $this->client;

        $url = 'https://phwoolcon.org/';
        $response = Client::head($url);
        $this->assertEmpty($response);
        $this->assertNotEmpty($headers = $client->getLastResponseHeaders());
        $this->assertArrayHasKey('content-type', $headers);
        $this->assertEquals(200, $client->getLastResponseCode());
        $this->assertEquals($url, $client->getLastRequest()['url']);
        $this->assertEquals($response, $client->getLastResponse());
    }

    public function testPost()
    {
        $client = $this->client;

        $url = 'https://phwoolcon.org/account/login';
        $response = Client::post($url, '{"scopes":["public_repo"]}');
        $this->assertNotEmpty($response);
        $this->assertNotEmpty($headers = $client->getLastResponseHeaders());
        $this->assertArrayHasKey('content-type', $headers);
        $this->assertEquals(403, $client->getLastResponseCode());
        $this->assertEquals($url, $client->getLastRequest()['url']);
        $this->assertEquals($response, $client->getLastResponse());
    }

    public function testCustomMethod()
    {
        $client = $this->client;

        $url = 'https://phwoolcon.org/some-thing-that-not-exists';
        $response = Client::request($url, '', 'DELETE');
        $this->assertNotEmpty($response);
        $this->assertNotEmpty($headers = $client->getLastResponseHeaders());
        $this->assertArrayHasKey('content-type', $headers);
        $this->assertEquals(404, $client->getLastResponseCode());
        $this->assertEquals($url, $client->getLastRequest()['url']);
        $this->assertEquals($response, $client->getLastResponse());
    }

    public function testErrorAndCustomDns()
    {
        $client = $this->client;
        $options = $client->getOptions();
        $invalidIp = '192.0.2.1';
        $customDns = "api.no-this-site.dev:80:{$invalidIp}";

        ob_start();
        $stdOut = fopen('php://output', 'w');
        $client->setOptions(array_replace($options, [
            'custom_dns'   => [$customDns],
            'curl_options' => [
                CURLOPT_CONNECTTIMEOUT_MS => 100,
                CURLOPT_VERBOSE           => true,
                CURLOPT_STDERR            => $stdOut,
            ],
        ]));

        $url = 'http://api.no-this-site.dev/';
        $response = null;
        $e = null;
        try {
            $response = Client::get($url);
        } catch (\Exception $e) {
        }
        fclose($stdOut);
        $verboseInfo = ob_get_clean();
        $client->setOptions($options);

        $this->assertInstanceOf(HttpClientException::class, $e);

        $this->assertContains("Added {$customDns} to DNS cache", $verboseInfo);
        $this->assertContains("Trying {$invalidIp}...", $verboseInfo);

        $this->assertNull($response);
        $this->assertNull($client->getLastResponse());
        $this->assertEmpty($client->getLastResponseHeaders());
        $this->assertEquals($url, $client->getLastCurlInfo()['url']);
        $this->assertEquals(0, $client->getLastResponseCode());
        $this->assertEquals($url, $client->getLastRequest()['url']);
    }
}


text:
namespace fst {

FST_CONSTEXPR const uint32 kEqualFsts = 0x0001;
FST_CONSTEXPR const uint32 kEqualFstTypes = 0x0002;
FST_CONSTEXPR const uint32 kEqualCompatProperties = 0x0004;
FST_CONSTEXPR const uint32 kEqualCompatSymbols = 0x0008;
FST_CONSTEXPR const uint32 kEqualAll =
    kEqualFsts | kEqualFstTypes | kEqualCompatProperties | kEqualCompatSymbols;

// Tests if two Fsts have the same states and arcs in the same order (when
// etype & kEqualFst).
// Also optional checks equality of Fst types (etype & kEqualFstTypes) and
// compatibility of stored properties (etype & kEqualCompatProperties) and
// of symbol tables (etype & kEqualCompatSymbols).
template <class Arc>
bool Equal(const Fst<Arc> &fst1, const Fst<Arc> &fst2, float delta = kDelta,
           uint32 etype = kEqualFsts) {
  if ((etype & kEqualFstTypes) && (fst1.Type() != fst2.Type())) {
    VLOG(1) << "Equal: Mismatched FST types (" << fst1.Type() << " != "
            << fst2.Type() << ")";
    return false;
  }
  if ((etype & kEqualCompatProperties) &&
      !CompatProperties(fst1.Properties(kCopyProperties, false),
                        fst2.Properties(kCopyProperties, false))) {
    VLOG(1) << "Equal: Properties not compatible";
    return false;
  }
  if (etype & kEqualCompatSymbols) {
    if (!CompatSymbols(fst1.InputSymbols(), fst2.InputSymbols(), false)) {
      VLOG(1) << "Equal: Input symbols not compatible";
      return false;
    }
    if (!CompatSymbols(fst1.OutputSymbols(), fst2.OutputSymbols(), false)) {
      VLOG(1) << "Equal: Output symbols not compatible";
      return false;
    }
  }
  if (!(etype & kEqualFsts)) return true;
  if (fst1.Start() != fst2.Start()) {
    VLOG(1) << "Equal: Mismatched start states (" << fst1.Start() << " != "
            << fst2.Start() << ")";
    return false;
  }
  StateIterator<Fst<Arc>> siter1(fst1);
  StateIterator<Fst<Arc>> siter2(fst2);
  while (!siter1.Done() || !siter2.Done()) {
    if (siter1.Done() || siter2.Done()) {
      VLOG(1) << "Equal: Mismatched number of states";
      return false;
    }
    const auto s1 = siter1.Value();
    const auto s2 = siter2.Value();
    if (s1 != s2) {
      VLOG(1) << "Equal: Mismatched states (" << s1 << "!= "
              << s2 << ")";
      return false;
    }
    const auto &final1 = fst1.Final(s1);
    const auto &final2 = fst2.Final(s2);
    if (!ApproxEqual(final1, final2, delta)) {
      VLOG(1) << "Equal: Mismatched final weights at state " << s1
              << " (" << final1 << " != " << final2 << ")";
      return false;
    }
    ArcIterator<Fst<Arc>> aiter1(fst1, s1);
    ArcIterator<Fst<Arc>> aiter2(fst2, s2);
    for (auto a = 0; !aiter1.Done() || !aiter2.Done(); ++a) {
      if (aiter1.Done() || aiter2.Done()) {
        VLOG(1) << "Equal: Mismatched number of arcs at state " << s1;
        return false;
      }
      const auto &arc1 = aiter1.Value();
      const auto &arc2 = aiter2.Value();
      if (arc1.ilabel != arc2.ilabel) {
        VLOG(1) << "Equal: Mismatched arc input labels at state " << s1
                << ", arc " << a << " (" << arc1.ilabel << " != "
                << arc2.ilabel << ")";
        return false;
      } else if (arc1.olabel != arc2.olabel) {
        VLOG(1) << "Equal: Mismatched arc output labels at state " << s1
                << ", arc " << a << " (" << arc1.olabel << " != "
                << arc2.olabel << ")";
        return false;
      } else if (!ApproxEqual(arc1.weight, arc2.weight, delta)) {
        VLOG(1) << "Equal: Mismatched arc weights at state " << s1
                << ", arc " << a << " (" << arc1.weight << " != "
                << arc2.weight << ")";
        return false;
      } else if (arc1.nextstate != arc2.nextstate) {
        VLOG(1) << "Equal: Mismatched next state at state " << s1
                << ", arc " << a << " (" << arc1.nextstate << " != "
                << arc2.nextstate << ")";
        return false;
      }
      aiter1.Next();
      aiter2.Next();
    }
    // Sanity checks: should never fail.
    if (fst1.NumArcs(s1) != fst2.NumArcs(s2)) {
      FSTERROR() << "Equal: Inconsistent arc counts at state " << s1
                 << " (" << fst1.NumArcs(s1) << " != "
                 << fst2.NumArcs(s2) << ")";
      return false;
    }
    if (fst1.NumInputEpsilons(s1) != fst2.NumInputEpsilons(s2)) {
      FSTERROR() << "Equal: Inconsistent input epsilon counts at state " << s1
                 << " (" << fst1.NumInputEpsilons(s1) << " != "
                 << fst2.NumInputEpsilons(s2) << ")";
      return false;
    }
    if (fst1.NumOutputEpsilons(s1) != fst2.NumOutputEpsilons(s2)) {
      FSTERROR() << "Equal: Inconsistent output epsilon counts at state " << s1
                 << " (" << fst1.NumOutputEpsilons(s1) << " != "
                 << fst2.NumOutputEpsilons(s2) << ")";
    }
    siter1.Next();
    siter2.Next();
  }
  return true;
}

}  // namespace fst

#endif  // FST_EQUAL_H_


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

package org.bondlib;

import java.io.IOException;

/**
 * Resposible for marshaling of objects.
 */
public final class Marshal {

    // prevent instantiation
    private Marshal() {
    }

    /**
     * Marshals a struct object using the given protocol writer.
     *
     * @param obj       object to marshal
     * @param writer    protocol writer
     * @param <TStruct> the type of the object
     * @throws IOException if an I/O error occurred
     */
    public static <TStruct extends BondSerializable> void marshal(TStruct obj, ProtocolWriter writer)
            throws IOException {
        ArgumentHelper.ensureNotNull(obj, "obj");
        ArgumentHelper.ensureNotNull(writer, "writer");
        Serializer<TStruct> serializer = new Serializer<TStruct>();
        writer.writeVersion();
        serializer.serialize(obj, writer);
    }

    /**
     * Marshals a Bonded object using the given protocol writer.
     *
     * @param obj       Bonded object to marshal
     * @param writer    protocol writer
     * @param <TStruct> the type of the object
     * @throws IOException if an I/O error occurred
     */
    public static <TStruct extends BondSerializable> void marshal(Bonded<? extends TStruct> obj, ProtocolWriter writer)
            throws IOException {
        ArgumentHelper.ensureNotNull(obj, "obj");
        ArgumentHelper.ensureNotNull(writer, "writer");
        writer.writeVersion();
        obj.serialize(writer);
    }
}


text:
<?php

namespace Sadekbaroudi\OperationState;

use Sadekbaroudi\OperationState\OperationStateException;

/**
 * This class defines an Operation State. You set actions to execute, and all the
 * appropriate undo actions for those execute actions. You can then use the OperationStateManager
 * class to keep track of what has been executed, and what needs to be undone.
 *
 * @author sadekbaroudi
 */
class OperationState {

    const NO_ARGUMENT = 'SorryYouCanNeverUseThisStringAsAnArgument';

    /**
     * This is the generated key that persists throughout the existence of this object
     * @var string
     */
    protected $key;

    /**
     * @var array An array of arrays, containing the actions to be executed
     */
    protected $executeParameters = array();

    /**
     * @var array An array of arrays, containing the actions to undo the executed actions
     */
    protected $undoParameters = array();

    /**
     * Getter for the executeParameters
     * @return array
     */
    public function getExecute()
    {
        return $this->executeParameters;
    }

    /**
     * Getter for the undoParameters
     * @return array
     */
    public function getUndo()
    {
        return $this->undoParameters;
    }

    /**
     * This will clear the current set of execute actions, and add the passed action
     *
     * @param mixed $callable php is_callable compliant call
     * @param array $arguments php is_callable compliant arguments, or OperationState::NO_ARGUMENT if none
     * @return \Sadekbaroudi\OperationState\OperationState
     */
    public function setExecute($callable, $arguments)
    {
        $this->clearExecute();

        $this->addExecute($callable, $arguments);

        return $this;
    }

    /**
     * This will add the passed action to the list of execute actions to be called
     *
     * @param mixed $callable php is_callable compliant call
     * @param array $arguments php is_callable compliant arguments, or OperationState::NO_ARGUMENT if none
     * @return \Sadekbaroudi\OperationState\OperationState
     */
    public function addExecute($callable, $arguments)
    {
        $this->executeParameters[] = array(
        	'callable' => $callable,
            'arguments' => $arguments,
        );

        return $this;
    }

    /**
     * This will clear all the execute actions from the queue
     */
    protected function clearExecute()
    {
        $this->executeParameters = array();
    }

    /**
     * This will execute all the actions in the queue. It will not clear the queue!
     *
     * @return array returns the results of the executed actions, with OperationState->getKey() as the array keys
     */
    public function execute()
    {
        $returnValues = array();

        while ($execute = array_shift($this->executeParameters)) {
            $returnValues[] = $this->run($execute);
        }

        return $returnValues;
    }

    /**
     * This will clear the current set of undo actions, and add the passed action
     *
     * @param mixed $callable php is_callable compliant call
     * @param array $arguments php is_callable compliant arguments, or OperationState::NO_ARGUMENT if none
     * @return \Sadekbaroudi\OperationState\OperationState
     */
    public function setUndo($callable, $arguments)
    {
        $this->clearUndo();

        $this->addUndo($callable, $arguments);

        return $this;
    }

    /**
     * This will add the passed action to the list of undo actions to be called
     *
     * @param mixed $callable php is_callable compliant call
     * @param array $arguments php is_callable compliant arguments, or OperationState::NO_ARGUMENT if none
     * @return \Sadekbaroudi\OperationState\OperationState
     */
    public function addUndo($callable, $arguments)
    {
        $this->undoParameters[] = array(
        	'callable' => $callable,
            'arguments' => $arguments,
        );

        return $this;
    }

    /**
     * This will clear all the execute actions from the queue
     */
    protected function clearUndo()
    {
        $this->undoParameters = array();
    }

    /**
     * This will execute all the undo actions in the queue. It will not clear the queue!
     *
     * @return array returns the results of the undo actions, with OperationState->getKey() as the array keys
     */
    public function undo()
    {
        $returnValues = array();
        while ($undo = array_shift($this->undoParameters)) {
            $returnValues[] = $this->run($undo);
        }

        return $returnValues;
    }

    /**
     * This will run the action passed, whether execute or undo.
     *
     * @param array $call Contains 'callable' index supporting is_callable and 'arguments' (NULL or args).
     *                    You can also pass OperationState::NO_ARGUMENT as an argument to call with no argument
     * @throws \RuntimeException
     * @return mixed returns the result of the method call
     */
    protected function run($call)
    {
        if (!isset($call['callable'])) {
            throw new OperationStateException("\$call['callable'] was not set");
        }

        if (!isset($call['arguments'])) {
            try {
                is_null($call['arguments']);
            } catch (\Exception $e) {
                throw new OperationStateException("\$call['arguments'] was not set");
            }
        }

        if (is_callable($call['callable'])) {
            if ($call['arguments'] == self::NO_ARGUMENT) {
                return call_user_func($call['callable']);
            } else {
                return call_user_func_array($call['callable'], $call['arguments']);
            }
        } else {
            throw new OperationStateException("\$call and \$arguments passed did not pass is_callable() check");
        }
    }

    /**
     * Get the a unique key for this object. It should return the same value regardless of when this function is called!
     *
     * @return string
     */
    public function getKey()
    {
        if (!isset($this->key)) {
            $this->key = md5(microtime().rand());
        }
        return $this->key;
    }
}


text:
"""

https://openclassrooms.com/courses/apprenez-a-programmer-en-python/le-reseau

À LA FIN LE TERMINAL QUITTE PYTHON :
DONC CE PROGRAMME NE MARCHE PAS !!

"""
# Les deux lignes précédentes serviraient si je rendais ce fichier
# directement exécutable

import socket

# Construire notre socket      :    LE SERVEUR
#   socket.AF_INET : la famille d'adresses, ici ce sont des adresses Internet ;
#
#     socket.SOCK_STREAM : le type du socket, SOCK_STREAM pour le protocole TCP.

connexion_principale = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print("connexion_principale :\n",connexion_principale)

# Connecter le socket

#  le nom de l'hôte sera vide et le port sera celui que vous voulez, entre 1024 et 65535.

connexion_principale.bind(("",12800))  # l'argument unique de bind est un tuple !!
print("bind :\n",connexion_principale.bind)

# Faire écouter notre socket

connexion_principale.listen(5)
print("listen :\n",connexion_principale.listen)
print("salute")

# +++                 Il y a donc deux ports dans notre histoire    +++
#
# mais celui qu'utilise le client
#  pour ouvrir sa connexion ne va pas nous intéresser.

connexion_avec_client,infos_connexion = connexion_principale.accept()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="shortcut icon" type="image/png" href="images/favicon.png"/>

    <title>Bolli Bau AG</title>

    <link href="https://www.landolt-bau.ch/css/bootstrap.min.css" rel="stylesheet">

    <link href="https://www.landolt-bau.ch/css/modern-business.css" rel="stylesheet">
    <link href="https://www.landolt-bau.ch/css/style.css" rel="stylesheet">

    <link href="https://www.landolt-bau.ch/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

Home

Kontakt

Wegbeschreibung

Wegbeschreibung

Unsere Büroräumlichkeiten befinden sich in Schaffhausen-Schweizersbild

Bolli Bau AG

Bauunternehmung
Längenbergstrasse 7
8200 Schaffhausen

  052 643 46 00

  043 433 43 44

 mail@bolli-bau.ch


text:
require 'funkytown/system'
require 'funkytown/funkytown_config'

module Funkytown
  class FunkytownTask
    attr_accessor :rails_env, :rails_root, :env
    attr_accessor :fail_if_remote_servants_not_running

    def initialize(rails_env = RAILS_ENV, rails_root = RAILS_ROOT, env = ENV, options = {})
      @rails_env = rails_env
      @rails_root = rails_root
      @env = env
      @system = SYSTEM
      @uid = Time.now.to_i

  # todo: refactor
  # Load options from host-specific yml file and set as instance vars
      options = FunkytownConfig.load.merge(options)
      options.keys.each do |key|
        instance_variable_set "@#{key}", options[key.to_sym]
      end

      say "Options #{options.to_yaml}", :when_verbose => true

      check_requirements
    end

    def start_servant
      servant = localhost_servant
      if servant.nil?
        say "No local servants found to start"
      else
        run_local_servant(servant)
      end
    end

    def stop_servant
      servant = localhost_servant
      if servant.nil?
        say "No local servants found to stop"
      elsif !servant.is_running?
        say "Servant not running on #{servant.host}:#{servant.port}"
      else
        servant.stop
        System.wait_for {!servant.is_running?}
        say "Servant stopped on #{servant.host}:#{servant.port}"
      end
    end

    def run_local_servant(servant)
      raise "You can't run a non-local servant" unless is_localhost?(servant.host)

      if servant.is_running?
        say "Servant already running on #{servant.host}:#{servant.port}"
      else
        say "Servant not found on #{servant.host}:#{servant.port}"
        if is_localhost?(servant.host)
          say "Launching #{servant.name} on port #{servant.port}"
          servant.start
          System.wait_for {servant.is_running?}
          say "Servant now running on #{servant.host}:#{servant.port}"
        end
      end
    end

    #todo: test
    def result(test)
      out = ''
      result_url = ''
      capturing = false
      File.open(test.logfile.filename).each do |line|
        line.gsub!(/^.*\[junit\] /,'')
        if line =~ /^Testcase: /
          capturing = true
        elsif line =~ /The result log is at/
          capturing = false
          result_url = /http[\S]+/.match(line).to_s
        end
        if capturing
          out = out + line
        end
      end
      say "Result XML: #{result_url}" unless result_url.empty?
      out
    end

    def localhost_servant
      localhost_servant_host.nil? ? nil : servant_process(localhost_servant_host)
    end

    def localhost_servant_host
      servant_hosts.detect {|host| is_localhost?(host)}
    end

    def is_localhost?(host)
      host == Socket.gethostname.downcase.chomp || host == "localhost" || host == "127.0.0.1"
    end

#    def latest_failure
#      results = Dir.glob("#{@logdir}/JSTEST-*")
#      latest = results.sort.last
#      XmlSimple.new.xml_in(latest).to_yaml
#    end

    def check_servants
      servant_hosts.each do |servant_host|
        say "checking #{servant_host}"
        check_servant(servant_host)
      end
      say "done checking"
    end

    def check_servant(servant_host)
      servant = servant_process(servant_host)
      if !servant.is_running?
        if is_localhost?(servant_host)
          run_local_servant(servant)
        elsif @fail_if_remote_servants_not_running
          raise "Servant not found on #{servant_host}"
        else
          say "Warning: Servant not found on #{servant_host}"
          servant_hosts.delete(servant_host)
        end
      end
    end

    protected

    def servant_process(servant_host)
      process({
        :name => servant_name(servant_host),
        :cmd => servant_cmd(servant_host),
        :host => servant_host,
        :port => servant_port(servant_host),
        :logdir => @logdir
      })
    end

    def check_requirements
      raise NotImplementedError.new("this is abstract!")
    end

    def servant_hosts
      raise NotImplementedError.new("this is abstract!")
    end

    def servant_name(host)
      raise NotImplementedError.new("this is abstract!")
    end

    def servant_port(host)
      raise NotImplementedError.new("this is abstract!")
    end

    def servant_cmd(host)
      raise NotImplementedError.new("this is abstract!")
    end

    def say(msg, options = {})
      SYSTEM.say(msg, options)
    end

    def process(options)
      say "creating process #{options.inspect}" if debug?
      System::Activity.new(options)
    end

  end
end


text:
#ifndef _FNVECTOR_H
#define _FNVECTOR_H

#ifdef __cplusplus  /* wrapper to enable C++ usage */
extern "C" {
#endif

#ifndef _SUNDIALS_CONFIG_H
#define _SUNDIALS_CONFIG_H
#include <sundials/sundials_config.h>
#endif

/* SUNDIALS solver IDs */

#define FCMIX_CVODE   1
#define FCMIX_IDA     2
#define FCMIX_KINSOL  3
#define FCMIX_ARKODE  4

#ifdef __cplusplus
}
#endif

#endif


text:
package org.openecard.android.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import org.openecard.common.I18n;

/**
 * The UnexpectedErrorAlertDialog shows an AlertDialog in it's run-method describing that there was an unexpected
 * Problem and gives the user the possibility to view the log of the App.
 *
 * @author Dirk Petrautzki <petrautzki@hs-coburg.de>
 */
final class UnexpectedErrorAlertDialog implements Runnable {

    private final Activity ctx;
    private final I18n lang = I18n.getTranslation("android");

    UnexpectedErrorAlertDialog(Activity ctx) {
	this.ctx = ctx;
    }

    @Override
    public void run() {
	AlertDialog ad = new AlertDialog.Builder(ctx).create();
	ad.setCancelable(false); // This blocks the 'BACK' button

	// add description of the error
	ad.setMessage(lang.translationForKey("android.error.unexpected"));

	// Add close button
	ad.setButton(lang.translationForKey("android.dialogs.quit"), new DialogInterface.OnClickListener() {
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		dialog.dismiss();
		ctx.finish();
	    }
	});

	// Add more info button
	ad.setButton2(lang.translationForKey("android.error.ext_apdu.more"), new DialogInterface.OnClickListener() {
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		Intent intent = new Intent(ctx, LogViewerActivity.class);
		ctx.startActivity(intent);
	    }
	});

	// finally show the dialog
	ad.show();
    }

}


text:
package org.apache.shardingsphere.example.core.api.entity;

import java.io.Serializable;

public class Order implements Serializable {

    private static final long serialVersionUID = 661434701950670670L;

    private long orderId;

    private int userId;

    private long addressId;

    private String status;

    public long getOrderId() {
        return orderId;
    }

    public void setOrderId(final long orderId) {
        this.orderId = orderId;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(final int userId) {
        this.userId = userId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(final String status) {
        this.status = status;
    }

    public long getAddressId() {
        return addressId;
    }

    public void setAddressId(final long addressId) {
        this.addressId = addressId;
    }

    @Override
    public String toString() {
        return String.format("order_id: %s, user_id: %s, address_id: %s, status: %s", orderId, userId, addressId, status);
    }
}