text:
namespace base {
class SingleThreadTaskRunner;
class TimeDelta;
}

namespace syncer {
class SyncError;
}

namespace sync_driver {
class AssociatorInterface;
class ChangeProcessor;
class SyncClient;
}

namespace browser_sync {

// Implementation for datatypes that reside on the frontend thread
// (UI thread). This is the same thread we perform initialization on, so we
// don't have to worry about thread safety. The main start/stop funtionality is
// implemented by default.
// Derived classes must implement (at least):
//    syncer::ModelType type() const
//    void CreateSyncComponents();
// NOTE: This class is deprecated! New sync datatypes should be using the
// syncer::SyncableService API and the UIDataTypeController instead.
// TODO(zea): Delete this once all types are on the new API.
class FrontendDataTypeController
    : public sync_driver::DirectoryDataTypeController {
 public:
  FrontendDataTypeController(
      const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread,
      const base::Closure& error_callback,
      sync_driver::SyncClient* sync_client);

  // DataTypeController interface.
  void LoadModels(const ModelLoadCallback& model_load_callback) override;
  void StartAssociating(const StartCallback& start_callback) override;
  void Stop() override;
  syncer::ModelType type() const override = 0;
  syncer::ModelSafeGroup model_safe_group() const override;
  std::string name() const override;
  State state() const override;

  // DataTypeErrorHandler interface.
  void OnSingleDataTypeUnrecoverableError(
      const syncer::SyncError& error) override;

 protected:
  friend class FrontendDataTypeControllerMock;

  // For testing only.
  FrontendDataTypeController();
  ~FrontendDataTypeController() override;

  // Kick off any dependent services that need to be running before we can
  // associate models. The default implementation is a no-op.
  // Return value:
  //   True - if models are ready and association can proceed.
  //   False - if models are not ready. Associate() should be called when the
  //           models are ready. Refer to Start(_) implementation.
  virtual bool StartModels();

  // Datatype specific creation of sync components.
  virtual void CreateSyncComponents() = 0;

  // Perform any DataType controller specific state cleanup before stopping
  // the datatype controller. The default implementation is a no-op.
  virtual void CleanUpState();

  // Helper method for cleaning up state and running the start callback.
  virtual void StartDone(
      ConfigureResult start_result,
      const syncer::SyncMergeResult& local_merge_result,
      const syncer::SyncMergeResult& syncer_merge_result);

  // Record association time.
  virtual void RecordAssociationTime(base::TimeDelta time);
  // Record causes of start failure.
  virtual void RecordStartFailure(ConfigureResult result);

  virtual sync_driver::AssociatorInterface* model_associator() const;
  virtual void set_model_associator(
      sync_driver::AssociatorInterface* associator);
  sync_driver::ChangeProcessor* GetChangeProcessor() const override;
  virtual void set_change_processor(sync_driver::ChangeProcessor* processor);

  // Handles the reporting of unrecoverable error. It records stuff in
  // UMA and reports to breakpad.
  // Virtual for testing purpose.
  virtual void RecordUnrecoverableError(
      const tracked_objects::Location& from_here,
      const std::string& message);

  // If the DTC is waiting for models to load, once the models are
  // loaded the datatype service will call this function on DTC to let
  // us know that it is safe to start associating.
  void OnModelLoaded();

  sync_driver::SyncClient* const sync_client_;

  State state_;

  StartCallback start_callback_;
  ModelLoadCallback model_load_callback_;

  // TODO(sync): transition all datatypes to SyncableService and deprecate
  // AssociatorInterface.
  scoped_ptr<sync_driver::AssociatorInterface> model_associator_;
  scoped_ptr<sync_driver::ChangeProcessor> change_processor_;

 private:
  // Build sync components and associate models.
  virtual void Associate();

  void AbortModelLoad();

  // Clean up our state and state variables. Called in response
  // to a failure or abort or stop.
  void CleanUp();

  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(FrontendDataTypeController);
};

}  // namespace browser_sync

#endif  // COMPONENTS_SYNC_DRIVER_FRONTEND_DATA_TYPE_CONTROLLER_H__


text:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin

class TwitterRecentEntries(CMSPlugin):
    title = models.CharField(_('title'), max_length=75, blank=True)
    twitter_user = models.CharField(_('twitter user'), max_length=75)
    count = models.PositiveSmallIntegerField(_('count'), help_text=_('Number of entries to display'), default=3)
    link_hint = models.CharField(_('link hint'), max_length=75, blank=True, help_text=_('If given, the hint is displayed as link to your Twitter profile.'))

    def __unicode__(self):
        return self.title

redpajama_set_name: RedPajamaGithub


text:
package May2021Leetcode;

public class _1578MinimumDeletionCostToAvoidRepeatingLetters {
	public static void main(String[] args) {
		System.out.println(minCost("abaac", new int[] { 1, 2, 3, 4, 5 }));
		System.out.println(minCost("abc", new int[] { 1, 2, 3 }));
		System.out.println(minCost("aabaa", new int[] { 1, 2, 3, 4, 1 }));
		System.out.println(minCost("bbbaaa", new int[] { 4, 9, 3, 8, 8, 9 }));
	}

	public static int minCost(String s, int[] cost) {

	}
}


text:
package com.google.blockly.android.ui.fieldview;

import android.content.Context;
import android.support.v7.widget.AppCompatCheckBox;
import android.util.AttributeSet;
import android.widget.CompoundButton;

import com.google.blockly.model.Field;
import com.google.blockly.model.FieldCheckbox;

/**
 * Renders a checkbox as part of a BlockView.
 */
public class BasicFieldCheckboxView extends AppCompatCheckBox implements FieldView {
    protected final Field.Observer mFieldObserver = new Field.Observer() {
        @Override
        public void onValueChanged(Field field, String oldStrValue, String newStrValue) {
            setChecked(mCheckboxField.isChecked());
        }
    };

    protected FieldCheckbox mCheckboxField = null;

    public BasicFieldCheckboxView(Context context) {
        super(context);
        initOnCheckedChangeListener();
    }

    public BasicFieldCheckboxView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initOnCheckedChangeListener();
    }

    public BasicFieldCheckboxView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initOnCheckedChangeListener();
    }

    private void initOnCheckedChangeListener() {
        setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mCheckboxField != null) {
                    mCheckboxField.setChecked(isChecked);
                }
            }
        });
    }

    @Override
    public void setField(Field field) {
        FieldCheckbox checkboxField = (FieldCheckbox) field;
        if (mCheckboxField == checkboxField) {
            return;
        }

        if (mCheckboxField != null) {
            mCheckboxField.unregisterObserver(mFieldObserver);
        }
        mCheckboxField = checkboxField;
        if (mCheckboxField != null) {
            setChecked(mCheckboxField.isChecked());
            mCheckboxField.registerObserver(mFieldObserver);
        }
    }

    @Override
    public Field getField() {
        return mCheckboxField;
    }

    @Override
    public void unlinkField() {
        setField(null);
    }
}


text:
Your Profile

  My ID is: {{(auth | async)?.uid}}

  <md-card class="profile-card">

Let's get started setting up your profile. What's your full name?

    <form *ngIf="user" (submit)="next(user)" class="user-form" ngNoForm>

          <md-input-container><input mdInput i18n-placeholder placeholder="Full Name" [(ngModel)]="user.name"></md-input-container>

        <button i18n md-raised-button color="primary" (click)="next(user)">Next</button>

    </form>

We don't yet have any data for your user.

  </md-card>


text:
package org.trustedanalytics.utils.errorhandling;

import org.springframework.context.annotation.Import;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import(RestErrorHandlerConfigFactory.class)
public @interface EnableRestErrorHandling {
}


text:
var path = require('canonical-path');
/**
 * dgProcessor
 * @description
 *
 */
module.exports = function renderAsJadeProcessor() {
  return {
    $runAfter: ['readFilesProcessor'],
    $runBefore: ['writing-files'],
    $process: function(docs) {
      return docs.map(function(doc) {
        var fileInfo = doc.fileInfo;
        doc.renderedContent =  doc.content ;
        var regionSuffix =  (doc.regionName && doc.regionName.length) ? "-" + doc.regionName.trim() : "";
        var origName = fileInfo.baseName + "." + fileInfo.extension;

        var newName = "_." + fileInfo.baseName + regionSuffix +  "." + fileInfo.extension;
        doc.outputPath = fileInfo.filePath.replace(origName, newName);
        return doc;
      })
    }
  };
};


text:
package org.opencb.hpg.bigdata.analysis.variant.statistics;

import java.security.InvalidParameterException;

public class MultipleTestCorrection {
    public static double[] fdrCorrection(double[] pvalues) throws InvalidParameterException {
        return bHCorrection(pvalues);
    }

    public static double[] bonferroniCorrection(double[] pvalues) throws InvalidParameterException {
        double[] res = new double[pvalues.length];
        int size = pvalues.length;
        for (int i = 0; i < size; i++) {
            res[i] = pvalues[i] * size;
        }
        return StatsUtils.pmin(1, res);
    }

    public static double[] bHCorrection(double[] pvalues) throws InvalidParameterException {
        int[] o = StatsUtils.order(pvalues, true);
        int[] ro = StatsUtils.order(o);
        double[] mult = StatsUtils.ordered(pvalues, o);
        for (int i = mult.length, j = 0; i > 0; i--, j++) {
            mult[j] *= ((double) mult.length / (i));
        }
        return StatsUtils.ordered(StatsUtils.pmin(1, StatsUtils.cummin(mult)), ro);
    }

    public static double[] hochbergCorrection(double[] pvalues) throws InvalidParameterException {
        int[] o = StatsUtils.order(pvalues, true);
        int[] ro = StatsUtils.order(o);
        double[] mult = StatsUtils.ordered(pvalues, o);
        for (int i = mult.length, j = 0; i > 0; i--, j++) {
            mult[j] *= (mult.length - i + 1);
        }
        return StatsUtils.ordered(StatsUtils.pmin(1, StatsUtils.cummin(mult)), ro);
    }

