text:
package io.getlime.push.shared;

import io.getlime.push.client.PushServerClient;
import io.getlime.push.client.PushServerClientException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.Security;

@Service
public class PushServerTestClientFactory {

    private static final String TEST_APPLICATION_NAME = "Push_Server_Tests";
    private static final String TEST_APPLICATION_VERSION = "default";
    private static final String TEST_USER_ID = "Test_User";

    @Value("${powerauth.service.url}")
    private String powerAuthRestUrl;

    public PushServerClient createPushServerClient(String baseUrl) throws PushServerClientException {
        return new PushServerClient(baseUrl);
    }

    public PowerAuthTestClient createPowerAuthTestClient() throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        PowerAuthTestClient powerAuthTestClient = new PowerAuthTestClient();
        powerAuthTestClient.initializeClient(powerAuthRestUrl);
        Long applicationId = powerAuthTestClient.initializeApplication(TEST_APPLICATION_NAME, TEST_APPLICATION_VERSION);
        String activationId = powerAuthTestClient.createActivation(TEST_USER_ID);
        String activationId2 = powerAuthTestClient.createActivation(TEST_USER_ID);
        String activationId3 = powerAuthTestClient.createActivation(TEST_USER_ID);
        String activationId4 = powerAuthTestClient.createActivation(TEST_USER_ID);
        powerAuthTestClient.setApplicationId(applicationId);
        powerAuthTestClient.setActivationId(activationId);
        powerAuthTestClient.setActivationId2(activationId2);
        powerAuthTestClient.setActivationId3(activationId3);
        powerAuthTestClient.setActivationId4(activationId4);
        return powerAuthTestClient;
    }
}


text:
require 'spec_helper'

describe Supervisor::CommentsController do
  describe 'routing' do
    it 'routes to #create' do
      expect(post('supervisor/comments')).to route_to('supervisor/comments#create')
    end
  end
end

describe CommentsController do
  describe 'routing' do
    it 'routes to #create' do
      expect(post('/comments')).to route_to('comments#create')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package sshd.shell.springboot.command;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.Resource;
import sshd.shell.springboot.autoconfiguration.SshSessionContext;
import sshd.shell.springboot.util.ZipUtils;

/**
 *
 * @author anand
 */
@lombok.extern.slf4j.Slf4j
public enum CommandUtils {
    ;

    public static Path sessionUserPathContainingZippedResource(Resource resource) throws IOException {
        Path heapDumpFilePath = Paths.get(resource.getURI());
        return ZipUtils.zipFiles(sessionUserDir(), true, heapDumpFilePath);
    }

    private static Path sessionUserDir() throws IOException {
        File sessionUserDir = SshSessionContext.getUserDir();
        if (!sessionUserDir.exists()) {
            Files.createDirectories(sessionUserDir.toPath());
        }
        return sessionUserDir.toPath();
    }

    public static String process(JsonProcessor processor) {
        try {
            return processor.process();
        } catch (IOException | IllegalArgumentException ex) {
            log.warn("Invalid json", ex);
            return "Expected valid json as argument";
        }
    }

    @FunctionalInterface
    public static interface JsonProcessor {

        String process() throws IOException;
    }
}


text:
void Instrument::apply_dynamic_range(std::vector<BasicPeak> &peaks) {
	if (peaks.size() > 0) {
		double max_intensity = std::min_element(peaks.begin(), peaks.end(), BasicPeak::greater_intensity)->intensity;

		max_intensity /= dynamic_range;

		for (auto itr = peaks.begin(); itr != peaks.end();) {
			if (itr->intensity < max_intensity) {
				itr = peaks.erase(itr);
			} else {
				++itr;
			}
		}
	}
}

double Instrument::get_scan_acquisition_time(ScanRequest* scanRequest) {
	if (scanRequest->do_fragmentation) return ms2_scan_time;
	else return ms1_scan_time;
}

double Instrument::get_scan_overhead_time() {
	return scan_overhead_time;
}


text:
package org.apache.felix.upnp.basedriver.importer.core.upnp;

import java.util.Enumeration;
import java.util.Hashtable;

import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.ActionList;
import org.cybergarage.upnp.Service;
import org.cybergarage.upnp.ServiceStateTable;
import org.cybergarage.upnp.StateVariable;

import org.osgi.service.upnp.UPnPAction;
import org.osgi.service.upnp.UPnPService;
import org.osgi.service.upnp.UPnPStateVariable;

/**
* @author Felix Project Team
*/
public class UPnPServiceImpl implements UPnPService {
	private Service service;
	private Hashtable actions;
	private Hashtable stateVariables;