    public static double[] bYCorrection(double[] pvalues) throws InvalidParameterException {
        int[] o = StatsUtils.order(pvalues, true);
        int[] ro = StatsUtils.order(o);
        double[] mult = StatsUtils.ordered(pvalues, o);

        double q = 0.0;
        for (int i = 1; i <= mult.length; i++) {
            q += (double) 1 / i;
        }

        for (int i = mult.length, j = 0; i > 0; i--, j++) {
            mult[j] *= (q * (double) mult.length / (i));
        }
        return StatsUtils.ordered(StatsUtils.pmin(1, StatsUtils.cummin(mult)), ro);
    }

    public static double[] holmCorrection(double[] pvalues) throws InvalidParameterException {
        int[] o = StatsUtils.order(pvalues);
        int[] ro = StatsUtils.order(o);
        double[] mult = StatsUtils.ordered(pvalues, o);
        for (int i = 0; i < mult.length; i++) {
            mult[i] *= (mult.length - i);
        }
        return StatsUtils.ordered(StatsUtils.pmin(1, StatsUtils.cummax(mult)), ro);
    }
}


text:
var fs = require('fs');
var util = require('util');
var acr_to_state = require('./states_hash.json');

var racers = JSON.parse(fs.readFileSync(process.argv[2]).toString());

var places = {};

racers.forEach(function (r) {
  if (r.dnf) return;
  var loc;
  var abc = r.origin.split(',').map(function (r) { return r.trim(); });
  if (acr_to_state[abc[1]])
    loc = abc[1];
  else
    loc = abc[2];

  if (!places[loc])
    places[loc] = [];
  places[loc].push(r.overall_place);
});

var averages = {};

Object.keys(places).forEach(function (p) {
  averages[p] = places[p].reduce(function(pv, cv) { return pv + cv; }, 0) / places[p].length;
});

//console.log(averages);

//console.log('Rank Country/State #_of_Skiers Average_Skier_Overall_Ranking');
var table = [];
var i = 0;
Object.keys(places).sort(function (a, b) { return averages[a] - averages[b]; }).forEach(function (p) {
  table.push([++i, p, places[p].length, averages[p]]);
  //console.log(++i + '. ' + p + ' ' + places[p].length + ' '  + averages[p]);
});

console.log(table);


text:
using System;
using System.Collections.Generic;
using OrdersCollector.Core.Suppliers.Events;
using OrdersCollector.Core.Suppliers.Exceptions;
using OrdersCollector.EventSourcing;

namespace OrdersCollector.Core.Suppliers.Models
{
    public class SuppliersCollection : AggregateRoot
    {
        private List<Supplier> suppliers = new List<Supplier>();
        private Dictionary<string, Supplier> suppliersDict = new Dictionary<string, Supplier>();

        public SuppliersCollection(
            Guid suppliersCollectionId,
            Guid groupId
        ) : this()
        {
            RaiseEvent(new SuppliersCollectionCreated(
                suppliersCollectionId,
                groupId
            ));
        }

        private SuppliersCollection()
        {
            RegisterEventHandler<SuppliersCollectionCreated>(When);
            RegisterEventHandler<SupplierAdded>(When);
        }

        public Guid GroupId { get; private set; }

        public IReadOnlyCollection<Supplier> Suppliers => suppliers.AsReadOnly();

        public void AddSupplier(Guid supplierInfoId, string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (suppliersDict.ContainsKey(name))
            {
                throw new SupplierWithSpecifiedNameOrAliasAlreadyExistsException(
                    name
                );
            }

            RaiseEvent(new SupplierAdded(
                supplierInfoId,
                name
            ));
        }

        private void When(SuppliersCollectionCreated @event)
        {
            Id = @event.SuppliersCollectionId;
            GroupId = @event.GroupId;
        }

        private void When(SupplierAdded @event)
        {
            var supplier = new Supplier(
                @event.SupplierInfoId,
                @event.Name
            );

            suppliers.Add(supplier);
            suppliersDict[supplier.Name] = supplier;
        }
    }
}


text:
# Load all *.rb files in lib/trick_bag and below.
start_dir = File.join(File.dirname(__FILE__), 'trick_bag') # the lib directory
file_mask = "#{start_dir}/**/*.rb"
Dir[file_mask].each { |file| require file }


text:
package trees

import (
	"errors"
	"sync"

	"github.com/kennylevinsen/qp"
)

// BUG(kl): ListHandle.ReadAt permits arbitrary seeking in the directory
// listing, which is out of spec.

// ListHandle is a special handle used to list directories that implement the
// Lister interface. It also provides access logging for directories
// implementing AccessLogger.
type ListHandle struct {
	sync.Mutex

	Dir  Lister
	User string

	list []qp.Stat
}

func (h *ListHandle) update() error {
	s, err := h.Dir.List(h.User)
	if err != nil {
		return err
	}

	h.list = s
	return nil
}

// ReadAt reads the directory listing.
func (h *ListHandle) ReadAt(p []byte, offset int64) (int, error) {
	if offset == 0 {
		h.Lock()
		err := h.update()
		h.Unlock()
		if err != nil {
			return 0, err
		}
	}

	if a, ok := h.Dir.(AccessLogger); ok {
		a.Accessed()
	}

	h.Lock()
	defer h.Unlock()
	var copied int
	for {
		if len(h.list) == 0 {
			break
		}

		s := h.list[0]
		l := s.EncodedSize()
		if len(p)-copied < l {
			if copied == 0 {
				return 0, errors.New("read: message size too small: stat does not fit")
			}
			break
		}

		if err := s.Marshal(p[copied:]); err != nil {
			return copied, err
		}

		copied += l
		h.list = h.list[1:]
	}

	return copied, nil
}

// WriteAt returns an error, as writing to a directory is not legal.
func (h *ListHandle) WriteAt(p []byte, offset int64) (int, error) {
	return 0, errors.New("cannot write to directory")
}

// Close closes the handle.
func (h *ListHandle) Close() error {
	if a, ok := h.Dir.(AccessLogger); ok {
		a.Closed()
	}
	return nil
}


text:
package org.apache.sling.ide.eclipse.sightly.internal;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.wst.common.project.facet.core.IDelegate;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;

public class SightlyFacetUninstallDelegate implements IDelegate {

    @Override
    public void execute(IProject project, IProjectFacetVersion version, Object config, IProgressMonitor monitor)
            throws CoreException {

    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation SDLSeatLocationCapability

- (instancetype)initWithSeats:(NSArray<SDLSeatLocation *> *)seats cols:(NSNumber<SDLInt> *)cols rows:(NSNumber<SDLInt> *)rows levels:(NSNumber<SDLInt> *)levels {
    self = [self init];
    if (!self) {
        return self;
    }

    self.seats = seats;
    self.cols = cols;
    self.rows = rows;
    self.levels = levels;

    return self;
}

- (void)setCols:(nullable NSNumber<SDLInt> *)cols {
    [self.store sdl_setObject:cols forName:SDLRPCParameterNameColumns];
}

- (nullable NSNumber<SDLInt> *)cols {
    NSError *error = nil;
    return [self.store sdl_objectForName:SDLRPCParameterNameColumns ofClass:NSNumber.class error:&error];
}

- (void)setRows:(nullable NSNumber<SDLInt> *)rows {
    [self.store sdl_setObject:rows forName:SDLRPCParameterNameRows];
}

- (nullable NSNumber<SDLInt> *)rows {
    NSError *error = nil;
    return [self.store sdl_objectForName:SDLRPCParameterNameRows ofClass:NSNumber.class error:&error];
}

- (void)setLevels:(nullable NSNumber<SDLInt> *)levels {
    [self.store sdl_setObject:levels forName:SDLRPCParameterNameLevels];
}

- (nullable NSNumber<SDLInt> *)levels {
    NSError *error = nil;
    return [self.store sdl_objectForName:SDLRPCParameterNameLevels ofClass:NSNumber.class error:&error];
}

- (void)setSeats:(nullable NSArray<SDLSeatLocation *> *)seats {
    [self.store sdl_setObject:seats forName:SDLRPCParameterNameSeats];
}

- (nullable NSArray<SDLSeatLocation *> *)seats {
    NSError *error = nil;
    return [self.store sdl_objectsForName:SDLRPCParameterNameSeats ofClass:SDLSeatLocation.class error:&error];
}

@end

NS_ASSUME_NONNULL_END


text:
package org.seaborne.delta.server.s3;

import org.seaborne.delta.server.local.PatchStoreMgr;
import org.seaborne.delta.server.local.PatchStoreProvider;

public class InitZkS3 {

    public static void register() {
        PatchStoreProvider psp = new PatchStoreProviderZkS3();
        PatchStoreMgr.register(psp);
    }
}


text:
Fragranz
========

A reference app for TruckJS about perfumes and colognes.

To see this running, you'll need to first run a server instance in this directory. If you've got Python, you can just run this in your terminal/command prompt:

```
python -m SimpleHTTPServer
```

This is just a prototype. It's purpose is to show how to use Truck's models, views, routes, etc. to put an app together. Because this is not a real app, it has no data persistence or actual commercial transaction.


text:
package io.quarkus.elytron.security.deployment;

import java.util.List;

import org.jboss.logging.Logger;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityRealm;

import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.BeanContainerBuildItem;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.elytron.security.runtime.DefaultRoleDecoder;
import io.quarkus.elytron.security.runtime.ElytronPasswordIdentityProvider;
import io.quarkus.elytron.security.runtime.ElytronRecorder;
import io.quarkus.elytron.security.runtime.ElytronSecurityDomainManager;
import io.quarkus.elytron.security.runtime.ElytronTokenIdentityProvider;
import io.quarkus.elytron.security.runtime.ElytronTrustedIdentityProvider;
import io.quarkus.runtime.RuntimeValue;

/**
 * The build time process for the security aspects of the deployment. This creates {@linkplain BuildStep}s for integration
 * with the Elytron security services. This supports the Elytron
 * {@linkplain org.wildfly.security.auth.realm.LegacyPropertiesSecurityRealm}
 * and {@linkplain org.wildfly.security.auth.realm.SimpleMapBackedSecurityRealm} realm implementations. Others could be
 * added by creating an extension that produces a SecurityRealmBuildItem for the realm.
 *
 * Additional authentication mechanisms can be added by producing AuthConfigBuildItems and including the associated
 * {@linkplain io.undertow.servlet.ServletExtension} implementations to register the
 * {@linkplain io.undertow.security.api.AuthenticationMechanismFactory}.
 *
 * TODO: The handling of the configuration to SecurityRealm instance creation/loading is clumsy to not being able to
 * have a config object annotated with @ConfigGroup inherit from another object with MP config annotated properties.
 *
 */
class ElytronDeploymentProcessor {
    private static final Logger log = Logger.getLogger(ElytronDeploymentProcessor.class.getName());

    @BuildStep
    void addBeans(BuildProducer<AdditionalBeanBuildItem> beans, List<ElytronPasswordMarkerBuildItem> pw,
            List<ElytronTokenMarkerBuildItem> token) {
        beans.produce(AdditionalBeanBuildItem.unremovableOf(ElytronSecurityDomainManager.class));
        beans.produce(AdditionalBeanBuildItem.unremovableOf(DefaultRoleDecoder.class));
        if (!token.isEmpty()) {
            beans.produce(AdditionalBeanBuildItem.unremovableOf(ElytronTokenIdentityProvider.class));
        }
        if (!pw.isEmpty()) {
            beans.produce(AdditionalBeanBuildItem.unremovableOf(ElytronPasswordIdentityProvider.class));
            beans.produce(AdditionalBeanBuildItem.unremovableOf(ElytronTrustedIdentityProvider.class));
        }
    }

    /**
     * Create the deployment SecurityDomain using the SecurityRealm build items that have been created.
     *
     * @param recorder - the runtime recorder class used to access runtime behaviors
     * @param realms - the previously created SecurityRealm runtime values
     * @return the SecurityDomain runtime value build item
     * @throws Exception
     */
    @BuildStep
    @Record(ExecutionTime.RUNTIME_INIT)
    SecurityDomainBuildItem build(ElytronRecorder recorder, List<SecurityRealmBuildItem> realms)
            throws Exception {
        if (realms.size() > 0) {
            // Configure the SecurityDomain.Builder from the main realm
            SecurityRealmBuildItem realmBuildItem = realms.get(0);
            RuntimeValue<SecurityDomain.Builder> securityDomainBuilder = recorder
                    .configureDomainBuilder(realmBuildItem.getName(), realmBuildItem.getRealm());
            // Add any additional SecurityRealms
            for (int n = 1; n < realms.size(); n++) {
                realmBuildItem = realms.get(n);
                RuntimeValue<SecurityRealm> realm = realmBuildItem.getRealm();
                recorder.addRealm(securityDomainBuilder, realmBuildItem.getName(), realm);
            }
            // Actually build the runtime value for the SecurityDomain
            RuntimeValue<SecurityDomain> securityDomain = recorder.buildDomain(securityDomainBuilder);

            // Return the build item for the SecurityDomain runtime value
            return new SecurityDomainBuildItem(securityDomain);
        }
        return null;
    }

    @BuildStep
    @Record(ExecutionTime.RUNTIME_INIT)
    void identityManager(ElytronRecorder recorder, SecurityDomainBuildItem securityDomain, BeanContainerBuildItem bc) {
        if (securityDomain != null) {
            recorder.setDomainForIdentityProvider(bc.getValue(), securityDomain.getSecurityDomain());
        }
    }

    /**
     * For each SecurityRealm, load it's runtime state. This is currently a little strange due to how the AuthConfig is
     * downcast to the type of SecurityRealm configuration instance.
     *
     * @param recorder - the runtime recorder class used to access runtime behaviors
     * @param realms - the previously created SecurityRealm runtime values
     * @throws Exception
     */
    @BuildStep
    @Record(ExecutionTime.RUNTIME_INIT)
    void loadRealm(ElytronRecorder recorder, List<SecurityRealmBuildItem> realms) throws Exception {
        for (SecurityRealmBuildItem realm : realms) {
            if (realm.getRuntimeLoadTask() != null) {
                recorder.runLoadTask(realm.getRuntimeLoadTask());
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System.Net.Http;
using System.Configuration;

using System.Diagnostics;
using System.Net;

namespace PoetryHub.Controllers
{
    /// <summary>
    /// Single Page App Routes. All valid routes get routed to / for the client to handle.
    /// </summary>
    public class AppController : Controller
    {
        public AppController()
        {
        }

        // see http://attributerouting.net/ for help on routes
        [Route(Name = "Home")] // default route at /
        // Other valid routes to go home for AngularJS routing engine to handle
        [Route("createDraft")]
        [Route("poems")]
        [Route("draft/{id}/{title?}")]
        [Route("poem/{id}/{title?}")]
        public ActionResult Index()
        {
            ViewBag.ShowSplash = true; // _Home adjusts accordingly
            return View();
        }

        // you can serve .cshtml in an AngularJS app instead of .html with a route such as this.
        // Your view files will not be inside the App directory
        // since MVC by convention is setup for view files in the View directory
        [Route("template/{id}")]
        public ViewResult Template(string id)
        {
            ViewBag.ShowSplash = false; // _Home adjusts accordingly
            return View(id, null, null);
        }
    }
}


text:
A port of [packr](https://github.com/libgdx/packr) written in rust-lang. Uses [jni-rs](https://github.com/code-disaster/jni-rs) to access the Java Invocation API.

This code was written as an experiment to get familiar with the Rust language and with Cargo, how to interface with C/C++, and how to integrate native code.

> This port is not complete. It only runs on Mac OS X so far. It doesn't implement all features available in the original.

> Disclaimer: This is one part of the very first code I've ever written in Rust. It's probably very ugly. No kittens were harmed while writing this code.


text:
#include "os_functions.h"
#include "vpad_functions.h"

EXPORT_DECL(void, VPADInit, void);
EXPORT_DECL(void, VPADRead, int chan, VPADData *buffer, u32 buffer_size, s32 *error);

void InitVPadFunctionPointers(void)
{
    unsigned int *funcPointer = 0;
    unsigned int vpad_handle;
    OSDynLoad_Acquire("vpad.rpl", &vpad_handle);

    OS_FIND_EXPORT(vpad_handle, VPADInit);
    OS_FIND_EXPORT(vpad_handle, VPADRead);
}


text:
using System;
using System.Security.Cryptography;

namespace Kerberos.NET.Crypto
{
    public interface IKeyDerivationAlgorithm
    {
        ReadOnlyMemory<byte> Derive(
            HashAlgorithmName algName,
            ReadOnlyMemory<byte> passwordBytes,
            ReadOnlyMemory<byte> salt,
            int k,
            int keySize
        );
    }
}


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib.impl;
import com.wilutions.com.*;

@SuppressWarnings("all")
@CoClass(guid="{1A23B778-F469-9BDB-319A-A858E2EE12D4}")
public class _IFavoriteContactsEventsImpl extends Dispatch implements com.wilutions.mslib.uccollaborationlib._IFavoriteContactsEvents {
  @DeclDISPID(500)  public void onOnNameChanged(final com.wilutions.mslib.uccollaborationlib.IGroup _eventSource, final com.wilutions.mslib.uccollaborationlib.IGroupNameChangedEventData _eventData) throws ComException {
    this._dispatchCall(500,"OnNameChanged", DISPATCH_METHOD,null,(_eventSource!=null?_eventSource:Dispatch.NULL),(_eventData!=null?_eventData:Dispatch.NULL));
  }
  @DeclDISPID(501)  public void onOnContactAdded(final com.wilutions.mslib.uccollaborationlib.IGroup _eventSource, final com.wilutions.mslib.uccollaborationlib.IGroupMemberChangedEventData _eventData) throws ComException {
    this._dispatchCall(501,"OnContactAdded", DISPATCH_METHOD,null,(_eventSource!=null?_eventSource:Dispatch.NULL),(_eventData!=null?_eventData:Dispatch.NULL));
  }
  @DeclDISPID(502)  public void onOnContactRemoved(final com.wilutions.mslib.uccollaborationlib.IGroup _eventSource, final com.wilutions.mslib.uccollaborationlib.IGroupMemberChangedEventData _eventData) throws ComException {
    this._dispatchCall(502,"OnContactRemoved", DISPATCH_METHOD,null,(_eventSource!=null?_eventSource:Dispatch.NULL),(_eventData!=null?_eventData:Dispatch.NULL));
  }
  public _IFavoriteContactsEventsImpl(String progId) throws ComException {
    super(progId, "{DAB42E13-500A-409A-AC34-C1BF4719EE2E}");
  }
  protected _IFavoriteContactsEventsImpl(long ndisp) {
    super(ndisp);
  }
  public String toString() {
    return "[_IFavoriteContactsEventsImpl" + super.toString() + "]";
  }
}


text:
This implementation presupposes e.g.

1. that a request consists of a header and a body
1. that the header has a specific length
1. that the length of the body is specified at a specific position in the header

To use this module, fork and adapt it to your needs :).


text:
using System;
using System.Text;
using System.Security.Cryptography;

namespace ML.Security
{
    public class TripleDESCryption
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        public TripleDESCryption()
        {
            //
        }

        /// <summary>
        /// 使用给定密钥字符串加密string
        /// </summary>
        /// <param name="original">原始文字</param>
        /// <param name="key">密钥</param>
        /// <param name="encoding">字符编码方案</param>
        /// <returns>密文</returns>
        public static string TripleDESEncryptBase64(string original, string key)
        {
            byte[] buff = System.Text.Encoding.UTF8.GetBytes(original);
            byte[] kb = System.Text.Encoding.UTF8.GetBytes(key);
            return Convert.ToBase64String(TripleDESEncrypt(buff, kb));
        }
        /// <summary>
        /// 使用给定密钥字符串解密string
        /// </summary>
        /// <param name="original">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string TripleDESDecryptBase64(string original, string key)
        {
            return TripleDESDecryptBase64(original, key, System.Text.Encoding.UTF8);
        }

        /// <summary>
        /// 使用给定密钥字符串解密string,返回指定编码方式明文
        /// </summary>
        /// <param name="encrypted">密文</param>
        /// <param name="key">密钥</param>
        /// <param name="encoding">字符编码方案</param>
        /// <returns>明文</returns>
        public static string TripleDESDecryptBase64(string encrypted, string key, Encoding encoding)
        {
            byte[] buff = Convert.FromBase64String(encrypted);
            byte[] kb = System.Text.Encoding.UTF8.GetBytes(key);
            return encoding.GetString(TripleDESDecrypt(buff, kb));
        }

        /// <summary>
        /// 使用给定密钥加密
        /// </summary>
        /// <param name="original">明文</param>
        /// <param name="key">密钥</param>
        /// <returns>密文</returns>
        public static byte[] TripleDESEncrypt(byte[] original, byte[] key)
        {
            TripleDESCryptoServiceProvider tripleDesProvider = new TripleDESCryptoServiceProvider();
            tripleDesProvider.Key = MD5Cryption.ComputeHash(key);
            tripleDesProvider.Mode = CipherMode.ECB;
            return tripleDesProvider.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
        }

        /// <summary>
        /// 使用给定密钥解密数据
        /// </summary>
        /// <param name="encrypted">密文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static byte[] TripleDESDecrypt(byte[] encrypted, byte[] key)
        {
            TripleDESCryptoServiceProvider tripleDesProvider = new TripleDESCryptoServiceProvider();
            tripleDesProvider.Key = MD5Cryption.ComputeHash(key);
            tripleDesProvider.Mode = CipherMode.ECB;
            return tripleDesProvider.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
        }

    }
}


text: export declare function convertToBoolProperty(val: any): boolean;


text:
package peer

type CoreRedisParameter struct {
	Password      string
	DBIndex       int
	PoolConnCount int
}

func (self *CoreRedisParameter) Init() {
	self.PoolConnCount = 1
}

func (self *CoreRedisParameter) SetPassword(v string) {
	self.Password = v
}

func (self *CoreRedisParameter) SetDBIndex(v int) {
	self.DBIndex = v
}

func (self *CoreRedisParameter) SetConnectionCount(v int) {
	self.PoolConnCount = v
}


text:
<?php

/**
 * $model.description$
 *
 * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
 *
 */
class GetStopTimetablesResult
{

    static $swaggerTypes = array(
        'StopTimetables' => 'array[StopTimetable]'

    );

    /**
     * The stop timetables found, if any
     */
    public $StopTimetables; // array[StopTimetable]
}


text:
package org.hibernate.ejb.test.ejb3configuration;

import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;

import org.hibernate.ejb.HibernatePersistence;

/**
 * TODO : javadoc
 *
 * @author Steve Ebersole
 */
public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
	private Properties properties;

	public String getPersistenceUnitName() {
		return "persistenceUnitAdapter";
	}

	public String getPersistenceProviderClassName() {
		return HibernatePersistence.class.getName();
	}

	public PersistenceUnitTransactionType getTransactionType() {
		return null;
	}

	public DataSource getJtaDataSource() {
		return null;
	}

	public DataSource getNonJtaDataSource() {
		return null;
	}

	public List<String> getMappingFileNames() {
		return Collections.emptyList();
	}

	public List<URL> getJarFileUrls() {
		return Collections.emptyList();
	}

	public URL getPersistenceUnitRootUrl() {
		return null;
	}

	public List<String> getManagedClassNames() {
		return Collections.emptyList();
	}

	public boolean excludeUnlistedClasses() {
		return false;
	}

	public SharedCacheMode getSharedCacheMode() {
		return null;
	}

	public ValidationMode getValidationMode() {
		return null;
	}

	public Properties getProperties() {
		if ( properties == null ) {
			properties = new Properties();
		}
		return properties;
	}

	public String getPersistenceXMLSchemaVersion() {
		return null;
	}

	public ClassLoader getClassLoader() {
		return Thread.currentThread().getContextClassLoader();
	}

	public void addTransformer(ClassTransformer transformer) {
	}

	public ClassLoader getNewTempClassLoader() {
		return Thread.currentThread().getContextClassLoader();
	}
}


text:
#include <XENetwork/NetworkManager.hpp>
#include <XENetwork/NetObserver.hpp>
#include <XEngine/Components/NetId.hpp>
#include <XEScripts/LUAEngine.h>
#include <plog/Log.h>

namespace XE
{
	NetworkManager::NetworkManager()
		: mReadLoopThread()// Exlicitly using the default constructor to underline the fact that it does get called
		, m_Running(false)
		, m_isClient(true)
		, peer(nullptr)
		, host(nullptr)
		, _increment(0)
	{
	}

	NetworkManager::~NetworkManager()
	{
		m_Running = false;
		if (mReadLoopThread.joinable()) mReadLoopThread.join();
	}

	void NetworkManager::registerObject(sol::state& lua)
	{
		lua.new_usertype<NetworkManager>("NetworkManager",

			//properties
			//"graphicsMgr", sol::property(&XEngine::getGraphicsManager),

			//functions
			"startLoop", &NetworkManager::startLoop
			);

		auto stateView = lua.set("NetworkManager", this); //set object instance
	}

	void NetworkManager::startLoop(bool isClient)
	{
		m_isClient = isClient;

		if (enet_initialize() != 0)
		{
			fprintf(stderr, "An error occurred while initializing ENet.\n");
		}
		atexit(enet_deinitialize);

		printf("Initialized.\n");

		/* Bind the server to the default localhost.     */
		/* A specific host address can be specified by   */
		/* enet_address_set_host (& address, "x.x.x.x"); */

		address.port = 1234;

		if (!m_isClient)
		{
			//----------------------- Server -----------------------
			printf("I am server...\n");
			fflush(stdout);

			/* Bind the server to the default localhost.     */
			/* A specific host address can be specified by   */
			/* enet_address_set_host (& address, "x.x.x.x"); */

			address.host = ENET_HOST_ANY;
			//enet_address_set_host(&address, "127.0.0.1");

			host = enet_host_create(&address, // the address to bind the server host to
				50,   // allow only 1 client and/or outgoing connections
				2,      /* allow up to 2 channels to be used, 0 and 1 */
				0,   // assume any amount of incoming bandwidth
				0);  // assume any amount of outgoing bandwidth

			if (!host) {
				fprintf(stderr, "An error occurred while trying to create an ENet server host.\n");
				exit(EXIT_FAILURE);
			}
			printf("Host Created at %s.\n", address.host);
			//----------------------- Server end -----------------------
		}
		else
		{
			//----------------------- Client -------------------------------
			printf("I am client...\n");
			fflush(stdout);

			host = enet_host_create(0, // create a client host
				1, // allow only 1 outgoing connection
				2, /* allow up 2 channels to be used, 0 and 1 */
				0, // use 57600 / 8 for 56K modem with 56 Kbps downstream bandwidth
				0);// use 14400 / 8 for 56K modem with 14 Kbps upstream bandwidth

			if (!host) {
				fprintf(stderr, "An error occurred while trying to create an ENet client host.\n");
				exit(EXIT_FAILURE);
			}

			// Connect to some.server.net:1234.
			enet_address_set_host(&address, ENET_HOST_ANY);// "localhost");
			peer = enet_host_connect(host, &address, 2, 0);
			peer->data = 0; // use this as mark that connection is not yet acknowledged
			if (!peer) {
				fprintf(stderr, "No available peers for initiating an ENet connection.\n");
				exit(EXIT_FAILURE);
			}

			/* Wait up to 5 seconds for the connection attempt to succeed. */
			if (enet_host_service(host, &event, 100) > 0 &&
				event.type == ENET_EVENT_TYPE_CONNECT)
			{
				//puts("Connection to some.server.net:1234 succeeded.");
				fprintf(stderr, "Connection to some.server.net:1234 succeeded.");
			/*...
					...
					...*/
			}
			else
			{
				/* Either the 5 seconds are up or a disconnect event was */
				/* received. Reset the peer in the event the 5 seconds   */
				/* had run out without any significant event.            */
				enet_peer_reset(peer);
				//puts("Connection to some.server.net:1234 failed.");
				fprintf(stderr, "Connection to some.server.net:1234 failed.");
			}
			//----------------------- Client end -------------------------------
		}

		if (!m_Running)
		{
			m_Running = true;
			mReadLoopThread = std::thread(&NetworkManager::ReadLoopThread, this); // This will start the thread. Notice move semantics! https://rafalcieslak.wordpress.com/2014/05/16/c11-stdthreads-managed-by-a-designated-class/
		}
	}

	void NetworkManager::stopLoop()
	{
		m_Running = false; //leak? test if calling start again
	}

	void NetworkManager::SendPacketToPeer(int Channel, const void * data, size_t dataLength)//, char pack[11])
	{
		/* Create a reliable packet of size 7 containing "packet\0" */
		ENetPacket * packet = enet_packet_create(data,	dataLength , ENET_PACKET_FLAG_RELIABLE);

		if (!packet)
		{
			LOG(plog::error) << "SendPacketToPeer. Failed to create ENet packet";
			return;
		}

		/* Send the packet to the peer over channel id 0. */
		/* One could also broadcast the packet by         */
		/* enet_host_broadcast (host, 0, packet);         */
		enet_peer_send(peer, Channel, packet);
		/* One could just use enet_host_service() instead. */
	//	enet_host_flush(host);

	}

	void NetworkManager::ReadLoopThread()
	{
		while (isRunning())
		{
			// processing incoming events:
			while (enet_host_service(host, &event, 10) > 0) {

				bool autodeleteBuffer = true;

				printf("Checking Incoming");
				switch (event.type) {
				case ENET_EVENT_TYPE_CONNECT: {

					printf("A new client connected from %x:%u. peerid: %u\n",
						event.peer->address.host,
						event.peer->address.port,
						event.peer->incomingPeerID);
					fflush(stdout);

				//	m_peers[event.peer->incomingPeerID] = event.peer;

					char buf[64];
					sprintf(buf, "%u:%u", event.peer->address.host, event.peer->address.port);
					int buflen = strlen(buf);
					event.peer->data = malloc(buflen + 1);
					strncpy((char*)event.peer->data, buf, buflen);
					peer = event.peer;

					break;
				}
				case ENET_EVENT_TYPE_RECEIVE:

					printf("A packet of length %u containing %s was received from %s on channel %u. peerid: %u\n",
						event.packet->dataLength,
						event.packet->data,
						event.peer->data,
						event.channelID,
						event.peer->incomingPeerID);

					fflush(stdout);

					NWMessage msg;
					msg.data = event.packet->data; //evtl. flatbuffer data
					msg.len = event.packet->dataLength;
					msg.peer = event.peer;// ->incomingPeerID;

					autodeleteBuffer = receivedMessage(msg);

					//enet_packet_destroy(event.packet); // clean up the packet now that we're done using it
					if (event.packet != NULL)
					{
						if (event.packet->freeCallback != NULL)
							(*event.packet->freeCallback) (event.packet);

						if (autodeleteBuffer)
						{
							if (!(event.packet->flags & ENET_PACKET_FLAG_NO_ALLOCATE) &&
								event.packet->data != NULL)
								enet_free(event.packet->data);
						}

						enet_free(event.packet);
					}

					//SendPacket(0, "Data Received");
					break;

				case ENET_EVENT_TYPE_DISCONNECT:
					printf("  host disconnected.\n");
					fflush(stdout);
					free(event.peer->data);

					// 5. Publisher broadcasts
					for (int i = 0; i < views.size(); i++)
						views[i]->disconnected(event.peer);

				//	m_peers.erase(event.peer->incomingPeerID);

					event.peer->data = 0; // reset the peer's client information.
					peer = 0;

				default:
					break;
				}
			}

		}

	}

	bool NetworkManager::receivedMessage(NWMessage& msg) {

		//todo convert enet to message

		//flatbuffer pointer
	//	char* tmp; // received data
		bool autoDeleteBuffer = true;

		// 5. Publisher broadcasts
		for (int i = 0; i < views.size(); i++)
		{
			bool tmp = views[i]->receivedMessage(msg);
			autoDeleteBuffer = autoDeleteBuffer ? tmp : true;
		}

		//delete msg.data; //done with enet_packet_destroy(event.packet); !!!
//		delete tmp; // delete pointer after all observers handled that message!
		return autoDeleteBuffer;
	}

	sf::Uint32 NetworkManager::newNetID()
	{
		return _increment++;
	}

	//entityx::Entity NetworkManager::getEntity(sf::Uint16 netId)
	//{
	//	return m_entities[netId];
	//}

	//uint16_t NetworkManager::addEntity(entityx::Entity entity)
	//{
	//	_increment++;
	//	entityx::ComponentHandle<NetIdComponent> netId = entity.assign<NetIdComponent>(_increment);
	//	netId->Id = _increment;
	//	m_entities[_increment] = entity;
	//
	//	return _increment;
	//}

	//void NetworkManager::removeEntity(entityx::Entity entity)
	//{
	//	auto netId = entity.component<NetIdComponent>();
	//	m_peers.erase(netId->Id());
	//	entity.remove<NetIdComponent>();
	//}

	void NetworkManager::attach(NetObserver *obs) {
		views.push_back(obs);
	}

	void NetworkManager::sendMessage(ENetPeer* peer, const void * data, size_t dataLength, _ENetPacketFlag flag){

	//	if (m_peers.size() <= 0)// || netComponent.peerID == 0)
	//		return;
		if (!peer)
			return;
		//const char* pack = "nodes mit size und orientation";

		/* Create a reliable packet of size 7 containing "packet\0" */
		//ENetPacket * packet = enet_packet_create(pack,
		//	strlen(pack) + 1,
		//	ENET_PACKET_FLAG_RELIABLE);
		ENetPacket * packet = enet_packet_create(data, dataLength, flag); //ENET_PACKET_FLAG_RELIABLE);

		if (!packet)
		{
			LOG(plog::error) << "sendMessage. Failed to create ENet packet";
			return;
		}

		/* Send the packet to the peer over channel id 0. */
		/* One could also broadcast the packet by         */
		/* enet_host_broadcast (host, 0, packet);         */
	//##	enet_peer_send(m_peers[0], 0, packet);

	// Pick channel for sending and broadcast to all peers
	//--->>todo 	enet_host_broadcast(host, 0, packet);

		if (enet_peer_send(peer, 0, packet) < 0)
		{
			LOG(plog::error) << "sendMessage. Failed to send ENet packet to peer";
			return;
		}

		/* One could just use enet_host_service() instead. */
	//	enet_host_flush(host);
	}
}


text:
public class Test {
	public static void main(String[] args) {
		Template t = new TemplateImpl();
		t.action();
	}
}


text: assert.equal(typeof customContextVariable, 'object');


text:
name: user-profile.tsx
language: javascript
---

```javascript
import { useAuth0 } from '@auth0/auth0-react';

const Profile: React.FC = () => {
  const { user, isLoading } = useAuth0();

  // If the SDK is not ready, or a user is not authenticated, exit.
  if (isLoading || !user) return null;

  return (
    <div>
      <img src={user.picture} alt={user.name} />
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
};

export default Profile;
```


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
       Copyright (C) 2015 Haruki Hasegawa

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
-->
<merge xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:background="@null"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_expand_more"/>

</merge>


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Presence',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('channel_name', models.CharField(help_text='Reply channel for connection that is present', max_length=255)),
                ('last_seen', models.DateTimeField(default=django.utils.timezone.now)),
            ],
        ),
        migrations.CreateModel(
            name='Room',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('channel_name', models.CharField(help_text='Group channel name for this room', max_length=255, unique=True)),
            ],
        ),
        migrations.AddField(
            model_name='presence',
            name='room',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='channels_presence.Room'),
        ),
        migrations.AddField(
            model_name='presence',
            name='user',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
        migrations.AlterUniqueTogether(
            name='presence',
            unique_together=set([('room', 'channel_name')]),
        ),
    ]


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'central_dogma'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install central_dogma

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it ( https://github.com/[my-github-username]/central_dogma/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package iphan.pibex.igarassu.ifpe.edu.br;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see Testing documentation
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}