	public UPnPServiceImpl(Service service) {
		this.service = service;
		actions = new Hashtable();
		stateVariables=new Hashtable();
		/*
		 * action
		 */
		ActionList actionlist = service.getActionList();
		for (int i = 0; i < actionlist.size(); i++) {
			Action act = actionlist.getAction(i);
			actions.put(act.getName(), new UPnPActionImpl(act,this));
		}
		/*StateVariable*/
		ServiceStateTable stateTable=service.getServiceStateTable();
		for(int i=0;i<stateTable.size();i++){
			StateVariable var= stateTable.getStateVariable(i);
			stateVariables.put(var.getName(),new UPnPStateVariableImpl(var));
		}

	} /*
	   * (non-Javadoc)
	   *
	   * @see org.osgi.service.upnp.UPnPService#getId()
	   */
	public String getId() {
		// TODO Auto-generated method stub
		return service.getServiceID();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.osgi.service.upnp.UPnPService#getType()
	 */
	public String getType() {
		// TODO Auto-generated method stub
		return service.getServiceType();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.osgi.service.upnp.UPnPService#getVersion()
	 */
	public String getVersion() {
		String serviceType = service.getServiceType();
		int start = serviceType.lastIndexOf(':');
		String version = serviceType.substring(start+1);
		return version;
	}
	/*
	   * (non-Javadoc)
	   *
	   * @see org.osgi.service.upnp.UPnPService#getAction(java.lang.String)
	   */
	public UPnPAction getAction(String name) {
		//TODO to check
		return (UPnPAction) actions.get(name);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.osgi.service.upnp.UPnPService#getActions()
	 */
	public UPnPAction[] getActions() {
		//TODO check again
		Enumeration e=actions.elements();
		if(e==null){
			return null;
		}
		UPnPAction [] uPnPacts=new UPnPAction[actions.size()];
		int i=0;
		while(e.hasMoreElements()){
			uPnPacts[i]=(UPnPActionImpl)e.nextElement();
			i++;
		}
		return uPnPacts;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.osgi.service.upnp.UPnPService#getStateVariables()
	 */
	public UPnPStateVariable[] getStateVariables() {
		//TODO check again
		UPnPStateVariableImpl [] vars =new UPnPStateVariableImpl[stateVariables.size()];
		Enumeration e=stateVariables.elements();
		if(e==null){
			return null;
		}
		int i=0;
		while(e.hasMoreElements()){
			vars[i]=(UPnPStateVariableImpl)e.nextElement();
			i++;
		}
		return vars;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.osgi.service.upnp.UPnPService#getStateVariable(java.lang.String)
	 */
	public UPnPStateVariable getStateVariable(String name) {
		//TODO chack again
		return (UPnPStateVariableImpl) stateVariables.get(name);
	}

	public Service getCyberService(){
		return service;
	}

}


text:
``` diff
 namespace System.Runtime {
+    public static class ControlledExecution {
+        [ObsoleteAttribute("ControlledExecution.Run method may corrupt the process and should not be used in production code.", DiagnosticId="SYSLIB0046", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
+        public static void Run(Action action, CancellationToken cancellationToken);
+    }
 }
```


text:
import linglog from 'linglog';

export default linglog('react-docer', {
  timeFormat: 'HH:mm:ss'
});


text:
using System;
using System.Linq;
using SlackAPI.Tests.Configuration;
using SlackAPI.Tests.Helpers;
using Xunit;

namespace SlackAPI.Tests
{
    [Collection("Integration tests")]
    public class JoinDirectMessageChannel
    {
        private readonly IntegrationFixture fixture;

        public JoinDirectMessageChannel(IntegrationFixture fixture)
        {
            this.fixture = fixture;
        }

        [Fact]
        public void ShouldJoinDirectMessageChannel()
        {
            // given
            var client = this.fixture.UserClient;
            JoinDirectMessageChannelResponse actual = null;

            string userName = this.fixture.Config.DirectMessageUser;
            string user = client.Users.First(x => x.name.Equals(userName, StringComparison.OrdinalIgnoreCase)).id;

            // when
            using (var sync = new InSync(nameof(SlackClient.JoinDirectMessageChannel)))
            {
                client.JoinDirectMessageChannel(response =>
                {
                    actual = response;
                    sync.Proceed();;
                }, user);
            }

            // then
            Assert.True(actual.ok, "Error while joining user channel");
            Assert.NotEmpty(actual.channel.id);
        }
    }
}


text:
using System.Linq;
using Hangfire.Mongo.Database;
using Hangfire.Mongo.Migration;
using Hangfire.Mongo.Migration.Steps.Version15;
using Hangfire.Mongo.Migration.Steps.Version16;
using Hangfire.Mongo.Tests.Utils;
using MongoDB.Bson;
using MongoDB.Driver;
using Moq;
using Xunit;

namespace Hangfire.Mongo.Tests.Migration
{
    [Collection("Database")]
    public class Version16MigrationStepFacts
    {
        private readonly HangfireDbContext _dbContext;
        private readonly Mock<IMongoMigrationBag> _mongoMigrationBagMock;
        private readonly IMongoDatabase _database;

        public Version16MigrationStepFacts()
        {
            _dbContext = ConnectionUtils.CreateDbContext();
            _database = _dbContext.Database;
            _mongoMigrationBagMock = new Mock<IMongoMigrationBag>(MockBehavior.Strict);
        }

        [Fact]
        public void ExecuteStep00_SetDtoNotContainingValue_Success()
        {
            // ARRANGE
            var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
            collection.DeleteMany(_ => true);
            var setDtoJson = @"
                    {
                        '_id' : ObjectId('5c2d1b398dfc0236031e1a35'),
                        'Key' : 'recurring-jobs:HomeController.PrintToDebug',
                        '_t' : ['BaseJobDto', 'ExpiringJobDto','KeyJobDto','SetDto'],
                        'ExpireAt' : null,
                        'Score' : 0.0,
                        'Value' : null
                    }";

            collection.InsertOne(BsonDocument.Parse(setDtoJson));

            // ACT
            var result = new UpdateSetDtoKeyAndValueField().Execute(_dbContext.Database, new MongoStorageOptions(),
                _mongoMigrationBagMock.Object);

            // ASSERT
            var migratedSetDto = collection.Find(_ => true).Single();
            Assert.Equal("recurring-jobs<HomeController.PrintToDebug>", migratedSetDto["Key"].AsString);
            Assert.Equal("HomeController.PrintToDebug", migratedSetDto["Value"].AsString);
        }

        [Fact]
        public void ExecuteStep00_SetDtoNotCompositeKey_Success()
        {
            // ARRANGE
            var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
            collection.DeleteMany(_ => true);
            var setDtoJson = @"
                    {
                        '_id' : ObjectId('5c2d1b398dfc0236031e1a35'),
                        'Key' : 'recurring-jobs',
                        '_t' : ['BaseJobDto', 'ExpiringJobDto','KeyJobDto','SetDto'],
                        'ExpireAt' : null,
                        'Score' : 0.0,
                        'Value' : 'HomeController.PrintToDebug'
                    }";

            collection.InsertOne(BsonDocument.Parse(setDtoJson));

            // ACT
            var result = new UpdateSetDtoKeyAndValueField().Execute(_dbContext.Database, new MongoStorageOptions(),
                _mongoMigrationBagMock.Object);

            // ASSERT
            var migratedSetDto = collection.Find(_ => true).Single();
            Assert.Equal("recurring-jobs<HomeController.PrintToDebug>", migratedSetDto["Key"].AsString);
            Assert.Equal("HomeController.PrintToDebug", migratedSetDto["Value"].AsString);
        }
    }
}


text:
package org.teavm.jso.dom.xml;

/**
 *
 * @author Alexey Andreev
 */
public interface EntityReference extends Node {
}


text:
# This file is automatically generated by puppet-swagger-generator and
# any manual changes are likely to be clobbered when the files
# are regenerated.

require_relative '../../../puppet_x/puppetlabs/kubernetes/provider'

Puppet::Type.type(:kubernetes_ingress_backend).provide(:swagger, :parent => PuppetX::Puppetlabs::Kubernetes::Provider) do

  mk_resource_methods

  def self.instance_to_hash(instance)
    {
    ensure: :present,
    name: instance.metadata.name,

        service_name: instance.serviceName.respond_to?(:to_hash) ? instance.serviceName.to_hash : instance.serviceName,

        service_port: instance.servicePort.respond_to?(:to_hash) ? instance.servicePort.to_hash : instance.servicePort,

    object: instance,
    }
  end

  def create
    Puppet.info("Creating kubernetes_ingress_backend #{name}")
    create_instance_of('ingress_backend', name, build_params)
  end

  def flush
   unless @property_hash.empty?
     unless resource[:ensure] == :absent
        flush_instance_of('ingress_backend', name, @property_hash[:object], build_params)
      end
    end
  end

  def destroy
    Puppet.info("Deleting kubernetes_ingress_backend #{name}")
    destroy_instance_of('ingress_backend', name)
    @property_hash[:ensure] = :absent
  end

  private
  def self.list_instances
    list_instances_of('ingress_backend')
  end

  def build_params
    params = {

        serviceName: resource[:service_name],

        servicePort: resource[:service_port],

    }
    params.delete_if { |key, value| value.nil? }
    params
  end
end


text:
namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace disjoint
{

struct disjoint_segment_box
{
    template <typename Segment, typename Box, typename Strategy>
    static inline bool apply(Segment const& segment, Box const& box, Strategy const& strategy)
    {
        return strategy.apply(segment, box);
    }
};

}} // namespace detail::disjoint
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename Segment, typename Box, std::size_t DimensionCount>
struct disjoint<Segment, Box, DimensionCount, segment_tag, box_tag, false>
    : detail::disjoint::disjoint_segment_box
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_DISJOINT_SEGMENT_BOX_HPP


text:
/*************************************************************************
* Author: Kai Ren
* Created Time: 2013-08-19 00:27:24
* File Name: ./ldb_hdfs_test.c
* Description:
 ************************************************************************/

#include "../backends/leveldb/include/leveldb/c.h"
#include <stdio.h>

struct LDB {
    leveldb_t* db;              // DB instance
    leveldb_comparator_t* cmp;  // Compartor object that allows user-defined
                                // object comparions functions.
    leveldb_cache_t* cache;     // Cache object: If set, individual blocks
                                // (of levelDB files) are cached using LRU.
    leveldb_env_t* env;
    leveldb_options_t* options;
    leveldb_readoptions_t*  lookup_options;
    leveldb_readoptions_t*  scan_options;
    leveldb_writeoptions_t* insert_options;
    leveldb_writeoptions_t* ext_insert_options;
    leveldb_writeoptions_t* sync_insert_options;
};

void init_db(struct LDB *ldb,
             const char* ip, int port,
             const char* dbname) {
    char* err = NULL;

    ldb->options = leveldb_options_create_with_hdfs_env(ip, port);
//    ldb->options = leveldb_options_create();

    leveldb_options_set_create_if_missing(ldb->options, 1);
    leveldb_options_set_info_log(ldb->options, NULL);
    leveldb_options_set_block_size(ldb->options, 1024*64);
    leveldb_options_set_compression(ldb->options, leveldb_no_compression);

    ldb->lookup_options = leveldb_readoptions_create();
    leveldb_readoptions_set_fill_cache(ldb->lookup_options, 1);

    ldb->scan_options = leveldb_readoptions_create();
    leveldb_readoptions_set_fill_cache(ldb->scan_options, 1);

    ldb->insert_options = leveldb_writeoptions_create();
    leveldb_writeoptions_set_sync(ldb->insert_options, 0);

    ldb->ext_insert_options = leveldb_writeoptions_create();
    leveldb_writeoptions_set_sync(ldb->ext_insert_options, 0);

    ldb->sync_insert_options = leveldb_writeoptions_create();
    leveldb_writeoptions_set_sync(ldb->sync_insert_options, 1);

    ldb->db = leveldb_open(ldb->options, dbname, &err);

    if (err != NULL) {
      printf("Error: %s\n", err);
    } else {
      printf("Initialized successfully!\n");
    }
}

void close_db(struct LDB *ldb) {
  leveldb_close(ldb->db);
  leveldb_options_destroy(ldb->options);
  leveldb_readoptions_destroy(ldb->lookup_options);
  leveldb_readoptions_destroy(ldb->scan_options);
  leveldb_writeoptions_destroy(ldb->insert_options);
  leveldb_writeoptions_destroy(ldb->ext_insert_options);
}

void test() {
  struct LDB ldb;
  init_db(&ldb, "localhost", 8020, "/l0/giga_ldb/l0/");

  char key[20];
  char value[20];
  sprintf(value, "hello world");
  char* err = NULL;
  int i;
  int n = 1000;

  int err_cnt = 0;
  for (i = 0; i < n; ++i) {
    sprintf(key, "%010d", i);
    size_t vallen;
    char* return_value = leveldb_get(ldb.db,
                                     ldb.lookup_options,
                                     key, 20,
                                     &vallen,
                                     &err);
    if (err != NULL) {
      err_cnt ++;
    } else
    if (strncmp(return_value, value, vallen) != 0 ||
        vallen == 0) {
      printf("key=%s\n", key);
      err_cnt ++;
    }
  }
  printf("Error count = %d\n", err_cnt);

  for (i = 0; i < n; ++i) {
    sprintf(key, "%010d", i);
    leveldb_put(ldb.db, ldb.insert_options,
                key, 20,
                value, 20,
                &err);
    if (err != NULL) {
      printf("Error: %s\n", err);
    }
  }

  err_cnt = 0;
  for (i = 0; i < n; ++i) {
    sprintf(key, "%010d", i);
    size_t vallen;
    char* return_value = leveldb_get(ldb.db,
                                     ldb.lookup_options,
                                     key, 20,
                                     &vallen,
                                     &err);
    if (err != NULL) {
      err_cnt ++;
    } else
    if (strncmp(return_value, value, vallen) != 0 ||
        vallen == 0) {
      err_cnt ++;
    }
  }
  printf("Error count = %d\n", err_cnt);

  close_db(&ldb);
}

int main() {
  test();
  return 0;
}


text:
package org.apache.eagle.security.userprofile.impl;

import org.apache.eagle.ml.model.MLModelAPIEntity;
import org.apache.eagle.security.userprofile.UserProfileMLAlgorithmEvaluator;
import org.apache.eagle.security.userprofile.model.UserProfileKDEModel;
import org.apache.eagle.security.userprofile.model.UserProfileKDEModelEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public abstract class AbstractUserProfileKDEEvaluator extends UserProfileMLAlgorithmEvaluator<UserProfileKDEModel> {
    private final static Logger LOG = LoggerFactory.getLogger(AbstractUserProfileKDEEvaluator.class);

    @Override
    public UserProfileKDEModel convert(MLModelAPIEntity entity) throws IOException {
        try {
            return UserProfileKDEModelEntity.deserializeModel(entity);
        } catch (IOException e) {
            LOG.error(e.getMessage(),e);
            throw e;
        }
    }
}


text:
using System;

namespace FluentNHibernate.Conventions.Inspections
{
    [Obsolete("Use ICollectionInspector")]
    public interface IMapInspector : ICollectionInspector
    {}
}


text:
Backup bundle
=============
[![Latest Stable Version](https://poser.pugx.org/nkt/backup-bundle/v/stable.svg)](https://packagist.org/packages/nkt/backup-bundle) [![Total Downloads](https://poser.pugx.org/nkt/backup-bundle/downloads.svg)](https://packagist.org/packages/nkt/backup-bundle) [![Latest Unstable Version](https://poser.pugx.org/nkt/backup-bundle/v/unstable.svg)](https://packagist.org/packages/nkt/backup-bundle) [![License](https://poser.pugx.org/nkt/backup-bundle/license.svg)](https://packagist.org/packages/nkt/backup-bundle)

Usage
-----

Add `"nkt/backup-bundle": "1.0.x-dev"` into composer.json.

Add `Nkt\BackupBundle\NktBackupBundle` into your kernel bundles.

Now you can add new cron job, for backup your application:

```bash
0 */6 * * * /path/to/app/console doctrine:database:backup --gzip=-9
```

You can also restore any backup using

```bash
/path/to/app/console doctrine:database:restore /path/to/app/backup/backupname.sql.gz
```

Backup options
--------------

Backup filename contains driver name, database name and date.
You can change date pattern (by default `Y-m-d-H-i-s`)
using `--date-pattern` option.

If you using multiply connections, specify it using `--connection` option
or `-c` flag.

By default all backups saves into `path/to/app/backups`, you can change it
using `--destination` option or `-d` flag.

As you can see in example, you can compress backups using `--gzip` option.
This option required value, you have to specify compress quality.

Restore options
---------------

Restore command required filename by first argument. It also support
change connection with `--connection` option or `-c` flag.

You don't have to specify gzipped file. Command checks does filename
ends with `.gz` and decompress it.

License
-------

MIT


text:
<nav-header></nav-header>
<nav-sidebar></nav-sidebar>


text:
using std::string;
typedef int socket_t;
typedef unsigned char IPAddress [4];

class StreamBase{
protected:
	virtual void close(void) = 0;
};

#endif


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

#include "ClusterPoolXML.h"

using namespace std;

const int ClusterPoolXML::NONE_CLUSTER_ID   = -1;

void ClusterPoolXML::add_object(xmlNodePtr node)
{
    if ( node == 0 || node->children == 0 )
    {
        NebulaLog::log("CLUSTER",Log::ERROR,
                       "XML Node does not represent a valid Cluster");

        return;
    }

    ClusterXML* cluster = new ClusterXML( node );

    objects.insert( pair<int,ObjectXML*>(cluster->get_oid(), cluster) );
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int ClusterPoolXML::load_info(xmlrpc_c::value &result)
{
    try
    {
        client->call("one.clusterpool.info", "", &result);

        return 0;
    }
    catch (exception const& e)
    {
        ostringstream   oss;
        oss << "Exception raised: " << e.what();

        NebulaLog::log("CLUSTER", Log::ERROR, oss);

        return -1;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */


text:
package microsoft.exchange.webservices.data;

/**
 * Represents a response object created to supress read receipts for an item.
 */
@ServiceObjectDefinition(xmlElementName = XmlElementNames.SuppressReadReceipt, returnedByServer = false)
 final class SuppressReadReceipt extends ServiceObject {

	/** The reference item. */
	private Item referenceItem;

	/**
	 * Initializes a new instance of the class.
	 *
	 * @param referenceItem
	 *            the reference item
	 * @throws Exception
	 *             the exception
	 */
	protected SuppressReadReceipt(Item referenceItem) throws Exception {
		super(referenceItem.getService());

		referenceItem.throwIfThisIsNew();
		this.referenceItem = referenceItem;
	}

	/**
	 * Internal method to return the schema associated with this type of object.
	 *
	 * @return The schema associated with this type of object.
	 */
	@Override
	protected ServiceObjectSchema getSchema() {
		return ResponseObjectSchema.Instance;
	}

	/**
	 * Gets the minimum required server version.
	 *
	 * @return Earliest Exchange version in which this service object type is
	 *         supported.
	 */
	@Override
	protected ExchangeVersion getMinimumRequiredServerVersion() {
		return ExchangeVersion.Exchange2007_SP1;
	}

	/**
	 * Loads the specified set of properties on the object.
	 *
	 * @param propertySet
	 *            the property set
	 */
	@Override
	protected void internalLoad(PropertySet propertySet) {
		throw new UnsupportedOperationException();
	}

	/**
	 * Deletes the object.
	 *
	 * @param deleteMode
	 *            the delete mode
	 * @param sendCancellationsMode
	 *            the send cancellations mode
	 * @param affectedTaskOccurrences
	 *            the affected task occurrences
	 */
	@Override
	protected void internalDelete(DeleteMode deleteMode,
			SendCancellationsMode sendCancellationsMode,
			AffectedTaskOccurrence affectedTaskOccurrences) {
		throw new UnsupportedOperationException();
	}

	/**
	 * Create the response object.
	 *
	 * @param parentFolderId
	 *            the parent folder id
	 * @param messageDisposition
	 *            the message disposition
	 * @throws Exception
	 *             the exception
	 */
	protected void internalCreate(FolderId parentFolderId,
			MessageDisposition messageDisposition) throws Exception {
		((ItemId)this.getPropertyBag().getObjectFromPropertyDefinition(
				ResponseObjectSchema.ReferenceItemId))
				.assign(this.referenceItem.getId());
		this.getService().internalCreateResponseObject(this, parentFolderId,
				messageDisposition);
	}
}


text:
DROP SCHEMA  IF EXISTS programs_manager_schema CASCADE;

CREATE SCHEMA programs_manager_schema
  AUTHORIZATION postgres;


text:
import React from 'react'
import { render } from 'enzyme'
import test from 'tape'

import List from '..'
import ListItem from '../../ListItem'

test('List', t => {
  t.ok(List, 'export')
  t.equal(List.displayName, 'FabricComponent(List)')

  t.end()
})

test('List#render - simple', t => {
  const container = render(
    <List>Foo</List>
  ).contents()

  t.assert(container.is('ul.ms-List', 'container'))
  t.assert(container.is('[data-fabric="List"]'), 'data-fabric')
  t.equal(container.text(), 'Foo')

  t.end()
})

test('List#render - selectable', t => {
  // shallow test would be better
  const wrapper = render(
    <List selectable>
      <ListItem primaryText="Foo" />
      <ListItem primaryText="Bar" />
      <ListItem primaryText="Baz" />
    </List>
  )

  t.assert(wrapper.find('.ms-ListItem-selectionTarget').length, 3)

  t.end()
})


text:
#ifndef NdbIndexOperation_H
#define NdbIndexOperation_H

#include "NdbOperation.hpp"

class Index;
class NdbResultSet;

/**
 * @class NdbIndexOperation
 * @brief Class of index operations for use in transactions
 */
class NdbIndexOperation : public NdbOperation
{
#ifndef DOXYGEN_SHOULD_SKIP_INTERNAL
  friend class Ndb;
  friend class NdbTransaction;
#endif

public:
  /**
   * @name Define Standard Operation
   * @{
   */

  /** insert is not allowed */
  int insertTuple();

  /**
   * Define the NdbIndexOperation to be a standard operation of type readTuple.
   * When calling NdbTransaction::execute, this operation
   * reads a tuple.
   *
   * @return 0 if successful otherwise -1.
   */
  int readTuple(LockMode);

#ifndef DOXYGEN_SHOULD_SKIP_DEPRECATED
  /**
   * Define the NdbIndexOperation to be a standard operation of type readTuple.
   * When calling NdbTransaction::execute, this operation
   * reads a tuple.
   *
   * @return 0 if successful otherwise -1.
   */
  int readTuple();

  /**
   * Define the NdbIndexOperation to be a standard operation of type
   * readTupleExclusive.
   * When calling NdbTransaction::execute, this operation
   * read a tuple using an exclusive lock.
   *
   * @return 0 if successful otherwise -1.
   */
  int readTupleExclusive();

  /**
   * Define the NdbIndexOperation to be a standard operation of type simpleRead.
   * When calling NdbTransaction::execute, this operation
   * reads an existing tuple (using shared read lock),
   * but releases lock immediately after read.
   *
   * @note  Using this operation twice in the same transaction
   *        may produce different results (e.g. if there is another
   *        transaction which updates the value between the
   *        simple reads).
   *
   * Note that simpleRead can read the value from any database node while
   * standard read always read the value on the database node which is
   * primary for the record.
   *
   * @return 0 if successful otherwise -1.
   */
  int simpleRead();

  /**
   * Define the NdbOperation to be a standard operation of type committedRead.
   * When calling NdbTransaction::execute, this operation
   * read latest committed value of the record.
   *
   * This means that if another transaction is updating the
   * record, then the current transaction will not wait.
   * It will instead use the latest committed value of the
   * record.
   *
   * @return 0 if successful otherwise -1.
   */
  int dirtyRead();

  int committedRead();
#endif

  /**
   * Define the NdbIndexOperation to be a standard operation of type
   * updateTuple.
   *
   * When calling NdbTransaction::execute, this operation
   * updates a tuple in the table.
   *
   * @return 0 if successful otherwise -1.
   */
  int updateTuple();

  /**
   * Define the NdbIndexOperation to be a standard operation of type
   * deleteTuple.
   *
   * When calling NdbTransaction::execute, this operation
   * deletes a tuple.
   *
   * @return 0 if successful otherwise -1.
   */
  int deleteTuple();

  /**
   * Get index object for this operation
   */
  const NdbDictionary::Index * getIndex() const;

#ifndef DOXYGEN_SHOULD_SKIP_DEPRECATED
  /**
   * Define the NdbIndexOperation to be a standard operation of type
   * dirtyUpdate.
   *
   * When calling NdbTransaction::execute, this operation
   * updates without two-phase commit.
   *
   * @return 0 if successful otherwise -1.
   */
  int dirtyUpdate();
#endif

#ifndef DOXYGEN_SHOULD_SKIP_INTERNAL
  /** @} *********************************************************************/
  /**
   * @name Define Interpreted Program Operation
   * @{
   */

  /**
   * Update a tuple using an interpreted program.
   *
   * @return 0 if successful otherwise -1.
   */
  int interpretedUpdateTuple();

  /**
   * Delete a tuple using an interpreted program.
   *
   * @return 0 if successful otherwise -1.
   */
  int interpretedDeleteTuple();
#endif

  /** @} *********************************************************************/

private:
  NdbIndexOperation(Ndb* aNdb);
  ~NdbIndexOperation();

  int receiveTCINDXREF(NdbApiSignal* aSignal);

  // Overloaded methods from NdbCursorOperation
  int indxInit(const class NdbIndexImpl* anIndex,
	       const class NdbTableImpl* aTable,
	       NdbTransaction*);

  // Private attributes
  const NdbIndexImpl* m_theIndex;
  friend struct Ndb_free_list_t<NdbIndexOperation>;
};

#endif


text:
tank.explode() # Do explosion visual
explosion_channel = explosion_sound.play()
if explosion_channel is not None:
    left, right = stereo_pan(tank.position.x, SCREEN_SIZE[0])
    explosion_channel.set_volume(left, right)


text:
function exit_on_error {
  echo "Step \"$1\" of test.sh failed"
  exit 1
}

sbt clean coverage test  || exit_on_error "sbt clean coverage test"
sbt coverageReport       || exit_on_error "sbt coverageReport"
sbt coverageAggregate    || exit_on_error "sbt coverageAggreagate"
sbt codacyCoverage       || exit_on_error "sbt codacyCoverage"


text:
function varargout = recordmodule(varargin)
% RECORDMODULE M-file for recordmodule.fig
%      RECORDMODULE, by itself, creates a new RECORDMODULE or raises the existing
%      singleton*.
%
%      H = RECORDMODULE returns the handle to a new RECORDMODULE or the handle to
%      the existing singleton*.
%
%      RECORDMODULE('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RECORDMODULE.M with the given input arguments.
%
%      RECORDMODULE('Property','Value',...) creates a new RECORDMODULE or
%      raises the existing singleton*.  Starting from the left, property
%      value pairs are applied to the GUI before recordmodule_OpeningFunction
%      gets called.  An unrecognized property name or invalid value makes
%      property application stop.  All inputs are passed to
%      recordmodule_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Copyright 2002-2003 The MathWorks, Inc.

% Edit the above text to modify the response to help recordmodule

% Last Modified by GUIDE v2.5 04-May-2016 09:18:16

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @recordmodule_OpeningFcn, ...
                   'gui_OutputFcn',  @recordmodule_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end

% Import needed folders. Yeah, I'm editing the initialization code
addpath(strcat(cd, '/recordmodule'));
addpath(strcat(cd, '/edition'));

% End initialization code - DO NOT EDIT

% --- Executes just before recordmodule is made visible.
function recordmodule_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to recordmodule (see VARARGIN)

% Choose default command line output for recordmodule
handles.output = hObject;

% Update handles structure
handles.constants = load_constants();
add_eeglab_path(handles.constants.get('EEGLAB_PATH'));
guidata(hObject, handles);

% --- Outputs from this function are returned to the command line.
function varargout = recordmodule_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on selection change in popupMode.
function popupMode_Callback(hObject, eventdata, handles)
% hObject    handle to popupMode (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: - `contents = get(hObject, 'String')` returns popupMode
%          contents as cell array
%        - `contents{get(hObject, 'Value')}` returns selected item
%          from popupMode
contents = get(handles.popupMode, 'String');
runningmode = contents{get(handles.popupMode, 'Value')};
switch runningmode
    case 'Protolize!!'
        setup_for_protolize(handles);
    case 'EEGLAB'
        setup_for_eeglab(handles);
    case 'Chopping'
        setup_for_chopping(handles);
    case 'EMG-RGP'
        setup_for_chopping(handles);
end

% --- Executes during object creation, after setting all properties.
function popupMode_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupMode (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
color = 'white';
if ~ispc
    color = get(0, 'defaultUicontrolBackgroundColor');
end
set(hObject, 'BackgroundColor', color);

% --- Executes on button press in buttonRun. -------------------------
function buttonRun_Callback(hObject, eventdata, handles)
% hObject    handle to buttonRun (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
contents = get(handles.popupMode, 'String');
runningmode = contents{get(handles.popupMode, 'Value')};
switch runningmode
    case 'Protolize!!'
        run_for_protolize(handles);
    case 'EEGLAB'
        run_for_eeglab(handles);
    case 'Chopping'
        run_for_chopping(handles);
    case 'EMG-RGP'
        run_for_emgrgp(handles);
end

% --------------------------------------------------------------------
function quitMenu_Callback(hObject, eventdata, handles)
% hObject    handle to quitMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
selection = questdlg(['Close module?'], ...
                     ['Closing module...'], ...
                     'Yes', 'No', 'Yes');
if strcmp(selection, 'No')
    return;
end
delete(handles.figure1)

% --------------------------------------------------------------------
function settingsMenu_Callback(hObject, eventdata, handles)
% hObject    handle to settingsMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
paramconfig;

% --------------------------------------------------------------------
function menuFile_Callback(hObject, eventdata, handles)
% hObject    handle to menuFile (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --------------------------------------------------------------------
function editMenu_Callback(hObject, eventdata, handles)
% hObject    handle to editMenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in checkMultiple. ---------------------
function checkMultiple_Callback(hObject, eventdata, handles)
% hObject    handle to checkMultiple (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkMultiple

% --- Executes on button press in checkRerefer. ----------------------
function checkRerefer_Callback(hObject, eventdata, handles)
% hObject    handle to checkRerefer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkRerefer
value = 'off';
if get(handles.checkRerefer, 'Value')
    value = 'on';
end
set(handles.editRerefer, 'Enable', value);

% -------------------------------------------------------------------
function editRerefer_Callback(hObject, eventdata, handles)
% hObject    handle to editRerefer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: - get(hObject,'String') returns contents of editRerefer as text
%        - str2double(get(hObject,'String')) returns contents of
%          editRerefer as a double

% --- Executes during object creation, after setting all properties.
function editRerefer_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editRerefer (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject,'BackgroundColor','white');
else
    set(hObject, ...
        'BackgroundColor', ...
        get(0, 'defaultUicontrolBackgroundColor'));
end

% --- Executes on button press in checkResample. --------------------
function checkResample_Callback(hObject, eventdata, handles)
% hObject    handle to checkResample (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkResample
value = 'off';
if get(handles.checkResample, 'Value')
    value = 'on';
end
set(handles.editResample, 'Enable', value);

function editResample_Callback(hObject, eventdata, handles)
% hObject    handle to editResample (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: - get(hObject,'String') returns contents of editResample as text
%        - str2double(get(hObject,'String')) returns contents of
%          editResample as a double

% --- Executes during object creation, after setting all properties. -
function editResample_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editResample (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject, 'BackgroundColor', 'white');
else
    set(hObject, ...
        'BackgroundColor', ...
        get(0,'defaultUicontrolBackgroundColor'));
end

% --- Executes on button press in checkICA. -------------------------
function checkICA_Callback(hObject, eventdata, handles)
% hObject    handle to checkICA (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkICA

% --------------------------------------------------------------------
function editInput_Callback(hObject, eventdata, handles)
% hObject    handle to editInput (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: - get(hObject,'String') returns contents of editInput as text
%        - str2double(get(hObject,'String')) returns contents of editInput
%          as a double

% --- Executes during object creation, after setting all properties. -
function editInput_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editInput (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc
    set(hObject, ...
        'BackgroundColor', ...
        'white');
else
    set(hObject, ...
        'BackgroundColor', ...
        get(0, 'defaultUicontrolBackgroundColor'));
end

% --- Executes on button press in buttonSearch. ---------------------
function buttonSearch_Callback(hObject, eventdata, handles)
% hObject    handle to buttonSearch (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile('*', 'MultiSelect', 'on');
if isnumeric(filename)
    return
elseif iscell(filename)
    set(handles.editInput, ...
        'String', ...
        join_strings(append_on_each_one(filename, ...
                                        pathname), ...
                     ';'));
else
    set(handles.editInput, ...
        'String', ...
        strcat(pathname, ...
               filename));
end


text:
"""Provides miscellaneous utility functions.

These functions are independent of other modules in this codebase.
"""

import datetime
import re

CAPWORDS_REGEX = None

def WMIDateToPythonDateTime(wmistr):
  """Converts WMI dates to Python datetime.datetime objects.

  See http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_yakv.mspx.

  Args:
    wmistr: MS WMI date to convert
  Returns:
    datetime.datetime object (UTC)
  """
  year = int(wmistr[0:4])
  month = int(wmistr[4:6])
  day = int(wmistr[6:8])
  hours = int(wmistr[8:10])
  minutes = int(wmistr[10:12])
  seconds = int(wmistr[12:14])
  microseconds = int(wmistr[15:21])
  return datetime.datetime(
      year, month, day, hours, minutes, seconds, microseconds)

def TimeDeltaToSeconds(delta):
  """Converts a datetime.timedelta to integer seconds.

  Args:
    delta: a datetime.timedelta object.

  Returns:
    the integer seconds for the timedelta.
  """
  return delta.seconds + (delta.days * 3600 * 24)

def CapWordsToLowerWithUnder(capwords_string):
  """Given a CapWords string, return it in lower_with_under style.

  Args:
    capwords_string: a string like CapWords (UpperCamelCasing).

  Returns:
    A string in lower_with_under style. i.e. FunAuthTest returns fun_auth_test.
  """
  # pylint: disable-msg=W0603
  global CAPWORDS_REGEX
  if CAPWORDS_REGEX is None:
    CAPWORDS_REGEX = re.compile(r'(?<!\A)([A-Z](?=[a-z])|(?<![A-Z])[A-Z])')
  lower_with_under = CAPWORDS_REGEX.sub(r'_\1', capwords_string)
  return lower_with_under.lower()


text:
package io.cdap.directives.column;

import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.annotation.Plugin;
import io.cdap.wrangler.api.Arguments;
import io.cdap.wrangler.api.Directive;
import io.cdap.wrangler.api.DirectiveExecutionException;
import io.cdap.wrangler.api.DirectiveParseException;
import io.cdap.wrangler.api.ExecutorContext;
import io.cdap.wrangler.api.Optional;
import io.cdap.wrangler.api.Row;
import io.cdap.wrangler.api.annotations.Categories;
import io.cdap.wrangler.api.lineage.Lineage;
import io.cdap.wrangler.api.lineage.Many;
import io.cdap.wrangler.api.lineage.Mutation;
import io.cdap.wrangler.api.parser.Identifier;
import io.cdap.wrangler.api.parser.TokenType;
import io.cdap.wrangler.api.parser.UsageDefinition;

import java.util.List;

/**
 * This class ChangeColCaseNames converts the case of the columns
 * to either lower-case or uppercase.
 */
@Plugin(type = Directive.TYPE)
@Name(ChangeColCaseNames.NAME)
@Categories(categories = { "column"})
@Description("Changes the case of column names to either lowercase or uppercase.")
public class ChangeColCaseNames implements Directive, Lineage {
  public static final String NAME = "change-column-case";
  private boolean toLower;

  @Override
  public UsageDefinition define() {
    UsageDefinition.Builder builder = UsageDefinition.builder(NAME);
    builder.define("case", TokenType.IDENTIFIER, Optional.TRUE);
    return builder.build();
  }

  @Override
  public void initialize(Arguments args) throws DirectiveParseException {
    toLower = true;
    if (args.contains("case")) {
      Identifier identifier = args.value("case");
      String casing = identifier.value();
      if (casing.equalsIgnoreCase("upper") || casing.equalsIgnoreCase("uppercase")) {
        toLower = false;
      }
    }
  }

  @Override
  public void destroy() {
    // no-op
  }

  @Override
  public List<Row> execute(List<Row> rows, ExecutorContext context) throws DirectiveExecutionException {
    for (Row row : rows) {
      for (int i = 0; i < row.width(); ++i) {
        String name = row.getColumn(i);
        if (toLower) {
          row.setColumn(i, name.toLowerCase());
        } else {
          row.setColumn(i, name.toUpperCase());
        }
      }
    }
    return rows;
  }

  @Override
  public Mutation lineage() {
    return Mutation.builder()
      .readable("Changed all column names to ", toLower ? "'lowercase'" : "'uppercase'")
      .all(Many.of())
      .build();
  }
}


text:
package apple.metalperformanceshaders;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSCoder;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import apple.metal.protocol.MTLDevice;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.ConstFloatPtr;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.ProtocolClassMethod;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * MPSImageThresholdToZero
 *

 * The MPSImageThresholdToZero filter applies a fixed-level threshold to each pixel in the image.
 * The threshold functions convert a single channel image to a binary image.
 * If the input image is not a single channel image, convert the inputimage to a single channel
 * luminance image using the linearGrayColorTransform and then apply the threshold.
 * The ThresholdToZero function is:
 * destinationPixelValue = sourcePixelValue > thresholdValue ? sourcePixelValue : 0
 */
@Generated
@Library("MetalPerformanceShaders")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class MPSImageThresholdToZero extends MPSUnaryImageKernel {
    static {
        NatJ.register();
    }

    @Generated
    protected MPSImageThresholdToZero(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native MPSImageThresholdToZero alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native MPSImageThresholdToZero allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native MPSImageThresholdToZero new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    @Generated
    @Selector("init")
    public native MPSImageThresholdToZero init();

    @Generated
    @Selector("initWithDevice:")
    public native MPSImageThresholdToZero initWithDevice(@Mapped(ObjCObjectMapper.class) Object device);

    /**
     * initialize a MPSImageThresholdToZero filter
     *
     * @param device         The device the filter will run on
     * @param thresholdValue The threshold value to use
     * @param transform      This matrix is an array of 3 floats.
     *                       The default if no transform is specifed is BT.601/JPEG: {0.299f, 0.587f, 0.114f};
     */
    @Generated
    @Selector("initWithDevice:thresholdValue:linearGrayColorTransform:")
    public native MPSImageThresholdToZero initWithDeviceThresholdValueLinearGrayColorTransform(
            @Mapped(ObjCObjectMapper.class) MTLDevice device, float thresholdValue, ConstFloatPtr transform);

    /**
     * [@property] thresholdValue
     *

     * The threshold value used to init the threshold filter
     */
    @Generated
    @Selector("thresholdValue")
    public native float thresholdValue();

    /**
     * [@property] transform
     *

     * The color transform used to init the threshold filter
     */
    @Generated
    @Selector("transform")
    public native ConstFloatPtr transform();

    @Generated
    @Selector("initWithCoder:")
    public native MPSImageThresholdToZero initWithCoder(NSCoder aDecoder);

    /**
     * NSSecureCoding compatability
     *

     * While the standard NSSecureCoding/NSCoding method
     * -initWithCoder: should work, since the file can't
     * know which device your data is allocated on, we
     * have to guess and may guess incorrectly. To avoid
     * that problem, use initWithCoder:device instead.
     *
     * @param aDecoder The NSCoder subclass with your serialized MPSKernel
     * @param device   The MTLDevice on which to make the MPSKernel
     * @return A new MPSKernel object, or nil if failure.
     */
    @Generated
    @Selector("initWithCoder:device:")
    public native MPSImageThresholdToZero initWithCoderDevice(NSCoder aDecoder,
            @Mapped(ObjCObjectMapper.class) Object device);

    @Generated
    @Selector("supportsSecureCoding")
    public static native boolean supportsSecureCoding();

    @Generated
    @ProtocolClassMethod("supportsSecureCoding")
    public boolean _supportsSecureCoding() {
        return supportsSecureCoding();
    }
}


text:
/**
 * SchemaGenerator.java
 * @author Vagisha Sharma
 * Sep 10, 2010
 */
package org.yeastrc.jqs.queue.ws;

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

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;

/**
 *
 */
public class SchemaGenerator {

	public static void main(String[] args) throws IOException, JAXBException {

		// specify where the generated XML schema will be created
		String schemaDir = "/Users/silmaril/WORK/UW/Workspaces/MyEclipse8.5/MSDaPlUploadQueue/";
		final File dir = new File(schemaDir);

		// create a JAXBContext for the MsJob class
		JAXBContext ctx = JAXBContext.newInstance(MsJob.class);
		// generate an XML schema from the annotated object model; create it
		// in the dir specified earlier under the default name, schema1.xsd
		ctx.generateSchema(new SchemaOutputResolver() {
			   @Override
			   public Result createOutput(String namespaceUri, String schemaName) throws IOException {
					return new StreamResult(new File(dir, "msjob_schema.xsd"));
			   }
		   });
	}
}


text:
import Enzyme, { ShallowWrapper, ReactWrapper } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import deprecated from 'prop-types-extra/lib/deprecated';

import { _resetWarned } from '../src/utils/deprecationWarning';

Enzyme.configure({ adapter: new Adapter() });

function assertLength(length) {
  return function $assertLength(selector) {
    let result = this.find(selector);
    expect(result).to.have.length(length);
    return result;
  };
}

ReactWrapper.prototype.assertSingle = assertLength(1);
ShallowWrapper.prototype.assertSingle = assertLength(1);

ReactWrapper.prototype.assertNone = assertLength(0);
ShallowWrapper.prototype.assertNone = assertLength(0);

beforeEach(() => {
  /* eslint-disable no-console */
  sinon.stub(console, 'error').callsFake(msg => {
    let expected = false;

    console.error.expected.forEach(about => {
      if (msg.indexOf(about) !== -1) {
        console.error.warned[about] = true;
        expected = true;
      }
    });

    if (expected) {
      return;
    }

    console.error.threw = true;
    throw new Error(msg);
  });

  console.error.expected = [];
  console.error.warned = Object.create(null);
  console.error.threw = false;
  /* eslint-enable no-console */
});

afterEach(() => {
  /* eslint-disable no-console */
  if (!console.error.threw && console.error.expected.length) {
    expect(console.error.warned).to.have.keys(console.error.expected);
  }

  console.error.restore();
  /* eslint-enable no-console */

  _resetWarned();
  deprecated._resetWarned();
});

describe('Process environment for tests', () => {
  it('should not be production for React console warnings', () => {
    expect(process.env.NODE_ENV).to.not.equal('production');
  });
});

// Ensure all files in src folder are loaded for proper code coverage analysis.
const srcContext = require.context('../src', true, /.*\.js$/);
srcContext.keys().forEach(srcContext);

const testsContext = require.context('.', true, /Spec$/);
testsContext.keys().forEach(testsContext);


text:
import { fire } from 'simulant';
import { initModule } from '../../helpers/test-config';
import { test } from 'qunit';

export default function() {
  initModule('event/expression.js');

  test('events can be handled as expressions', t => {
    const r = new Ractive({
      el: fixture,
      template: `<button on-click="@this.set('foo', 42)">click me</button>`,
      data: { foo: 'nope' }
    });
    const button = r.find('button');

    simulant.fire(button, 'click');

    t.equal(r.get('foo'), 42);
  });

  test('expression events can handle arguments refs', t => {
    t.expect(1);

    const r = new Ractive({
      el: fixture,
      template: `<button on-click=".check(arguments[0])">click me</button>`,
      data: {
        check(arg) {
          t.ok('foo' === arg);
        }
      }
    });

    r.getContext('button').raise('click', {}, 'foo');
  });

  test('expression events can handle dollar refs', t => {
    t.expect(1);

    const r = new Ractive({
      el: fixture,
      template: `<button on-click=".check($1)">click me</button>`,
      data: {
        check(arg) {
          t.ok('foo' === arg);
        }
      }
    });

    r.getContext('button').raise('click', {}, 'foo');
  });

  test('expression events can handle spread args', t => {
    t.expect(1);

    const r = new Ractive({
      el: fixture,
      template: `<button on-click=".check(...arguments)">click me</button>`,
      data: {
        check(arg) {
          t.ok('foo' === arg);
        }
      }
    });

    r.getContext('button').raise('click', {}, 'foo');
  });

  test('expression events can handle argument keypath access', t => {
    t.expect(1);

    const r = new Ractive({
      el: fixture,
      template: `<button on-click=".check(arguments[0].length)">click me</button>`,
      data: {
        check(arg) {
          t.ok(3 === arg);
        }
      }
    });

    r.getContext('button').raise('click', {}, 'foo');
  });

  test('expression events can handle dollar arg keypath access', t => {
    t.expect(1);

    const r = new Ractive({
      el: fixture,
      template: `<button on-click=".check($1.length)">click me</button>`,
      data: {
        check(arg) {
          t.ok(3 === arg);
        }
      }
    });

    r.getContext('button').raise('click', {}, 'foo');
  });

  test('expression events work with complex expressions', t => {
    const r = new Ractive({
      el: fixture,
      template: `<button on-click="@this.set('foo', 42) && @this.toggle('bar')">click me</button>`
    });

    fire(r.find('button'), 'click');

    t.equal(r.get('foo'), 42);
    t.equal(r.get('bar'), true);
  });

  test('comma-ish operator can be used with expression events', t => {
    const r = new Ractive({
      el: fixture,
      template: `<button on-click="@this.set('foo', 42), @this.toggle('bar')">click me</button>`
    });

    fire(r.find('button'), 'click');

    t.equal(r.get('foo'), 42);
    t.equal(r.get('bar'), true);
  });
}


text:
class Ability
  class << self
    def allowed(user, subject)
      return [] unless user.kind_of?(User)

      case subject.class.name
      when "Page" then page_abilities(user, subject)
      when "User" then user_abilities(user, subject)
      else []
      end.concat(global_abilities(user))
    end

    def global_abilities(user)
      rules = []
      rules
    end

    def page_abilities(user, page)
      rules = []

      members = page.page_members
      member = page.page_members.find_by_user_id(user.id)

      # Rules based on role in page
      if user.admin? || members.admins.include?(member)
        rules << page_admin_rules

      elsif members.masters.include?(member)
        rules << page_master_rules

      elsif members.editors.include?(member)
        rules << page_editor_rules

      elsif members.guests.include?(member)
        rules << page_guest_rules
      end

      rules.flatten
    end

    def user_abilities(user, subject)
      rules = []

      # An user can only show and update itself
      if user.id == subject.id
        rules << [:show_user, :update_user]
      end

      rules.flatten
    end

    def page_guest_rules
      [
        :read_page,
        :read_budget,
        :read_page_member,
        :leave_page
      ]
    end

    def page_editor_rules
      page_guest_rules + [
        :update_page,
        :create_budget,
        :delete_budget,
      ]
    end

    def page_master_rules
      page_editor_rules + [
        :create_page_member,
        :update_page_member,
        :delete_page_member
      ]
    end

    def page_admin_rules
      page_master_rules + [
        :create_page_member_admin,
        :delete_page
      ]
    end
  end
end


text:
package bazel;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

/**
 * Main class for the Bazel Android "Hello, World" app.
 */
public class MainActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.v("Bazel", "Hello, Android");
    Log.v("Bazel", "Lib says: " + Lib.message());
    System.loadLibrary("hello_world");
    Log.v("Bazel", "JNI says: " + Jni.hello());
  }
}


text:
package wm.xmwei.core.database.table;

/**
 *
 *
 */
public class UserDomainTable {

    public static final String TABLE_NAME = "atusers_table";
    public static final String ID = "_id";
    public static final String USERID = "userid";
    public static final String ACCOUNTID = "accountid";
    public static final String JSONDATA = "json";
}


text:
	<title>William Roache's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

William Roache's panel show appearances

William Roache (born 1932-04-25[ref]) has appeared in 8 episodes between 2002-2013.  William Roache on IMDB. William Roache on Wikipedia.

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2013-03-07 / Celebrity Juice

2012-02-01 / Loose Women

2011-02-24 / Loose Women

2010-09-23 / Loose Women

2007-12-19 / Loose Women

2007-10-16 / Loose Women

2002-03-15 / Call My Bluff

2002-02-21 / Call My Bluff


text:
require 'minitest/spec'
require 'minitest/autorun'

require 'open_calais'


text:
==================
 Sidebar Examples
==================

This page demonstrates the use of a simple navigation sidebar.

Headings
========
This is a first level heading (``h1``).

Sub-Heading
-----------
This is a second level heading (``h2``).

Sub-Sub-Heading
~~~~~~~~~~~~~~~
This is a third level heading (``h3``).

Let's Rock Some Lorem!
======================

\.\.\. and now some Lorem text so that we can check scrolling

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
package org.shaolin.uimaster.page.cache;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.shaolin.bmdp.datamodel.common.ExpressionType;
import org.shaolin.bmdp.datamodel.common.ParamScopeType;
import org.shaolin.bmdp.datamodel.common.ParamType;
import org.shaolin.bmdp.datamodel.page.ComponentMappingType;
import org.shaolin.bmdp.datamodel.page.DirectComponentMappingType;
import org.shaolin.bmdp.datamodel.page.DynamicUIMappingType;
import org.shaolin.bmdp.datamodel.page.PageInType;
import org.shaolin.bmdp.datamodel.page.PageODMappingType;
import org.shaolin.bmdp.datamodel.page.PageOutType;
import org.shaolin.bmdp.datamodel.page.SimpleComponentMappingType;
import org.shaolin.bmdp.datamodel.page.UIPage;
import org.shaolin.bmdp.exceptions.I18NRuntimeException;
import org.shaolin.bmdp.i18n.ExceptionConstants;
import org.shaolin.bmdp.runtime.spi.IServerServiceManager;
import org.shaolin.javacc.context.DefaultEvaluationContext;
import org.shaolin.javacc.context.DefaultParsingContext;
import org.shaolin.javacc.exception.EvaluationException;
import org.shaolin.javacc.exception.ParsingException;
import org.shaolin.uimaster.page.AjaxContext;
import org.shaolin.uimaster.page.UserRequestContext;
import org.shaolin.uimaster.page.WebConfig;
import org.shaolin.uimaster.page.od.ODContext;
import org.shaolin.uimaster.page.od.ODContextHelper;
import org.shaolin.uimaster.page.od.ODPageContext;
import org.shaolin.uimaster.page.od.mappings.ComponentMapping;
import org.shaolin.uimaster.page.od.mappings.DirectComponentMapping;
import org.shaolin.uimaster.page.od.mappings.DynamicUIComponentMapping;
import org.shaolin.uimaster.page.od.mappings.SimpleComponentMapping;
import org.shaolin.uimaster.page.widgets.HTMLReferenceEntityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ODPageObject extends ODObject implements java.io.Serializable
{
    private static final long serialVersionUID = -1328112393440558301L;

    private static Logger logger = LoggerFactory.getLogger(ODPageObject.class);

    /**
     * whether is or not exist od mapping in current page entity.
     */
    private boolean isExistOdMapping = true;

    /**
     * Page In meta-info.
     */
    private PageInType pageInDescritpor;

	/**
     * Page out meta-infos.
     */
    private List<PageOutType> outs;

    /**
     * Declare parameters of OD.
     */
    private List<ParamType> localParamTypes;

    private final List<ComponentMapping> compMappings =
    		new ArrayList<ComponentMapping>();

    /**
     * key set.
     */
    private String[] localKeys;

    private Map pageOutKeys = new HashMap();

    /**
     * whether is or not the out node had been parsed.
     */
    private Map isParseOutNode = new HashMap();

    /**
     * last modify time for uipage component.
     */
    private long lastModifyTime;

	public ODPageObject(String name) throws ParsingException, ClassNotFoundException
    {
		super();

		this.name = name;

		load();
    }

	private void clear()
    {
		this.pageOutKeys.clear();
		this.isParseOutNode.clear();

		this.uiEntityName = "";
		this.isExistOdMapping = true;
		this.pageInDescritpor = null;
		this.outs = null;
		this.localParamTypes = null;
		this.localKeys = null;

		clearODObject();
    }

    private void load() throws ClassNotFoundException, ParsingException
    {
    	if(logger.isInfoEnabled())
    	{
    		logger.info("Load page od: "+name);
    	}

        UIPage pageDescriptor = IServerServiceManager.INSTANCE.getEntityManager().getEntity(name, UIPage.class);
        PageODMappingType odDescriptor = pageDescriptor.getODMapping();
    	this.uiEntityName = pageDescriptor.getEntityName();
		if(logger.isDebugEnabled())
    		logger.debug("The page entity name is: "+uiEntityName);
    	if(odDescriptor == null && pageDescriptor.getIn() == null && pageDescriptor.getOuts() == null )
    	{
    		this.isExistOdMapping = false;
    		logger.warn("This ui page dosen't have exsited od mapping!");
    	}

    	this.pageInDescritpor = pageDescriptor.getIn();
    	this.outs = pageDescriptor.getOuts();
    	this.localParamTypes = odDescriptor.getDataEntities();
    	this.localKeys = new String[localParamTypes.size()];
    	for (int i = 0; i < localParamTypes.size(); i++)
		{
    		localKeys[i] = localParamTypes.get(i).getName();
		}

    	if(logger.isDebugEnabled())
    	{
    		logger.debug("Initial parsing context.");
    		logger.debug("Local parsing context["+ODContext.LOCAL_TAG+"] variable list:");
    	}
        DefaultParsingContext localPContext = ODContextHelper.getParsingContext( localParamTypes );
        localPContext.setVariableClass(ODPageContext.UIPageEntity_MARK, HTMLReferenceEntityType.class);

        //DefaultParsingContext inPagePContext = ODContextHelper.getParsingContext( inParamTypes );
        DefaultParsingContext defaultPContext = new DefaultParsingContext();
        defaultPContext.setVariableClass("context", UserRequestContext.class);
        defaultPContext.setVariableClass("odContext", ODContext.class);
        defaultPContext.setVariableClass("page", AjaxContext.class);

        opContext.setDefaultParsingContext(defaultPContext);
        opContext.setParsingContextObject(ODContext.LOCAL_TAG, localPContext);
        opContext.setParsingContextObject(ODContext.GLOBAL_TAG, defaultPContext);
        opContext.setExternalParseContext(opContext);

        parseCompMapping(odDescriptor);

        parseInNode();

        parseOutNode();

        if(logger.isDebugEnabled())
        	logger.debug("---------->Parse od component end.");
    }

    private void parseCompMapping(PageODMappingType odDescriptor) throws ParsingException {
		List<ComponentMappingType> tempCompMappings = odDescriptor.getComponentMappings();
		for (ComponentMappingType compMapping: tempCompMappings)
    	{
			if(logger.isDebugEnabled()) {
	    		logger.debug("Parse component mapping: {}", compMapping.getName());
			}

			if (compMapping instanceof SimpleComponentMappingType) {
				SimpleComponentMapping simpleCM =
						new SimpleComponentMapping((SimpleComponentMappingType)compMapping);
				simpleCM.parse(opContext, this);
				compMappings.add(simpleCM);
			} else if (compMapping instanceof DynamicUIMappingType) {
				DynamicUIComponentMapping dynamicCM =
						new DynamicUIComponentMapping((DynamicUIMappingType)compMapping);
				dynamicCM.parse(opContext, this);
				compMappings.add(dynamicCM);
			} else {
				DirectComponentMapping directCM =
						new DirectComponentMapping((DirectComponentMappingType)compMapping);
				directCM.parse(opContext, this);
				compMappings.add(directCM);
			}
    	}
	}

	private void parseInNode() throws ParsingException
	{
		if(pageInDescritpor == null) {
			return;
		}

    	ExpressionType serverOperation = pageInDescritpor.getServerOperation();
    	if (serverOperation == null) {
    		ExpressionType dataToUIExpr = new ExpressionType();
    		dataToUIExpr.setExpressionString("{@odContext.executeAllMappings();}");
    		pageInDescritpor.setServerOperation(dataToUIExpr);
    	}
		if(logger.isDebugEnabled()) {
    		logger.debug("Parse op type: {}", pageInDescritpor.getServerOperation().getExpressionString());
		}
		pageInDescritpor.getServerOperation().parse(opContext);
	}

	private void parseOutNode() throws ParsingException
	{
		if(this.outs == null || this.outs.size() == 0) {
			return;
		}

		for (PageOutType out : this.outs) {
			ExpressionType serverOperation = out.getServerOperation();
			if (serverOperation == null || serverOperation.getExpressionString() == null) {
				ExpressionType dataToUIExpr = new ExpressionType();
				dataToUIExpr.setExpressionString("{@odContext.executeAllMappings();}");
				out.setServerOperation(dataToUIExpr);
			}
			if(logger.isDebugEnabled()) {
				logger.debug("Parse op type: {}", out.getServerOperation().getExpressionString());
			}
			out.getServerOperation().parse(opContext);
		}
	}

	public boolean isExistOdMapping() {
		return isExistOdMapping;
	}

	public String[] getLocalKeys()
	{
		return localKeys;
	}

	public boolean isOutVariable(String varName) {
		for (ParamType param : localParamTypes) {
			if (varName.equals(param.getName())
					&& (param.getScope() == ParamScopeType.IN_OUT
						|| param.getScope() == ParamScopeType.OUT )) {
				return true;
			}
		}
		return false;
	}

	public boolean isInVariable(String varName) {
		for (ParamType param : localParamTypes) {
			if (varName.equals(param.getName())
					&& (param.getScope() == ParamScopeType.IN_OUT
						|| param.getScope() == ParamScopeType.IN)) {
				return true;
			}
		}
		return false;
	}

    public List<ComponentMapping> getAllMappings(){
    	return this.compMappings;
    }

    public List<PageOutType> getOuts() {
		return outs;
	}

    public PageOutType getOut(String outName)
    {
    	for (PageOutType out: outs)
        {
			if(out.getName().equals(outName))
				return out;
        }
    	throw new I18NRuntimeException(ExceptionConstants.UIMASTER_ODMAPPER_059,new Object[]{outName});
	}

	public PageInType getPageInDescritpor() {
		return pageInDescritpor;
	}

	private void checkUpdate() throws ParsingException, ClassNotFoundException
    {
		if (!WebConfig.enableHotDeploy()) {
			return;
		}
		long currentTime = System.currentTimeMillis();
    	refresh();
    }

	synchronized private void refresh() throws ParsingException, ClassNotFoundException
    {
		//notice: if two threads access in here,
		//the first thread change lastCheckTime, the second thread will skip operation.
		File compFile = null;
        long modifyTime = compFile.lastModified();
        if ( modifyTime != lastModifyTime )
        {
            if ( logger.isInfoEnabled() )
                logger.info("the page od: " + name + " has been changed, start to reload it.");

            this.clear();
            this.load();
            lastModifyTime = modifyTime;
        }
    }

    public DefaultEvaluationContext getLocalEContext() throws EvaluationException, ParsingException {

    	if(logger.isDebugEnabled())
			logger.info("----->Initial 'page od'["+ODContext.LOCAL_TAG+"] variables.");

        Map localVariableValues = new HashMap();
		for (ParamType localVar: localParamTypes)
    	{
    		String key = localVar.getName();
    		Object value = ODContextHelper.evalVariableExpression(localVar);
    		localVariableValues.put(key, value);

    		if(logger.isDebugEnabled())
    		{
    			StringBuffer sb = new StringBuffer();
    			sb.append("Local variable name ");
    			sb.append(key);
    			if(localVar.getDefault() != null)
    			{
    				sb.append(", default value expression: ");
        			sb.append(localVar.getDefault().getExpressionString());
    			}
    			sb.append(", variable value: ");
    			sb.append(value);
    			logger.debug(sb.toString());
    		}
    	}
		return ODContextHelper.getEvalContext(localParamTypes, localVariableValues);
	}

}


text:
{{ define "main" }}

{{ humanize .Section | upper  }}

{{ .Title }}

    {{ with .Params.description }}

{{ . }}

    {{ end }}

{{ .Content }}

    {{ partial "menu-contextual.html" . }}

{{ end }}


text:
require 'test_helper'

class StaticPageTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
using Runtime.Deployments;
using Machine.Specifications;
using Moq;

namespace Runtime.Specifications.Deployment.for_DeploymentOrchestrator.given
{
    public class all_dependencies
    {
        protected static Mock<IDeployers> deployers_mock;
        protected static Mock<IDeploymentStepOrchestrator> deployment_step_orchestrator_mock;

        Establish context = () =>
        {
            deployers_mock = new Mock<IDeployers>();
            deployment_step_orchestrator_mock = new Mock<IDeploymentStepOrchestrator>();
        };
    }
}


text:
@class VFParams, VFSession;

@interface VFRequestCenter : NSObject

+ (nullable instancetype)new NS_UNAVAILABLE;
- (nullable instancetype)init NS_UNAVAILABLE;

- (nullable instancetype)initWithPublicKey:(nonnull NSString *)publicKey
                                privateKey:(nonnull NSString *)privateKey;

- (nullable instancetype)initWithSession:(nonnull VFSession *)session NS_DESIGNATED_INITIALIZER;

- (void)verifyWithParams:(nonnull VFParams *)params
              completion:(nonnull void(^)(NSString *_Nullable requestId, NSError *_Nullable error))callback;

- (void)confirmWithCode:(nonnull NSString *)code requestId:(nonnull NSString *)requestId
             completion:(nonnull void(^)(VFParams *_Nullable response, NSError *_Nullable error))callback;

@end


text:
namespace co {

struct ThreadLocalInfo;

// 协程执行器
//   管理一批协程的共享栈和调度, 非线程安全.
class Processer
    : public TSQueueHook
{
private:
    typedef TSQueue<Task> TaskList;

    Task* current_task_ = nullptr;
    TaskList runnable_list_;
    uint32_t id_;
    static std::atomic<uint32_t> s_id_;

public:
    explicit Processer();

    void AddTaskRunnable(Task *tk);

    uint32_t Run(uint32_t &done_count);

    void CoYield();

    uint32_t GetTaskCount();

    Task* GetCurrentTask();

    std::size_t StealHalf(Processer & other);
};

} //namespace co


text:
// ***********************************************************************
// Copyright (c) 2017 Dominik Lachance
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System.Threading;
using TechTalk.SpecFlow;

namespace YellowJacket.Core.Test.Data.Steps
{
    [Binding]
    public class RegisterSteps
    {
        [Then(@"I see register success message")]
        public void ThenISeeRegisterSuccessMessage()
        {
            Thread.Sleep(1);
        }
    }
}


text:
require 'action_controller'
require 'action_controller/test_case'
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'action_controller_extension/test_case'
require 'action_controller_extension/accessible_via_protocol'
require 'action_controller_extension/accessible_via_format'
require 'action_controller_extension/accessible_via_user'
require 'action_controller_extension/routing'


text:
<?php

/**
 * Get result data
 *
 * @phpstub
 *
 * @param resource $result
 * @param int $row
 * @param mixed $field
 *
 * @return string The contents of one cell from a MySQL result set on success, or
 *                false on failure.
 */
function mysql_result($result, $row, $field = '0')
{
}


text:
package org.openmhealth.dsu.factory;

import org.openmhealth.dsu.domain.DataPointBuilder;
import org.openmhealth.dsu.domain.DataPointSearchCriteriaBuilder;
import org.openmhealth.schema.domain.omh.CaloriesBurned;
import org.openmhealth.schema.domain.omh.KcalUnitValue;
import org.openmhealth.schema.domain.omh.SchemaVersion;
import org.openmhealth.schema.domain.omh.TimeInterval;
import org.springframework.stereotype.Service;

import java.time.OffsetDateTime;

import static java.time.ZoneOffset.UTC;
import static org.openmhealth.schema.domain.omh.KcalUnit.KILOCALORIE;

/**
 * A factory that builds objects to support data point tests.
 *
 * @author Emerson Farrugia
 */
@Service
public class DataPointFactory {

    public static final String TEST_USER_ID = "test";
    public static final String TEST_SCHEMA_NAMESPACE = "test";
    public static final String TEST_SCHEMA_NAME = "test";
    public static final SchemaVersion TEST_SCHEMA_VERSION = new SchemaVersion(1, 1);

    public static DataPointBuilder newDataPointBuilder() {

        return new DataPointBuilder()
                .setUserId(TEST_USER_ID)
                .setSchemaNamespace(TEST_SCHEMA_NAMESPACE)
                .setSchemaName(TEST_SCHEMA_NAME)
                .setSchemaVersion(TEST_SCHEMA_VERSION)
                .setBody(newKcalBurnedBody());
    }

    public static DataPointSearchCriteriaBuilder newSearchCriteriaBuilder() {

        return new DataPointSearchCriteriaBuilder()
                .setUserId(TEST_USER_ID)
                .setSchemaNamespace(TEST_SCHEMA_NAMESPACE)
                .setSchemaName(TEST_SCHEMA_NAME)
                .setSchemaVersion(TEST_SCHEMA_VERSION);
    }

    public static CaloriesBurned newKcalBurnedBody() {

        TimeInterval effectiveTimeInterval = TimeInterval.ofStartDateTimeAndEndDateTime(
                OffsetDateTime.of(2013, 2, 5, 6, 25, 0, 0, UTC),
                OffsetDateTime.of(2013, 2, 5, 7, 25, 0, 0, UTC)
        );

        return new CaloriesBurned.Builder(new KcalUnitValue(KILOCALORIE, 160))
                .setActivityName("walking")
                .setEffectiveTimeFrame(effectiveTimeInterval)
                .build();
    }
}


text:
p = gcp();
% To request multiple evaluations, use a loop.
for idx = 1:10
  f(idx) = parfeval(p,@magic,1,idx); % Square size determined by idx
end
% Collect the results as they become available.
magicResults = cell(1,10);
for idx = 1:10
  % fetchNext blocks until next results are available.
  [completedIdx,value] = fetchNext(f);
  magicResults{completedIdx} = value;
  fprintf('Got result with index: %d.\n', completedIdx);
end