text:
<?php
/**
 * The template for displaying Archive pages.
 *
 * Used to display archive-type pages if nothing more specific matches a query.
 * For example, puts together date-based pages if no date.php file exists.
 *
 * If you'd like to further customize these archive views, you may create a
 * new template file for each specific one. For example, BuddyBoss already
 * has tag.php for Tag archives, category.php for Category archives, and
 * author.php for Author archives.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage BuddyBoss
 * @since BuddyBoss 3.0
 */

get_header(); ?>

		<?php if ( have_posts() ) : ?>

<?php
					if ( is_day() ) :
						printf( __( 'Daily Archives: %s', 'buddyboss' ), '' . get_the_date() . '' );
					elseif ( is_month() ) :
						printf( __( 'Monthly Archives: %s', 'buddyboss' ), '' . get_the_date( _x( 'F Y', 'monthly archives date format', 'buddyboss' ) ) . '' );
					elseif ( is_year() ) :
						printf( __( 'Yearly Archives: %s', 'buddyboss' ), '' . get_the_date( _x( 'Y', 'yearly archives date format', 'buddyboss' ) ) . '' );
					else :
						_e( 'Archives', 'buddyboss' );
					endif;
				?>

			<?php
			/* Start the Loop */
			while ( have_posts() ) : the_post();

				/* Include the post format-specific template for the content. If you want to
				 * this in a child theme then include a file called called content-___.php
				 * (where ___ is the post format) and that will be used instead.
				 */
				get_template_part( 'content', get_post_format() );

			endwhile;

			buddyboss_pagination();
			?>

		<?php else : ?>
			<?php get_template_part( 'content', 'none' ); ?>
		<?php endif; ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
var child = require('child_process')
var byline = require('./byline')

/**
 * Context for the request.
 */

var ctx

/**
 * Child process for binary I/O.
 */

var proc = child.spawn('./main', { stdio: ['pipe', 'pipe', process.stderr] })

proc.on('error', function(err){
  console.error('error: %s', err)
  process.exit(1)
})

proc.on('exit', function(code){
  console.error('exit: %s', code)
  process.exit(1)
})

/**
 * Newline-delimited JSON stdout.
 */

var out = byline(proc.stdout)

out.on('data', function(line){
  if (process.env.DEBUG_SHIM) console.log('[shim] parsing: %j', line)
  var msg = JSON.parse(line)
  ctx.done(msg.error, msg.value)
})

/**
 * Handle events.
 */

exports.handle = function(event, context) {
  ctx = context
  ctx.callbackWaitsForEmptyEventLoop = false

  proc.stdin.write(JSON.stringify({
    "event": event,
    "context": context
  })+'\n');
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Hosting;
using System.Web.Http.Routing;

namespace UnitTestingWebAPI.Tests.Helpers
{
    public class ControllerActionSelector
    {
        #region Variables
        HttpConfiguration config;
        HttpRequestMessage request;
        IHttpRouteData routeData;
        IHttpControllerSelector controllerSelector;
        HttpControllerContext controllerContext;
        #endregion

        #region Constructor
        public ControllerActionSelector(HttpConfiguration conf, HttpRequestMessage req)
        {
            config = conf;
            request = req;
            routeData = config.Routes.GetRouteData(request);
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
            controllerSelector = new DefaultHttpControllerSelector(config);
            controllerContext = new HttpControllerContext(config, routeData, request);
        }
        #endregion

        #region Methods
        public string GetActionName()
        {
            if (controllerContext.ControllerDescriptor == null)
                GetControllerType();

            var actionSelector = new ApiControllerActionSelector();
            var descriptor = actionSelector.SelectAction(controllerContext);

            return descriptor.ActionName;
        }

        public Type GetControllerType()
        {
            var descriptor = controllerSelector.SelectController(request);
            controllerContext.ControllerDescriptor = descriptor;
            return descriptor.ControllerType;
        }
        #endregion
    }
}


text:
import { types as t } from "@marko/compiler";
import { isNativeTag, importDefault } from "@marko/babel-utils";
import classToString from "marko/src/runtime/helpers/class-value";
import withPreviousLocation from "../../../util/with-previous-location";

export default {
  exit(tag, _, value) {
    const {
      hub: { file }
    } = tag;
    if (!isNativeTag(tag)) return;
    if (value.isStringLiteral()) return;

    const { confident, value: computed } = value.evaluate();

    const s = classToString(computed);
    value.replaceWith(
      confident
        ? s
          ? t.stringLiteral(s)
          : t.nullLiteral()
        : withPreviousLocation(
            t.callExpression(
              importDefault(
                file,
                "marko/src/runtime/helpers/class-value.js",
                "marko_class_merge"
              ),
              [value.node]
            ),
            value.node
          )
    );
  }
};


text:
#! /usr/bin/env node

// require other modules
var utilities = require('./utilities'),
	 	xslt = require('node_xslt'),
		fileSystem = require('fs');
		pathUtil = require('path');

// extract the command line parameters from the process args
var userArgs = process.argv.slice(2);

// exit and print command line usage if number of params isnt correct
if(userArgs.length != 3) {
	utilities.printUsageInformation();
	process.exit();
}

// first param is the path to the xsl stylesheet document
var xslPath = pathUtil.normalize(userArgs[0]);

// second argument is the input folder/file
var inputPath = userArgs[1];

// third argument is the output folder
var outputPath = userArgs[2];

// fourth argument is the file extensions of the transformed documents (defaults to .html)
var outputExtension = userArgs[3];

if(!outputExtension) {
	outputExtension = '.html';
}

// ensure that output path is not a file and create the directory if necessary
utilities.ensureDirectoryExistence(outputPath);

// load the xsl file log any errors to the console
var xsl = utilities.loadXslFile(xslPath);

// gets an array of xml files from the input path
var xmlFilePaths = utilities.getXmlFilePaths(inputPath);

// log a warning if no input files are found
if(xmlFilePaths.length === 0) {
	utilities.throwError('No xml files found at "' + inputPath + '"');
}

// loop over all xml files and transform them to the output format
for(var i=0; i < xmlFilePaths.length; i++) {

	var currentXmlFilePath = xmlFilePaths[i],
			xmlFileBasename = pathUtil.basename(currentXmlFilePath, '.xml'),
			currentOutputPath = outputPath + "/" + xmlFileBasename + outputExtension;

	// force UTF-8 encoding on xml files!
	var xmlFileBuffer = fileSystem.readFileSync(currentXmlFilePath, { encoding: 'utf8' });
	var xmlDocument = xslt.readXmlString(xmlFileBuffer);
	var outputString = xslt.transform(xsl, xmlDocument, []);

	fileSystem.writeFile(currentOutputPath, outputString, function(err) {

    if(err) {
        console.log(err);
    } else {
        console.log("Successfully transformed " + currentXmlFilePath + " into " + currentOutputPath);
    }

	});

}


text:
var mAccessToken = null;
var mClientId = null;
var mServiceId = null;

function init() {

  if (DEVICE_CONNECT_HOST) {
    dConnect.setHost(DEVICE_CONNECT_HOST);
  }

  if (TEST_TIMEOUT == undefined) {
    TEST_TIMEOUT = 10000;
  }

  if (DEVICE_NAME == undefined) {
    DEVICE_NAME = 'Test Success Device';
  }

  QUnit.config.autostart = false;
  QUnit.config.testTimeout = TEST_TIMEOUT;
}

function checkErrorCode(errorCode) {
  return errorCode == dConnect.constants.ErrorCode.NOT_SUPPORT_ATTRIBUTE
      || errorCode == dConnect.constants.ErrorCode.NOT_SUPPORT_ACTION
      || errorCode == dConnect.constants.ErrorCode.NOT_SUPPORT_PROFILE;
}

function searchTestDevice(services) {
  var re = new RegExp(DEVICE_NAME, 'i');

  for (var i = 0; i < services.length; i++) {
    var service = services[i];
    console.log('services: ' + services + ', name: ' + service.name);
    if (service.name.match(re)) {
      return service.id;
    }
  }
  return null;
}

function getAccessToken(func) {
  var scopes = Array(
      // core profile
      'authorization',
      'battery',
      'canvas',
      'connect',
      'deviceorientation',
      'file_descriptor',
      'file',
      'keyevent',
      'media_player',
      'mediastream_recording',
      'serviceinformation',
      'servicediscovery',
      'notification',
      'phone',
      'proximity',
      'settings',
      'system',
      'touch',
      'vibration',

      // extra profile
      'camera',
      'dice',
      'drive_controller',
      'light',
      'remote_controller',
      'sphero',
      'temperature',
      'health',
      'humandetect'
  );

  dConnect.authorization(scopes,
      'Device Connect Javascript Test',
      function(clientId, accessToken) {
        mAccessToken = accessToken;
        mClientId = clientId;
        getTestServiceId(func);
      },
      function(errorCode, errorMessage) {
        func(null, null);
      }
  );
}

function getTestServiceId(func) {
  if (mAccessToken == null) {
    getAccessToken(func);
  } else if (mServiceId == null) {
    dConnect.discoverDevices(mAccessToken, function(json) {
        mServiceId = searchTestDevice(json.services);
        func(mAccessToken, mServiceId);
      },
      function(errorCode, errorMessage) {
        func(errorCode, 'Error: ' + errorMessage);
      }
    );
  } else {
    func(mAccessToken, mServiceId);
  }
}

function searchTestService(successCallback, errorCallback) {
  getTestServiceId(function(accessToken, serviceId) {
    if (accessToken == null || serviceId == null) {
      errorCallback(-2, 'Device not found.');
    } else {
      successCallback(accessToken, serviceId);
    }
  });
}

function openWebsocketInternal(func) {
  getTestServiceId(function(accessToken, serviceId) {
    if (accessToken == null || serviceId == null) {
      func(null, null, null);
    } else {
      if (dConnect.isConnectedWebSocket()) {
        func(accessToken, serviceId, mClientId);
      } else {
        dConnect.connectWebSocket(mClientId,
          function(errorCode, errorMessage) {
            if (errorCode === 0) {
              func(accessToken, serviceId, mClientId);
            }
          });
      }
    }
  });
}

function openWebsocket(builder, assert, timeout, eventCallback) {
  var eventCount = 0;
  openWebsocketInternal(function(accessToken, serviceId, sessionKey) {
    builder.setServiceId(serviceId);
    builder.setAccessToken(accessToken);
    builder.setSessionKey(sessionKey);
    var uri = builder.build();
    dConnect.addEventListener(uri, function(message) {
      var ret = eventCallback(message);
      if (ret) {
        eventCount++;
      }
    }, function() {
      assert.ok(true, 'Succeeded to add the event listener.');
      dConnect.removeEventListener(uri, function() {
        assert.ok(true, 'Succeeded to remove the event listener.');
        QUnit.start();
      }, function(errorCode, errorMessage) {
        assert.ok(false, 'Failed to remove the event listener.');
        QUnit.start();
      });
    }, function(errorCode, errorMessage) {
      if (errorCode == 2) {
        assert.ok(true, 'Profile not support');
      } else if (errorCode == 4) {
        assert.ok(true, 'Attribute not support');
      } else {
        assert.ok(false,
            'Failed to add the event listener. errorCode=' + errorCode +
            ' errorMessage: ' + errorMessage);
      }
      QUnit.start();
    });
  });
}


text:
pynrc.simul.apt.update\_eng\_detectors
======================================

.. currentmodule:: pynrc.simul.apt

.. autofunction:: update_eng_detectors


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.alibaba.otter</groupId>
		<artifactId>canal</artifactId>
		<version>1.0.24</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>canal.parse</artifactId>
	<packaging>jar</packaging>
	<name>canal parse module for otter ${project.version}</name>
	<dependencies>
		<dependency>
			<groupId>com.alibaba.otter</groupId>
			<artifactId>canal.common</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba.otter</groupId>
			<artifactId>canal.protocol</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba.otter</groupId>
			<artifactId>canal.meta</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba.otter</groupId>
			<artifactId>canal.sink</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba.otter</groupId>
			<artifactId>canal.parse.dbsync</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba.otter</groupId>
			<artifactId>canal.filter</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba.otter</groupId>
			<artifactId>canal.parse.driver</artifactId>
			<version>${project.version}</version>
		</dependency>
		<!-- test dependency -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
package leeon.mobile.BBSBrowser.yanxi;

public class YanxiHttpConfig {

	public static final String BBS_HOST = "61.147.124.205";

	public static final String BBS_URL = "http://" + BBS_HOST;

	public static final String BBS_BLOCK = "/mainpage.php";

	public static final String BBS_BLOCK_BOARD = "/bbsboa.php?group=";

	public static final String BBS_SUB_BOARD = "/bbsdoc.php?board=";

	public static final String BBS_DOC = "/bbsdoc.php?board=";

	public static final String BBS_DOC_TITLE = "/bbsdoc.php?ftype=6&board=";

	public static final String BBS_DOC_PAGE_PARAM_NAME = "page";

	public static final String BBS_CON = "/bbscon.php?bid=";

	public static final String BBS_CON_FILE_PARAM_NAME = "id";

	public static final String BBS_CON_TYPE_PARAM_NAME = "&ftype=11";

	public static final String BBS_CON_TITLE = "/bbstcon.php?board=";

	public static final String BBS_CON_TITLE_PARAM_NAME = "gid";

	public static final String BBS_CON_PAGE_PARAM_NAME = "pno";

	public static final int BBS_PAGE_SIZE = 20;

}


text:
using namespace lldb;
using namespace lldb_private;

ScriptInterpreter::ScriptInterpreter(Debugger &debugger,
                                     lldb::ScriptLanguage script_lang)
    : m_debugger(debugger), m_script_lang(script_lang) {}

ScriptInterpreter::~ScriptInterpreter() {}

void ScriptInterpreter::CollectDataForBreakpointCommandCallback(
    std::vector<BreakpointOptions *> &bp_options_vec,
    CommandReturnObject &result) {
  result.SetStatus(eReturnStatusFailed);
  result.AppendError(
      "ScriptInterpreter::GetScriptCommands(StringList &) is not implemented.");
}

void ScriptInterpreter::CollectDataForWatchpointCommandCallback(
    WatchpointOptions *bp_options, CommandReturnObject &result) {
  result.SetStatus(eReturnStatusFailed);
  result.AppendError(
      "ScriptInterpreter::GetScriptCommands(StringList &) is not implemented.");
}

std::string ScriptInterpreter::LanguageToString(lldb::ScriptLanguage language) {
  std::string return_value;

  switch (language) {
  case eScriptLanguageNone:
    return_value = "None";
    break;
  case eScriptLanguagePython:
    return_value = "Python";
    break;
  case eScriptLanguageUnknown:
    return_value = "Unknown";
    break;
  }

  return return_value;
}

lldb::ScriptLanguage
ScriptInterpreter::StringToLanguage(const llvm::StringRef &language) {
  if (language.equals_lower(LanguageToString(eScriptLanguageNone)))
    return eScriptLanguageNone;
  if (language.equals_lower(LanguageToString(eScriptLanguagePython)))
    return eScriptLanguagePython;
  return eScriptLanguageUnknown;
}

Status ScriptInterpreter::SetBreakpointCommandCallback(
    std::vector<BreakpointOptions *> &bp_options_vec,
    const char *callback_text) {
  Status return_error;
  for (BreakpointOptions *bp_options : bp_options_vec) {
    return_error = SetBreakpointCommandCallback(bp_options, callback_text);
    if (return_error.Success())
      break;
  }
  return return_error;
}

void ScriptInterpreter::SetBreakpointCommandCallbackFunction(
    std::vector<BreakpointOptions *> &bp_options_vec,
    const char *function_name) {
  for (BreakpointOptions *bp_options : bp_options_vec) {
    SetBreakpointCommandCallbackFunction(bp_options, function_name);
  }
}

std::unique_ptr<ScriptInterpreterLocker>
ScriptInterpreter::AcquireInterpreterLock() {
  return std::unique_ptr<ScriptInterpreterLocker>(
      new ScriptInterpreterLocker());
}


text:
package model.rules;

import model.Box;
import model.formulas.Contradiction;
import model.formulas.Formula;
import model.formulas.Negation;
import start.Constants;

public class NegationIntro extends Rule {

    private Interval interval;

    public NegationIntro() {
        super();
    }

    public NegationIntro(Interval interval) {
        super();
        this.interval = interval;
    }

    @Override
    public boolean hasCompleteInfo() {
        return interval != null;
    }

    @Override
    public void updateReference(int index, String newValue) {
        if (index < 1 || index > 1) throw new IllegalArgumentException();

        if (index == 1) {
            try {
                interval = ReferenceParser.parseIntervalReference(newValue);
            } catch (NumberFormatException e) {
                interval = null;
                throw new NumberFormatException();
            }
        }
    }

    @Override
    public boolean verifyReferences(Box data, int rowIndex) {
        if (!(data.isInScopeOf(interval, rowIndex))) return false;
        Formula intervalEndFormula = data.getRow(interval.endIndex).getFormula();
        return (intervalEndFormula instanceof Contradiction);
    }

    @Override
    public boolean verifyRow(Box data, int rowIndex) {
        Formula intervalStartFormula = data.getRow(interval.startIndex).getFormula();
        Formula RowToVerifyFormula = data.getRow(rowIndex).getFormula();
        if (!(RowToVerifyFormula instanceof Negation)) {
            return false;
        }
        Negation neg = (Negation) RowToVerifyFormula;
        Formula RowToVerifyFormulaNoNeg = neg.formula;
        return intervalStartFormula.equals(RowToVerifyFormulaNoNeg);
    }

    @Override
    public Formula generateRow(Box data) {
        Formula intervalStartFormula = data.getRow(interval.startIndex).getFormula();
        return new Negation(intervalStartFormula);
    }

    @Override
    public String toString() {
        return String.format("¬i, %s", interval);
    }
    @Override
	public String[] getReferenceStrings() {
		String ref1 = interval == null ? "" : (interval.startIndex+1)+"-"+(interval.endIndex+1);
		return new String[]{ref1};
	}

	@Override
	public String getDisplayName() {
		return Constants.negationIntro;
	}
}


text:
<?php

namespace Symfony\Bundle\MakerBundle\Security;

use Symfony\Bundle\MakerBundle\Exception\RuntimeCommandException;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Bundle\MakerBundle\Validator;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @internal
 */
final class InteractiveSecurityHelper
{
    public function guessFirewallName(SymfonyStyle $io, array $securityData, string $questionText = null): string
    {
        $realFirewalls = array_filter(
            $securityData['security']['firewalls'] ?? [],
            function ($item) {
                return !isset($item['security']) || true === $item['security'];
            }
        );

        if (0 === \count($realFirewalls)) {
            return 'main';
        }

        if (1 === \count($realFirewalls)) {
            return key($realFirewalls);
        }

        return $io->choice(
            $questionText ?? 'Which firewall do you want to update?',
            array_keys($realFirewalls),
            key($realFirewalls)
        );
    }

    public function guessEntryPoint(SymfonyStyle $io, array $securityData, string $authenticatorClass, string $firewallName)
    {
        if (!isset($securityData['security'])) {
            $securityData['security'] = [];
        }

        if (!isset($securityData['security']['firewalls'])) {
            $securityData['security']['firewalls'] = [];
        }

        $firewalls = $securityData['security']['firewalls'];
        if (!isset($firewalls[$firewallName])) {
            throw new RuntimeCommandException(sprintf('Firewall "%s" does not exist', $firewallName));
        }

        if (!isset($firewalls[$firewallName]['guard'])
            || !isset($firewalls[$firewallName]['guard']['authenticators'])
            || !$firewalls[$firewallName]['guard']['authenticators']
            || isset($firewalls[$firewallName]['guard']['entry_point'])) {
            return null;
        }

        $authenticators = $firewalls[$firewallName]['guard']['authenticators'];
        $authenticators[] = $authenticatorClass;

        return $io->choice(
            'The entry point for your firewall is what should happen when an anonymous user tries to access
a protected page. For example, a common "entry point" behavior is to redirect to the login page.
The "entry point" behavior is controlled by the start() method on your authenticator.
However, you will now have multiple authenticators. You need to choose which authenticator\'s
start() method should be used as the entry point (the start() method on all other
authenticators will be ignored, and can be blank.',
            $authenticators,
            current($authenticators)
        );
    }

    public function guessUserClass(SymfonyStyle $io, array $providers, string $questionText = null): string
    {
        if (1 === \count($providers) && isset(current($providers)['entity'])) {
            $entityProvider = current($providers);

            return $entityProvider['entity']['class'];
        }

        $userClass = $io->ask(
            $questionText ?? 'Enter the User class that you want to authenticate (e.g. <fg=yellow>App\\Entity\\User</>)',
            $this->guessUserClassDefault(),
            [Validator::class, 'classIsUserInterface']
        );

        return $userClass;
    }

    private function guessUserClassDefault(): string
    {
        if (class_exists('App\\Entity\\User') && isset(class_implements('App\\Entity\\User')[UserInterface::class])) {
            return 'App\\Entity\\User';
        }

        if (class_exists('App\\Security\\User') && isset(class_implements('App\\Security\\User')[UserInterface::class])) {
            return 'App\\Security\\User';
        }

        return '';
    }

    public function guessUserNameField(SymfonyStyle $io, string $userClass, array $providers): string
    {
        if (1 === \count($providers) && isset(current($providers)['entity']) && isset(current($providers)['entity']['property'])) {
            $entityProvider = current($providers);

            return $entityProvider['entity']['property'];
        }

        if (property_exists($userClass, 'email') && !property_exists($userClass, 'username')) {
            return 'email';
        }

        if (!property_exists($userClass, 'email') && property_exists($userClass, 'username')) {
            return 'username';
        }

        $classProperties = [];
        $reflectionClass = new \ReflectionClass($userClass);
        foreach ($reflectionClass->getProperties() as $property) {
            $classProperties[] = $property->name;
        }

        if (empty($classProperties)) {
            throw new \LogicException(sprintf('No properties were found in "%s" entity', $userClass));
        }

        return $io->choice(
            sprintf('Which field on your <fg=yellow>%s</> class will people enter when logging in?', $userClass),
            $classProperties,
            property_exists($userClass, 'username') ? 'username' : (property_exists($userClass, 'email') ? 'email' : null)
        );
    }

    public function guessEmailField(SymfonyStyle $io, string $userClass): string
    {
        if (property_exists($userClass, 'email')) {
            return 'email';
        }

        $classProperties = [];
        $reflectionClass = new \ReflectionClass($userClass);
        foreach ($reflectionClass->getProperties() as $property) {
            $classProperties[] = $property->name;
        }

        return $io->choice(
            sprintf('Which field on your <fg=yellow>%s</> class holds the email address?', $userClass),
            $classProperties
        );
    }

    public function guessPasswordField(SymfonyStyle $io, string $userClass): string
    {
        if (property_exists($userClass, 'password')) {
            return 'password';
        }

        $classProperties = [];
        $reflectionClass = new \ReflectionClass($userClass);
        foreach ($reflectionClass->getProperties() as $property) {
            $classProperties[] = $property->name;
        }

        return $io->choice(
            sprintf('Which field on your <fg=yellow>%s</> class holds the encoded password?', $userClass),
            $classProperties
        );
    }

    public function getAuthenticatorClasses(array $firewallData): array
    {
        $authenticatorClasses = [];

        if (!isset($firewallData['guard'])) {
            return [];
        }

        if (!isset($firewallData['guard']['authenticators'])) {
            return [];
        }

        foreach ($firewallData['guard']['authenticators'] as $authenticator) {
            // skip service id's - as they won't work for autowiring
            if (class_exists($authenticator)) {
                $authenticatorClasses[] = $authenticator;
            }
        }

        return $authenticatorClasses;
    }

    public function guessPasswordSetter(SymfonyStyle $io, string $userClass): string
    {
        if (null === ($methodChoices = $this->methodNameGuesser($userClass, 'setPassword'))) {
            return 'setPassword';
        }

        return $io->choice(
            sprintf('Which method on your <fg=yellow>%s</> class can be used to set the encoded password (e.g. setPassword())?', $userClass),
            $methodChoices
        );
    }

    public function guessEmailGetter(SymfonyStyle $io, string $userClass, string $emailPropertyName): string
    {
        $supposedEmailMethodName = sprintf('get%s', Str::asCamelCase($emailPropertyName));

        if (null === ($methodChoices = $this->methodNameGuesser($userClass, $supposedEmailMethodName))) {
            return $supposedEmailMethodName;
        }

        return $io->choice(
            sprintf('Which method on your <fg=yellow>%s</> class can be used to get the email address (e.g. getEmail())?', $userClass),
            $methodChoices
        );
    }

    public function guessIdGetter(SymfonyStyle $io, string $userClass): string
    {
        if (null === ($methodChoices = $this->methodNameGuesser($userClass, 'getId'))) {
            return 'getId';
        }

        return $io->choice(
            sprintf('Which method on your <fg=yellow>%s</> class can be used to get the unique user identifier (e.g. getId())?', $userClass),
            $methodChoices
        );
    }

    private function methodNameGuesser(string $className, string $suspectedMethodName): ?array
    {
        $reflectionClass = new \ReflectionClass($className);

        if ($reflectionClass->hasMethod($suspectedMethodName)) {
            return null;
        }

        $classMethods = [];

        foreach ($reflectionClass->getMethods() as $method) {
            $classMethods[] = $method->name;
        }

        return $classMethods;
    }
}


text:
<?hh // strict

/**
 * Replaces newlines with paragraph tags.
 */
class :axe:paragraphs extends :x:element implements HasXHPHelpers
{
    use XHPHelpers;

    category %flow;
    children empty;
    attribute :xhp:html-element,
        ?Stringish text = '';

    protected function render(): XHPRoot
    {
        $text = trim((string) $this->:text);
        $container =
;
        foreach (preg_split("/[\r\n]+/m", $text) as $line) {
            $container->appendChild(
{$line}
);
        }
        return $container;
    }
}


text:
package org.apache.uima.tools.cvd.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import org.apache.uima.tools.cvd.AnnotationDisplayCustomizationFrame;
import org.apache.uima.tools.cvd.MainFrame;

/**
 * The Class ShowAnnotationCustomizerHandler.
 */
public class ShowAnnotationCustomizerHandler implements ActionListener {

  /** The main. */
  private final MainFrame main;

  /**
   * Instantiates a new show annotation customizer handler.
   *
   * @param frame
   *          the frame
   */
  public ShowAnnotationCustomizerHandler(MainFrame frame) {
    this.main = frame;
  }

  /*
   * (non-Javadoc)
   *
   * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  @Override
  public void actionPerformed(ActionEvent event) {
    AnnotationDisplayCustomizationFrame acd = new AnnotationDisplayCustomizationFrame(
            "Customize Annotation Display");
    acd.init(this.main.getStyleMap(), this.main.getCas());
    acd.pack();
    acd.setVisible(true);
  }

}


text:
module Facter::Util::Macosx
  require 'thread'
  require 'facter/util/plist'
  require 'facter/util/resolution'

  # JJM I'd really like to dynamically generate these methods
  # by looking at the _name key of the _items dict for each _dataType

  def self.profiler_xml(data_field)
    Facter::Util::Resolution.exec("/usr/sbin/system_profiler -xml #{data_field}")
  end

  def self.intern_xml(xml)
    return nil unless xml
    Plist::parse_xml(xml)
  end

  # Return an xml result, modified as we need it.
  def self.profiler_data(data_field)
    begin
      return nil unless parsed_xml = intern_xml(profiler_xml(data_field))
      return nil unless data = parsed_xml[0]['_items'][0]
      data.delete '_name'
      data
    rescue
      return nil
    end
  end

  def self.hardware_overview
    profiler_data("SPHardwareDataType")
  end

  def self.os_overview
    profiler_data("SPSoftwareDataType")
  end

  def self.sw_vers
    ver = Hash.new
    [ "productName", "productVersion", "buildVersion" ].each do |option|
      ver["macosx_#{option}"] = Facter::Util::Resolution.exec("/usr/bin/sw_vers -#{option}").strip
    end
    productversion = ver["macosx_productVersion"]
    if not productversion.nil?
      versions = productversion.scan(/(\d+)\.(\d+)\.*(\d*)/)[0]
      ver["macosx_productversion_major"] = "#{versions[0]}.#{versions[1]}"
      if versions[2].empty?  # 10.x should be treated as 10.x.0
        versions[2] = "0"
      end
      ver["macosx_productversion_minor"] = versions[2]
    end
    ver
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.monitor.implementation;

import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.monitor.fluent.EventCategoriesClient;
import com.azure.resourcemanager.monitor.fluent.models.LocalizableStringInner;
import com.azure.resourcemanager.monitor.models.EventCategoryCollection;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in EventCategoriesClient. */
public final class EventCategoriesClientImpl implements EventCategoriesClient {
    private final ClientLogger logger = new ClientLogger(EventCategoriesClientImpl.class);

    /** The proxy service used to perform REST calls. */
    private final EventCategoriesService service;

    /** The service client containing this operation class. */
    private final MonitorClientImpl client;

    /**
     * Initializes an instance of EventCategoriesClientImpl.
     *
     * @param client the instance of the service client containing this operation class.
     */
    EventCategoriesClientImpl(MonitorClientImpl client) {
        this.service =
            RestProxy.create(EventCategoriesService.class, client.getHttpPipeline(), client.getSerializerAdapter());
        this.client = client;
    }

    /**
     * The interface defining all the services for MonitorClientEventCategories to be used by the proxy service to
     * perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "MonitorClientEventCa")
    private interface EventCategoriesService {
        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get("/providers/microsoft.insights/eventcategories")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<EventCategoryCollection>> list(
            @HostParam("$host") String endpoint, @QueryParam("api-version") String apiVersion, Context context);
    }

    /**
     * Get the list of available event categories supported in the Activity Logs Service.
The current list
     * includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy.
     *
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the list of available event categories supported in the Activity Logs Service.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<LocalizableStringInner>> listSinglePageAsync() {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        final String apiVersion = "2015-04-01";
        return FluxUtil
            .withContext(context -> service.list(this.client.getEndpoint(), apiVersion, context))
            .<PagedResponse<LocalizableStringInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), null, null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Get the list of available event categories supported in the Activity Logs Service.
The current list
     * includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy.
     *
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the list of available event categories supported in the Activity Logs Service.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<LocalizableStringInner>> listSinglePageAsync(Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        final String apiVersion = "2015-04-01";
        context = this.client.mergeContext(context);
        return service
            .list(this.client.getEndpoint(), apiVersion, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), null, null));
    }

    /**
     * Get the list of available event categories supported in the Activity Logs Service.
The current list
     * includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy.
     *
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the list of available event categories supported in the Activity Logs Service.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<LocalizableStringInner> listAsync() {
        return new PagedFlux<>(() -> listSinglePageAsync());
    }

    /**
     * Get the list of available event categories supported in the Activity Logs Service.
The current list
     * includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy.
     *
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the list of available event categories supported in the Activity Logs Service.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<LocalizableStringInner> listAsync(Context context) {
        return new PagedFlux<>(() -> listSinglePageAsync(context));
    }

    /**
     * Get the list of available event categories supported in the Activity Logs Service.
The current list
     * includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy.
     *
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the list of available event categories supported in the Activity Logs Service.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<LocalizableStringInner> list() {
        return new PagedIterable<>(listAsync());
    }

    /**
     * Get the list of available event categories supported in the Activity Logs Service.
The current list
     * includes the following: Administrative, Security, ServiceHealth, Alert, Recommendation, Policy.
     *
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the list of available event categories supported in the Activity Logs Service.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<LocalizableStringInner> list(Context context) {
        return new PagedIterable<>(listAsync(context));
    }
}