text:
package org.motechproject.nms.kilkari.utils;

import org.motechproject.nms.csv.exception.CsvImportDataException;
import org.motechproject.nms.csv.utils.ConstraintViolationUtils;
import org.motechproject.nms.csv.utils.GetLong;
import org.motechproject.nms.csv.utils.GetString;
import org.motechproject.nms.kilkari.domain.MctsBeneficiary;
import org.motechproject.nms.region.domain.District;
import org.motechproject.nms.region.domain.HealthBlock;
import org.motechproject.nms.region.domain.HealthFacility;
import org.motechproject.nms.region.domain.HealthSubFacility;
import org.motechproject.nms.region.domain.State;
import org.motechproject.nms.region.domain.Taluka;
import org.motechproject.nms.region.domain.Village;
import org.motechproject.nms.region.exception.InvalidLocationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.ift.CellProcessor;

import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

public final class MctsBeneficiaryUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(MctsBeneficiaryUtils.class);

    private MctsBeneficiaryUtils() {
    }

    public static void getBeneficiaryLocationMapping(Map<String, CellProcessor> mapping) {
        mapping.put(KilkariConstants.STATE_ID, new Optional(new GetLong()));

        mapping.put(KilkariConstants.DISTRICT_ID, new Optional(new GetLong()));
        mapping.put(KilkariConstants.DISTRICT_NAME, new Optional(new GetString()));

        mapping.put(KilkariConstants.TALUKA_ID, new Optional(new GetString()));
        mapping.put(KilkariConstants.TALUKA_NAME, new Optional(new GetString()));

        mapping.put(KilkariConstants.CENSUS_VILLAGE_ID, new Optional(new GetLong()));
        mapping.put(KilkariConstants.NON_CENSUS_VILLAGE_ID, new Optional(new GetLong()));
        mapping.put(KilkariConstants.VILLAGE_NAME, new Optional(new GetString()));

        mapping.put(KilkariConstants.PHC_ID, new Optional(new GetLong()));
        mapping.put(KilkariConstants.PHC_NAME, new Optional(new GetString()));

        mapping.put(KilkariConstants.HEALTH_BLOCK_ID, new Optional(new GetLong()));
        mapping.put(KilkariConstants.HEALTH_BLOCK_NAME, new Optional(new GetString()));

        mapping.put(KilkariConstants.SUB_CENTRE_ID, new Optional(new GetLong()));
        mapping.put(KilkariConstants.SUB_CENTRE_NAME, new Optional(new GetString()));
    }

    public static void setLocationFields(Map<String, Object> locations, MctsBeneficiary beneficiary) throws InvalidLocationException {

        LOGGER.info("locations {}", locations);
        if (locations.get(KilkariConstants.STATE_ID) == null && locations.get(KilkariConstants.DISTRICT_ID) == null) {
            throw new InvalidLocationException("Missing mandatory state and district fields");
        }

        if (locations.get(KilkariConstants.STATE_ID) == null) {
            throw new InvalidLocationException("Missing mandatory state field");
        }

        if (locations.get(KilkariConstants.DISTRICT_ID) == null) {
            throw new InvalidLocationException("Missing mandatory district field");
        }
        beneficiary.setState((State) locations.get(KilkariConstants.STATE_ID));
        beneficiary.setDistrict((District) locations.get(KilkariConstants.DISTRICT_ID));
        beneficiary.setTaluka((Taluka) locations.get(KilkariConstants.TALUKA_ID));
        beneficiary.setHealthBlock((HealthBlock) locations.get(KilkariConstants.HEALTH_BLOCK_ID));
        beneficiary.setHealthFacility((HealthFacility) locations.get(KilkariConstants.PHC_ID));
        beneficiary.setHealthSubFacility((HealthSubFacility) locations.get(KilkariConstants.SUB_CENTRE_ID));
        beneficiary.setVillage((Village) locations.get(KilkariConstants.CENSUS_VILLAGE_ID + KilkariConstants.NON_CENSUS_VILLAGE_ID));
    }

    public static String createErrorMessage(String message, int rowNumber) {
        return String.format("CSV instance error [row: %d]: %s", rowNumber, message);
    }

    public static String createErrorMessage(Set<ConstraintViolation<?>> violations, int rowNumber) {
        return String.format("CSV instance error [row: %d]: validation failed for instance of type %s, violations: %s",
                rowNumber, MctsBeneficiary.class.getName(), ConstraintViolationUtils.toString(violations));
    }

    public static void verify(boolean condition, String message, String... args) {
        if (!condition) {
            throw new CsvImportDataException(String.format(message, args));
        }
    }
    public static void idCleanup(ArrayList<String > listOfIds, Map<String, Object> record){
        for(String id :listOfIds){
            if(record.get(id)!=null){
                String idValue=(String)record.get(id);
                idValue=idValue.replaceAll(KilkariConstants.SPECIAL_CHAR_STRING,"");
                record.replace(id,idValue);
            }
        }
    }
}


text:
@interface ChatRedEnvelopeCell : GJGCChatFriendBaseCell

@end

redpajama_set_name: RedPajamaGithub


text:
package com.iluwatar.model.view.presenter;

import org.junit.Test;

/**
 *
 * Application test
 *
 */
public class AppTest {

  @Test
  public void test() {
    String[] args = {};
    App.main(args);
  }

}


text:
import org.shipkit.demo.UserService;

public class UserServiceImpl implements UserService {
    @Override
    public void persist(String username) {
        System.out.println("persisted = " + username);
    }

    @Override
    public String findByName(String name) {
        return name;
    }
}


text:
package com.doplgangr.secrecy.filesystem.encryption;

import com.doplgangr.secrecy.Config;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.crypto.Cipher;

/**
 * The SecrecyCipherInputStream is a modified version of Bouncy Castles
 * CipherInputStream.
 */
public class SecrecyCipherInputStream extends FilterInputStream {
    private final Cipher cipher;
    private final byte[] buf;
    private final byte[] inBuf;
    private int bufOff;
    private int maxBuf;
    private boolean finalized;

    public SecrecyCipherInputStream(InputStream is, Cipher cipher) {
        super(is);
        this.cipher = cipher;

        buf = new byte[cipher.getOutputSize(Config.BUFFER_SIZE)];
        inBuf = new byte[Config.BUFFER_SIZE];
    }

    private int nextChunk() throws IOException {
        int available = super.available();

        // must always try to read 1 byte!
        // some buggy InputStreams return < 0!
        if (available <= 0) {
            available = 1;
        }

        if (available > inBuf.length) {
            available = super.read(inBuf, 0, inBuf.length);
        } else {
            available = super.read(inBuf, 0, available);
        }

        if (available < 0) {
            if (finalized) {
                return -1;
            }

            try {
                maxBuf = cipher.doFinal(buf, 0);
            } catch (Exception e) {
                throw new IOException("error processing stream: " + e.toString());
            }

            bufOff = 0;
            finalized = true;

            if (bufOff == maxBuf) {
                return -1;
            }
        } else {
            bufOff = 0;

            try {
                maxBuf = cipher.update(inBuf, 0, available, buf, 0);
            } catch (Exception e) {
                throw new IOException("error processing stream: " + e.toString());
            }

            // not enough bytes read for first block...
            if (maxBuf == 0) {
                return nextChunk();
            }
        }
        return maxBuf;
    }

    @Override
    public int read() throws IOException {
        if (bufOff == maxBuf) {
            if (nextChunk() < 0) {
                return -1;
            }
        }
        return buf[bufOff++] & 0xff;
    }

    @Override
    public int read(byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (bufOff == maxBuf) {
            if (nextChunk() < 0) {
                return -1;
            }
        }
        int available = maxBuf - bufOff;

        if (len > available) {
            System.arraycopy(buf, bufOff, b, off, available);
            bufOff = maxBuf;

            return available;
        } else {
            System.arraycopy(buf, bufOff, b, off, len);
            bufOff += len;

            return len;
        }
    }

    @Override
    public long skip(long n) throws IOException {
        if (n <= 0) {
            return 0;
        }

        int available = maxBuf - bufOff;

        if (n > available) {
            bufOff = maxBuf;
            return available;
        } else {
            bufOff += (int) n;
            return (int) n;
        }
    }

    @Override
    public int available() throws IOException {
        return maxBuf - bufOff;
    }

    @Override
    public boolean markSupported() {
        return false;
    }
}


text:
extern void idp_leds_event(led_event_t evt);
extern void lubbock_leds_event(led_event_t evt);
extern void mainstone_leds_event(led_event_t evt);


text:
class EggData;
class EggGroupNode;
class LoaderOptions;

////////////////////////////////////////////////////////////////////
//       Class : SomethingToEggConverter
// Description : This is a base class for a family of converter
//               classes that manage a conversion from some file type
//               to egg format.
//
//               Classes of this type can be used to implement xxx2egg
//               converter programs, as well as LoaderFileTypeXXX
//               run-time loaders.
////////////////////////////////////////////////////////////////////
class SomethingToEggConverter {
public:
  SomethingToEggConverter();
  SomethingToEggConverter(const SomethingToEggConverter &copy);
  virtual ~SomethingToEggConverter();

  virtual SomethingToEggConverter *make_copy()=0;

  INLINE void clear_error();
  INLINE bool had_error() const;

  INLINE void set_path_replace(PathReplace *path_replace);
  INLINE PathReplace *get_path_replace();
  INLINE const PathReplace *get_path_replace() const;

  // These methods dealing with animation and frame rate are only
  // relevant to converter types that understand animation.
  INLINE void set_animation_convert(AnimationConvert animation_convert);
  INLINE AnimationConvert get_animation_convert() const;

  INLINE void set_character_name(const string &character_name);
  INLINE const string &get_character_name() const;

  INLINE void set_start_frame(double start_frame);
  INLINE bool has_start_frame() const;
  INLINE double get_start_frame() const;
  INLINE void clear_start_frame();

  INLINE void set_end_frame(double end_frame);
  INLINE bool has_end_frame() const;
  INLINE double get_end_frame() const;
  INLINE void clear_end_frame();

  INLINE void set_frame_inc(double frame_inc);
  INLINE bool has_frame_inc() const;
  INLINE double get_frame_inc() const;
  INLINE void clear_frame_inc();

  INLINE void set_neutral_frame(double neutral_frame);
  INLINE bool has_neutral_frame() const;
  INLINE double get_neutral_frame() const;
  INLINE void clear_neutral_frame();

  INLINE void set_input_frame_rate(double input_frame_rate);
  INLINE bool has_input_frame_rate() const;
  INLINE double get_input_frame_rate() const;
  INLINE void clear_input_frame_rate();

  INLINE void set_output_frame_rate(double output_frame_rate);
  INLINE bool has_output_frame_rate() const;
  INLINE double get_output_frame_rate() const;
  INLINE void clear_output_frame_rate();

  INLINE static double get_default_frame_rate();

  INLINE void set_merge_externals(bool merge_externals);
  INLINE bool get_merge_externals() const;

  void set_egg_data(EggData *egg_data);
  INLINE void clear_egg_data();
  INLINE EggData *get_egg_data();

  virtual string get_name() const=0;
  virtual string get_extension() const=0;
  virtual string get_additional_extensions() const;
  virtual bool supports_compressed() const;
  virtual bool supports_convert_to_node(const LoaderOptions &options) const;

  virtual bool convert_file(const Filename &filename)=0;
  virtual PT(PandaNode) convert_to_node(const LoaderOptions &options, const Filename &filename);
  virtual DistanceUnit get_input_units();

  bool handle_external_reference(EggGroupNode *egg_parent,
                                 const Filename &ref_filename);

  INLINE Filename convert_model_path(const Filename &orig_filename);

  // Set this true to treat errors as warnings and generate output
  // anyway.
  bool _allow_errors;

protected:
  PT(PathReplace) _path_replace;

  AnimationConvert _animation_convert;
  string _character_name;
  double _start_frame;
  double _end_frame;
  double _frame_inc;
  double _neutral_frame;
  double _input_frame_rate;   // frames per second
  double _output_frame_rate;  // frames per second
  enum ControlFlags {
    CF_start_frame        = 0x0001,
    CF_end_frame          = 0x0002,
    CF_frame_inc          = 0x0004,
    CF_neutral_frame      = 0x0008,
    CF_input_frame_rate   = 0x0010,
    CF_output_frame_rate  = 0x0020,
  };
  int _control_flags;

  bool _merge_externals;

  PT(EggData) _egg_data;

  bool _error;
};

#include "somethingToEggConverter.I"

#endif


text:
package dimitrovskif.smartcache;

import android.content.Context;
import android.util.Log;
import android.util.LruCache;

import com.google.common.hash.Hashing;
import com.jakewharton.disklrucache.DiskLruCache;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;

import okhttp3.Request;
import retrofit2.Response;

/**
 * A basic caching system that stores responses in RAM & disk
 * It uses {@link DiskLruCache} and {@link LruCache} to do the former.
 */
public class BasicCaching implements CachingSystem {
    private DiskLruCache diskCache;
    private LruCache<String, Object> memoryCache;

    public BasicCaching(File diskDirectory, long maxDiskSize, int memoryEntries){
        try{
            diskCache = DiskLruCache.open(diskDirectory, 1, 1, maxDiskSize);
        }catch(IOException exc){
            Log.e("SmartCall", "", exc);
            diskCache = null;
        }

        memoryCache = new LruCache<>(memoryEntries);
    }

    private static final long REASONABLE_DISK_SIZE = 1024 * 1024; // 1 MB
    private static final int REASONABLE_MEM_ENTRIES = 50; // 50 entries

    /***
     * Constructs a BasicCaching system using settings that should work for everyone
     * @param context
     * @return
     */
    public static BasicCaching fromCtx(Context context){
        return new BasicCaching(
                new File(context.getCacheDir(), "retrofit_smartcache"),
                REASONABLE_DISK_SIZE,
                REASONABLE_MEM_ENTRIES);
    }

    @Override
    public <T> void addInCache(Response<T> response, byte[] rawResponse) {
        String cacheKey = urlToKey(response.raw().request().url().url());
        memoryCache.put(cacheKey, rawResponse);

        try {
            DiskLruCache.Editor editor = diskCache.edit(urlToKey(response.raw().request().url().url()));
            editor.set(0, new String(rawResponse, Charset.defaultCharset()));
            editor.commit();
        }catch(IOException exc){
            Log.e("SmartCall", "", exc);
        }
    }

    @Override
    public <T> byte[] getFromCache(Request request) {
        String cacheKey = urlToKey(request.url().url());
        byte[] memoryResponse = (byte[]) memoryCache.get(cacheKey);
        if(memoryResponse != null){
            Log.d("SmartCall", "Memory hit!");
            return memoryResponse;
        }

        try {
            DiskLruCache.Snapshot cacheSnapshot = diskCache.get(cacheKey);
            if(cacheSnapshot != null){
                Log.d("SmartCall", "Disk hit!");
                return cacheSnapshot.getString(0).getBytes();
            }else{
                return null;
            }
        }catch(IOException exc){
            return null;
        }
    }

    private String urlToKey(URL url){
        return Hashing.sha1().hashString(url.toString(), Charset.defaultCharset()).toString();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Vuforiademo2</string>
</resources>


text:
var browserWindows = require('sdk/windows').browserWindows;
var clearTimeout = require('sdk/timers').clearTimeout;
var setTimeout = require('sdk/timers').setTimeout;
var simplePrefs = require('sdk/simple-prefs');
var viewFor = require('sdk/view/core').viewFor;

var SearchScrub = {

    originalSearchCommand: undefined,

    init: function(browserWindow, clearSearch) {
        var _seconds = simplePrefs.prefs.seconds;
        if (isNaN(_seconds)) {
            _seconds = 0;
        }
        if (browserWindow) {
            var _chromeWindow = viewFor(browserWindow);
            if (_chromeWindow) {
                var _searchbar = _chromeWindow.document.getElementById('searchbar');
                if (_searchbar && _searchbar.handleSearchCommand) {
                    this.originalSearchCommand = _searchbar.handleSearchCommand;
                    // when installing clear the searchbar on existing windows
                    if (clearSearch) {
                        _searchbar.value = '';
                    }
                    _searchbar.handleSearchCommand = function() {
                        var _results = SearchScrub.originalSearchCommand.apply(this, arguments);
                        // Clear out an existing timeout
                        if (browserWindow._searchTimeoutId) {
                            clearTimeout(browserWindow._searchTimeoutId);
                            delete browserWindow._searchTimeoutId;
                        }
                        browserWindow._searchTimeoutId = setTimeout(function() {_searchbar.value = ''; delete browserWindow._searchTimeoutId;}, _seconds * 1000);
                        return _results;
                    };
                }
            }
        }
    },

    remove: function(browserWindow, deleteTimeouts) {
        if (browserWindow) {
            var _chromeWindow = viewFor(browserWindow);
            if (_chromeWindow) {
                var _searchbar = _chromeWindow.document.getElementById('searchbar');
                if (_searchbar && _searchbar.handleSearchCommand) {
                    _searchbar.handleSearchCommand = this.originalSearchCommand;
                }
            }
            // Clear out any existing timeouts
            if (deleteTimeouts && browserWindow._searchTimeoutId) {
                clearTimeout(browserWindow._searchTimeoutId);
                delete browserWindow._searchTimeoutId;
            }
        }
    }
};

simplePrefs.on('', function() {
    // Remove and then re-init on exsting windows
    for(var x = 0; x < browserWindows.length; x++) {
        SearchScrub.remove(browserWindows[x]);
        SearchScrub.init(browserWindows[x]);
    }
});

exports.main = function() {
    // Init on any new window
    browserWindows.on('open', SearchScrub.init);

    // Init on exsiting windows
    for(var x = 0; x < browserWindows.length; x++) {
        SearchScrub.init(browserWindows[x], true);
    }
};

exports.onUnload = function() {
    // Remove on exsiting windows
    for(var x = 0; x < browserWindows.length; x++) {
        SearchScrub.remove(browserWindows[x], true);
    }
};


text:
using System;
using System.Collections.Generic;
using Mmarab.CqsExample.DomainModels;
using Mmarab.CqsExample.DomainModels.Exceptions;
using System.Linq;
using System.Threading.Tasks;

namespace Mmarab.CqsExample.Infrastructure
{
    public class EventStore : IEventStore
    {
        private List<Event> _inMemoryEventStore = new List<Event>();

        private readonly Dictionary<Guid, List<EventDescriptor>> _current = new Dictionary<Guid, List<EventDescriptor>>();
        private struct EventDescriptor
        {

            public readonly Event EventData;
            public readonly Guid Id;
            public readonly int Version;

            public EventDescriptor(Guid id, Event eventData, int version)
            {
                EventData = eventData;
                Version = version;
                Id = id;
            }
        }

        public async Task<List<Event>> GetEventsForAggregate(Guid aggregateId)
        {
            if (!_current.TryGetValue(aggregateId, out List<EventDescriptor> eventDescriptors))
            {
                throw new AggregateNotFoundException();
            }

            return await Task.Run( () =>  eventDescriptors.Select(desc => desc.EventData).ToList());
        }

        public async Task SaveEvents(Guid aggregateId, IEnumerable<Event> events, int? expectedVersion)
        {
            if (!_current.TryGetValue(aggregateId, out List<EventDescriptor> eventDescriptors))
            {
                eventDescriptors = new List<EventDescriptor>();
                _current.Add(aggregateId, eventDescriptors);
            }
            else if (expectedVersion != null && eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion)
            {
                throw new ConcurrencyException();
            }

            var i = eventDescriptors.Count == 0 ? -1 : eventDescriptors[eventDescriptors.Count - 1].Version;
            foreach (var @event in events)
            {
                i++;
                @event.Version = i;
                eventDescriptors.Add(new EventDescriptor(aggregateId, @event, i));
                _inMemoryEventStore.Add(@event);
            }
        }
    }
}


text:
using namespace std;

BufferFrame::BufferFrame(uint64_t pageNo, void* data)
  : pageNo(pageNo),
    LSN(0),
    state(CLEAN) {
    // Ensures the data-block PAGESIZE large
    this->data = realloc(data, PAGESIZE);

    if (pthread_rwlock_init(&this->latch, NULL) != 0) {
        perror("Could not initialize latch.");
        perror(nullptr);
        throw "Could not initialize latch.";
    }
}

BufferFrame::BufferFrame(uint64_t pageNo)
  : pageNo(pageNo),
    LSN(0),
    state(NEW) {
    this->data = malloc(PAGESIZE);
    if (pthread_rwlock_init(&this->latch, NULL) != 0) {
        perror("Could not initialize latch.");
        throw "Could not initialize latch.";
    }
}

void BufferFrame::lock(bool exclusive) {
    if (exclusive) {
        if (pthread_rwlock_wrlock(&this->latch) != 0) {
            perror("ERROR");
            perror("Failed to lock exclusive.");
            throw "Failed to lock.";
        }
    } else {
        if (pthread_rwlock_rdlock(&this->latch) != 0) {
            perror("ERROR");
            perror("Failed to lock non exclusive.");
            throw "Failed to lock.";
        }
    }
}

int BufferFrame::tryLock(bool exclusive) {
    return exclusive  ? pthread_rwlock_trywrlock(&this->latch) :
                        pthread_rwlock_tryrdlock(&this->latch);
}

void BufferFrame::unlock() {
    if (pthread_rwlock_unlock(&this->latch) != 0) {
        perror("Failed to unlock.");
        throw "Failed to unlock.";
    }
}

uint64_t BufferFrame::getPageNo() {
    return this->pageNo;
}

int BufferFrame::getLSN() {
    return this->LSN;
}

void BufferFrame::setLSN(int LSN) {
    if (LSN <= this->LSN) {
        perror("Can not lower the LSN.");
        throw "Can not lower the LSN.";
    }
    this->LSN = LSN;
}

FrameStatus BufferFrame::getState() {
    return this->state;
}

void BufferFrame::setState(FrameStatus state) {
    this->state = state;
}

void *BufferFrame::getData() {
    return this->data;
}

BufferFrame::~BufferFrame() {
    if (pthread_rwlock_trywrlock(&this->latch) != 0) {
        perror("Tying to delete locked BufferFrame.");
        throw "Trying to delete locked BufferFrame.";
    }
    free(this->data);
}


text: Bootstrap Responsive website built for a school assignment.


text:
Returns `true` or `false` depending on if the `fd` is associated with a
terminal.


text:
using System;
using System.Collections.Generic;
using System.Web;

namespace ServiceStack.MiniProfiler.Storage
{
    /// <summary>
    /// Understands how to store a <see cref="Profiler"/> to the <see cref="System.Web.HttpRuntime.Cache"/> with absolute expiration.
    /// </summary>
    public class HttpRuntimeCacheStorage : IStorage
    {
        /// <summary>
        /// The string that prefixes all keys that MiniProfilers are saved under, e.g.
        /// "mini-profiler-ecfb0050-7ce8-4bf1-bf82-2cb38e90e31e".
        /// </summary>
        public const string CacheKeyPrefix = "mini-profiler-";

        /// <summary>
        /// How long to cache each <see cref="Profiler"/> for (i.e. the absolute expiration parameter of
        /// <see cref="System.Web.Caching.Cache.Insert(string, object, System.Web.Caching.CacheDependency, System.DateTime, System.TimeSpan, System.Web.Caching.CacheItemUpdateCallback)"/>)
        /// </summary>
        public TimeSpan CacheDuration { get; set; }

        /// <summary>
        /// Returns a new HttpRuntimeCacheStorage class that will cache MiniProfilers for the specified duration.
        /// </summary>
        public HttpRuntimeCacheStorage(TimeSpan cacheDuration)
        {
            CacheDuration = cacheDuration;
        }

        /// <summary>
        /// Saves <paramref name="profiler"/> to the HttpRuntime.Cache under a key concated with <see cref="CacheKeyPrefix"/>
        /// and the parameter's <see cref="Profiler.Id"/>.
        /// </summary>
        public void Save(Profiler profiler)
        {
            InsertIntoCache(GetCacheKey(profiler.Id), profiler);

            // so we can easily follow POST -> redirects, store ids for this user
            var ids = GetPerUserUnviewedIds(profiler);
            lock (ids)
            {
                if (!ids.Contains(profiler.Id))
                {
                    ids.Add(profiler.Id);
                }
            }
        }

        /// <summary>
        /// Returns the saved <see cref="Profiler"/> identified by <paramref name="id"/>. Also marks the resulting
        /// profiler <see cref="Profiler.HasUserViewed"/> to true.
        /// </summary>
        public Profiler Load(Guid id)
        {
            var result = HttpRuntime.Cache[GetCacheKey(id)] as Profiler;

            if (result != null)
            {
                var ids = GetPerUserUnviewedIds(result);

                lock (ids)
                {
                    ids.Remove(result.Id);
                    result.HasUserViewed = true;
                }
            }

            return result;
        }

        /// <summary>
        /// Returns a list of <see cref="Profiler.Id"/>s that haven't been seen by <paramref name="user"/>.
        /// </summary>
        /// <param name="user">User identified by the current <see cref="Profiler.Settings.UserProvider"/>.</param>
        public List<Guid> GetUnviewedIds(string user)
        {
            var ids = GetPerUserUnviewedIds(user);
            lock (ids)
            {
                return new List<Guid>(ids);
            }
        }

        private void InsertIntoCache(string key, object value)
        {
            // use insert instead of add; add fails if the item already exists
            HttpRuntime.Cache.Insert(
                key: key,
                value: value,
                dependencies: null,
                absoluteExpiration: DateTime.Now.Add(CacheDuration), // servers will cache based on local now
                slidingExpiration: System.Web.Caching.Cache.NoSlidingExpiration,
                priority: System.Web.Caching.CacheItemPriority.Low,
                onRemoveCallback: null);
        }

        private string GetCacheKey(Guid id)
        {
            return CacheKeyPrefix + id;
        }

        private string GetPerUserUnviewedCacheKey(string user)
        {
            return CacheKeyPrefix + "unviewed-for-user-" + user;
        }

        private List<Guid> GetPerUserUnviewedIds(Profiler profiler)
        {
            return GetPerUserUnviewedIds(profiler.User);
        }

        private List<Guid> GetPerUserUnviewedIds(string user)
        {
            var key = GetPerUserUnviewedCacheKey(user);
            var result = HttpRuntime.Cache[key] as List<Guid>;

            if (result == null)
            {
                lock (AddPerUserUnviewedIdsLock)
                {
                    // check again, as we could have been waiting
                    result = HttpRuntime.Cache[key] as List<Guid>;
                    if (result == null)
                    {
                        result = new List<Guid>();
                        InsertIntoCache(key, result);
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Syncs access to runtime cache when adding a new list of ids for a user.
        /// </summary>
        private static readonly object AddPerUserUnviewedIdsLock = new object();
    }
}


text:
package sh.komet.gui.provider.classification;

import sh.isaac.api.component.concept.ConceptSpecification;

import java.util.Optional;

public class StringWithOptionalConceptSpec {
    final String label;
    final ConceptSpecification conceptSpecification;

    public StringWithOptionalConceptSpec(String label, ConceptSpecification conceptSpecification) {
        this.label = label;
        this.conceptSpecification = conceptSpecification;
    }
    public StringWithOptionalConceptSpec(String label) {
        this.label = label;
        this.conceptSpecification = null;
    }

    public String getLabel() {
        return label;
    }

    public Optional<ConceptSpecification> getOptionalConceptSpecification() {
        return Optional.ofNullable(conceptSpecification);
    }

    @Override
    public String toString() {
        return label;
    }
}


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package ghidra.framework.plugintool.util;

import java.util.Map;

import generic.test.TestUtils;
import ghidra.framework.plugintool.Plugin;

/**
 * A builder to allow test writers to easily create a {@link StubPluginDescription}.
 */
public class StubPluginDescriptionBuilder {

	private Class<? extends Plugin> clazz;
	private PluginPackage pluginPackage;
	private PluginStatus status = PluginStatus.RELEASED;
	private String category = "Category";
	private String shortDescription = "Short description";

	public StubPluginDescriptionBuilder(Class<? extends Plugin> clazz,
			PluginPackage pluginPackage) {
		this.clazz = clazz;
		this.pluginPackage = pluginPackage;
	}

	public StubPluginDescriptionBuilder status(PluginStatus pluginStatus) {
		this.status = pluginStatus;
		return this;
	}

	public StubPluginDescriptionBuilder category(String pluginCategory) {
		this.category = pluginCategory;
		return this;
	}

	public StubPluginDescriptionBuilder shortDescription(String description) {
		this.shortDescription = description;
		return this;
	}

	public StubPluginDescription build() {

		// as a convenience for test writers, ensure that the given plugin package is registered
		// with the system
		@SuppressWarnings("unchecked")
		Map<String, PluginPackage> map = (Map<String, PluginPackage>) TestUtils
				.getInstanceField("packageMap", PluginPackage.class);
		map.put(pluginPackage.getName().toLowerCase(), pluginPackage);

		if (shortDescription == null) {
			shortDescription = "Short description for " + clazz.getSimpleName();
		}

		return new StubPluginDescription(clazz, pluginPackage, category, shortDescription, status);
	}
}


text:
<?xml version='1.0' encoding='utf-8'?>
<resources>
    <string name="app_name">mrmrs</string>
    <string name="launcher_name">@string/app_name</string>
    <string name="activity_name">@string/launcher_name</string>
    <string name="action_settings">action_settings</string>
    <string name="hello_world">hello world</string>
    <string name="categories">Categories</string>
    <string name="webview">Webview</string>
    <string name="next">Next</string>
    <string name="back">Cancel</string>
    <string name="shoplist">ShopList</string>
    <string name="optional">optionalInfo</string>
    <string name="shopsimilar">shopSimilar</string>
    <string name="product_title">Product Title</string>
    <string name="shop">Shop</string>

</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/zipcode_preview_header_card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="3dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical"
    card_view:cardBackgroundColor="@android:color/darker_gray">

    <TextView
        android:id="@+id/zipcode_preview_header_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="7dp"
        android:text="@string/zipcode_list_title"
        android:textAlignment="center"
        android:textSize="30dp" />

</android.support.v7.widget.CardView>


text:
using UnityEngine;
using System.Collections;

public class BulletScript : MonoBehaviour {
	private ShootingTower shootingtower;
	private GameObject enemyguy;

	// Use this for initialization
	void Start () {

		ShootingTower shootingtower = (ShootingTower)this.GetComponent(typeof(ShootingTower));
		enemyguy = GameObject.Find("Enemy");

	}
	// Update is called once per frame
	void Update () {
		float newXPos = (transform.position.x-transform.position.x );
		float newYPos = (transform.position.y-transform.position.y );
		float newZPos = (transform.position.z-transform.position.z );
		float bSp = 10;
		rigidbody.AddRelativeForce(newXPos*bSp, newYPos*bSp, newZPos*bSp);
	}
	void OnTriggerEnter(Collider col) {

	}
	void OnCollisionEnter(Collision col){
		Debug.Log(col.gameObject.name);

		Destroy (gameObject);
		if(col.gameObject.name == "Enemy")
		{

			enemyguy.GetComponent<EnemyHealth>().TakeDamage(10);
			Destroy(gameObject, 3);
			//shootingtower.enemiesInRange.Remove(col.gameObject);
		}
	}
}


text:
%%% File encoding is UTF8

\chapter{Introducción}
%\newchapter{Introducción}
\label{ch:introduccion}
% Activate arabic numbering (e. g. 12)
\pagenumbering{arabic}
% Start with page 1 (I)
\setcounter{page}{1}
A través del presente capítulo se introduce el problema a resolver a lo largo del trabajo. En primer lugar, se presentan los antecedentes que motivan su realización. A continuación, se describen las características del problema, la propuesta de solución, sus alcances y objetivos. Finalmente, se describe la metodología utilizada y la organización del presente documento.

\input{02_Chapters/01_Introduccion/01_Antecedentes_Motivacion.tex}
\input{02_Chapters/01_Introduccion/02_Descripcion_Problema.tex}
\input{02_Chapters/01_Introduccion/03_Solucion_Propuesta.tex}
\input{02_Chapters/01_Introduccion/04_Objetivos_Alcances.tex}
\input{02_Chapters/01_Introduccion/05_Metodologias_Herramientas.tex}
\input{02_Chapters/01_Introduccion/06_Organizacion_Documento.tex}


text:
require 'active_storage_validations/matchers'
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|

#Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each { |f| require f }

  config.include ActiveStorageValidations::Matchers

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.shared_context_metadata_behavior = :apply_to_host_groups
  config.filter_run_when_matching :focus
  # config.example_status_persistence_file_path = "spec/examples.txt"
  config.disable_monkey_patching!

  if config.files_to_run.one?
    config.default_formatter = 'doc'
  end

  config.profile_examples = 1

  config.order = :random
  Kernel.srand config.seed

  RSpec::Matchers.define :have_attached_file do |name|
    match do |record|
      file = record.send(name)
      file.respond_to?(:variant) && file.respond_to?(:attach)
    end
  end

end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>CSS Masking: mask-repeat: repeated mask layer image</title>
    <link rel="author" title="Astley Chen" href="mailto:aschen@mozilla.com">
    <link rel="author" title="Mozilla" href="https://www.mozilla.org">


text:
<?php

namespace App\Model;

use App\Entity\Performance;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Type;

/**
 * Class PerformancesResponse
 * @package App\Model
 * @ExclusionPolicy("all")
 */
class PerformancesResponse extends AbstractPaginatedModel
{
    /**
     * @var Performance[]
     * @Type("array")
     * @Expose
     */
    protected $performances;

    /**
     * @var int
     *
     * @Type("integer")
     * @Accessor(getter="getCount")
     * @Expose
     */
    protected $count;

    /**
     * @return mixed
     */
    public function getPerformances()
    {
        return $this->performances;
    }

    /**
     * @param  Performance[] $performances
     * @return $this
     */
    public function setPerformances($performances)
    {
        $this->performances = $performances;

        return $this;
    }

    /**
     * @return int
     */
    public function getCount()
    {
        return count($this->getPerformances());
    }
}


text:
@typedef {function(documentjs.process.docObject)} documentjs.generators.html.types.renderer(docObject) renderer
@parent documentjs.generators.html.build.types

A renderer built by [documentjs.generators.html.build.renderer] that is used to
render each [documentjs.process.docObject docObject].

@param {documentjs.process.docObject} docObject The [documentjs.tags tag] data
of a comment.

@return {String} The HTML to be outputted.

@body

## Properties

A renderer function also has a `.layout` property which can be used
to render the layout template and a `.content` property that can be used
to render the `content` template.


text:
/**
 * jspsych-video-slider-response
 * Josh de Leeuw
 *
 * plugin for playing a video file and getting a slider response
 *
 * documentation: docs.jspsych.org
 *
 **/

jsPsych.plugins["video-slider-response"] = (function() {

  var plugin = {};

  jsPsych.pluginAPI.registerPreload('video-slider-response', 'stimulus', 'video');

  plugin.info = {
    name: 'video-slider-response',
    description: '',
    parameters: {
      sources: {
        type: jsPsych.plugins.parameterType.VIDEO,
        pretty_name: 'Video',
        default: undefined,
        description: 'The video file to play.'
      },
      prompt: {
        type: jsPsych.plugins.parameterType.STRING,
        pretty_name: 'Prompt',
        default: null,
        description: 'Any content here will be displayed below the stimulus.'
      },
      width: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name: 'Width',
        default: '',
        description: 'The width of the video in pixels.'
      },
      height: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name: 'Height',
        default: '',
        description: 'The height of the video display in pixels.'
      },
      autoplay: {
        type: jsPsych.plugins.parameterType.BOOL,
        pretty_name: 'Autoplay',
        default: true,
        description: 'If true, the video will begin playing as soon as it has loaded.'
      },
      controls: {
        type: jsPsych.plugins.parameterType.BOOL,
        pretty_name: 'Controls',
        default: false,
        description: 'If true, the subject will be able to pause the video or move the playback to any point in the video.'
      },
      start: {
        type: jsPsych.plugins.parameterType.FLOAT,
        pretty_name: 'Start',
        default: null,
        description: 'Time to start the clip.'
      },
      stop: {
        type: jsPsych.plugins.parameterType.FLOAT,
        pretty_name: 'Stop',
        default: null,
        description: 'Time to stop the clip.'
      },
      rate: {
        type: jsPsych.plugins.parameterType.FLOAT,
        pretty_name: 'Rate',
        default: 1,
        description: 'The playback rate of the video. 1 is normal, <1 is slower, >1 is faster.'
      },
      min: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name: 'Min slider',
        default: 0,
        description: 'Sets the minimum value of the slider.'
      },
      max: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name: 'Max slider',
        default: 100,
        description: 'Sets the maximum value of the slider',
      },
      slider_start: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name: 'Slider starting value',
        default: 50,
        description: 'Sets the starting value of the slider',
      },
      step: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name: 'Step',
        default: 1,
        description: 'Sets the step of the slider'
      },
      labels: {
        type: jsPsych.plugins.parameterType.HTML_STRING,
        pretty_name:'Labels',
        default: [],
        array: true,
        description: 'Labels of the slider.',
      },
      slider_width: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name:'Slider width',
        default: null,
        description: 'Width of the slider in pixels.'
      },
      button_label: {
        type: jsPsych.plugins.parameterType.STRING,
        pretty_name: 'Button label',
        default:  'Continue',
        array: false,
        description: 'Label of the button to advance.'
      },
      require_movement: {
        type: jsPsych.plugins.parameterType.BOOL,
        pretty_name: 'Require movement',
        default: false,
        description: 'If true, the participant will have to move the slider before continuing.'
      },
      trial_ends_after_video: {
        type: jsPsych.plugins.parameterType.BOOL,
        pretty_name: 'End trial after video finishes',
        default: false,
        description: 'If true, the trial will end immediately after the video finishes playing.'
      },
      trial_duration: {
        type: jsPsych.plugins.parameterType.INT,
        pretty_name: 'Trial duration',
        default: null,
        description: 'How long to show trial before it ends.'
      },
      response_ends_trial: {
        type: jsPsych.plugins.parameterType.BOOL,
        pretty_name: 'Response ends trial',
        default: true,
        description: 'If true, the trial will end when subject makes a response.'
      }
    }
  }

  plugin.trial = function(display_element, trial) {

    // setup stimulus
    var video_html = '<video id="jspsych-video-slider-response-stimulus"';

    if(trial.width) {
      video_html += ' width="'+trial.width+'"';
    }
    if(trial.height) {
      video_html += ' height="'+trial.height+'"';
    }
    if(trial.autoplay){
      video_html += " autoplay ";
    }
    if(trial.controls){
      video_html +=" controls ";
    }
    video_html +=">";

    var video_preload_blob = jsPsych.pluginAPI.getVideoBuffer(trial.sources[0]);
    if(!video_preload_blob) {
      for(var i=0; i<trial.sources.length; i++){
        var file_name = trial.sources[i];
        if(file_name.indexOf('?') > -1){
          file_name = file_name.substring(0, file_name.indexOf('?'));
        }
        var type = file_name.substr(file_name.lastIndexOf('.') + 1);
        type = type.toLowerCase();
        video_html+='<source src="' + file_name + '" type="video/'+type+'">';
      }
    }
    video_html += "</video>";

    var html = '
';
    html += '
' + video_html + '
';
    html += '
';
    html += '<input type="range" value="'+trial.start+'" min="'+trial.min+'" max="'+trial.max+'" step="'+trial.step+'" style="width: 100%;" id="jspsych-video-slider-response-response"></input>';
    html += '
'
    for(var j=0; j < trial.labels.length; j++){
      var width = 100/(trial.labels.length-1);
      var left_offset = (j * (100 /(trial.labels.length - 1))) - (width/2);
      html += '
';
      html += ''+trial.labels[j]+'';
      html += '
'
    }
    html += '
';
    html += '
';
    html += '
';

    // add prompt if there is one
    if (trial.prompt !== null) {
      html += '
'+trial.prompt+'
';
    }

    // add submit button
    html += '<button id="jspsych-video-slider-response-next" class="jspsych-btn" '+ (trial.require_movement ? "disabled" : "") + '>'+trial.button_label+'</button>';

    display_element.innerHTML = html;

    if(video_preload_blob){
      display_element.querySelector('#jspsych-video-slider-response-stimulus').src = video_preload_blob;
    }

    display_element.querySelector('#jspsych-video-slider-response-stimulus').onended = function(){
      if(trial.trial_ends_after_video){
        end_trial();
      }
    }

    if(trial.start !== null){
      display_element.querySelector('#jspsych-video-slider-response-stimulus').currentTime = trial.start;
    }

    if(trial.stop !== null){
      display_element.querySelector('#jspsych-video-slider-response-stimulus').addEventListener('timeupdate', function(e){
        var currenttime = display_element.querySelector('#jspsych-video-slider-response-stimulus').currentTime;
        if(currenttime >= trial.stop){
          display_element.querySelector('#jspsych-video-slider-response-stimulus').pause();
        }
      })
    }

    display_element.querySelector('#jspsych-video-slider-response-stimulus').playbackRate = trial.rate;

    if(trial.require_movement){
      display_element.querySelector('#jspsych-video-slider-response-response').addEventListener('change', function(){
        display_element.querySelector('#jspsych-video-slider-response-next').disabled = false;
      })
    }

    var startTime = performance.now();

    // store response
    var response = {
      rt: null,
      response: null
    };

    display_element.querySelector('#jspsych-video-slider-response-next').addEventListener('click', function() {
      // measure response time
      var endTime = performance.now();
      response.rt = endTime - startTime;
      response.response = display_element.querySelector('#jspsych-video-slider-response-response').value;

      if(trial.response_ends_trial){
        end_trial();
      } else {
        display_element.querySelector('#jspsych-video-slider-response-next').disabled = true;
      }

    });

    // function to end trial when it is time
    function end_trial() {

      // kill any remaining setTimeout handlers
      jsPsych.pluginAPI.clearAllTimeouts();

      // gather the data to store for the trial
      var trial_data = {
        "rt": response.rt,
        "stimulus": trial.stimulus,
        "response": response.response
      };

      // clear the display
      display_element.innerHTML = '';

      // move on to the next trial
      jsPsych.finishTrial(trial_data);
    };

    // end trial if time limit is set
    if (trial.trial_duration !== null) {
      jsPsych.pluginAPI.setTimeout(function() {
        end_trial();
      }, trial.trial_duration);
    }
  };

  return plugin;
})();


text:
New Bulk Needle Change Report

            Home

            BulkNeedleChangeReport

            New Bulk Needle Change Report

        <form data-ng-submit="create()" novalidate>
          <fieldset>

                Machine Number

                  <input type="Text" data-ng-model="machineNumber" id="machineNumber" class="form-control" placeholder="" required />

                Machine Make

                  <input type="Text" data-ng-model="machineMake" id="machineMake" class="form-control" placeholder="" required />

                DIA

                  <input type="Text" data-ng-model="dia" id="dia" class="form-control" placeholder="" required />

                Last Bulk Needle Changed Date

                  <input type="Date" data-ng-model="lastBulkNeedlechangedDate" id="lastbulkneedlechangeddate" class="form-control" placeholder="" required />

                Allowed Production Quantity

                  <input type="Number" data-ng-model="allowedProductionQuantity" id="allowedProductionQuantity" class="form-control" placeholder="" required />

                Actual Production Quantity

                  <input type="Number" data-ng-model="actualProductionQuantity" id="actualproductionquantity" class="form-control" placeholder="" required />

                Balance Qty

                  <input type="Number" data-ng-model="balanceQty" id="balanceqty" class="form-control" placeholder="" required />

                Remarks

                  <input type="Text" data-ng-model="remarks" id="remarks" class="form-control" placeholder="" required />

                <input type="submit" class="btn btn-primary" />

          </fieldset>
        </form>


text:
define(['./underscore', './toPath'], function (underscore, toPath$1) {

  // Internal wrapper for `_.toPath` to enable minification.
  // Similar to `cb` for `_.iteratee`.
  function toPath(path) {
    return underscore.toPath(path);
  }

  return toPath;

});


text:
<?php

namespace ERP\InventarioBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use ERP\AdminBundle\Entity\CtlTipoInventario;
use ERP\AdminBundle\Form\CtlTipoInventarioType;

/**
 * CtlPais controller.
 *
 * @Route("/admin/InventarioBundle/ctltipoinventario")
 */
class CtlTipoInventarioController extends Controller
{
    /**
     * Lists all CtlTipoInventario entities.
     *
     * @Route("/", name="ctltipoinventario_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $ctlTipoInventario = new CtlTipoInventario(); //Es para poder poner el ingreso
        $form = $this->createForm('ERP\AdminBundle\Form\CtlTipoInventarioType', $ctlTipoInventario); //Es para poder poner el ingreso
        $form->handleRequest($request); //Es para poder poner el ingreso

        $ctltipoinventario = $em->getRepository('ERPAdminBundle:CtlTipoInventario')->findAll();
        return $this->render('ERPInventarioBundle:tipoinventario:index.html.twig', array(
            'ctltipoinventario' => $ctltipoinventario,
            'form' => $form->createView(),
        ));
    }

    /**
     * Creates a new CtlTipoInventario entity.
     *
     * @Route("/new", name="ctltipoinventario_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $ctlTipoInventario = new CtlTipoInventario();
        $form = $this->createForm('ERP\AdminBundle\Form\CtlTipoInventarioType', $ctlTipoInventario);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $ctlTipoInventario->setEstado('1');
            $em->persist($ctlTipoInventario);
            $em->flush();

//            return $this->redirectToRoute('ctltipoinventario_index', array('id' => $ctlTipoInventario->getId()));
            return $this->redirectToRoute('ctltipoinventario_index');
        }

        return $this->render('ERPInventarioBundle:tipoinventario:new.html.twig', array(
            'ctlTipoInventario' => $ctlTipoInventario,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a CtlTipoInventario entity.
     *
     * @Route("/{id}", name="ctltipoinventario_show")
     * @Method("GET")
     */
    public function showAction(CtlTipoInventario $CtlTipoInventario)
    {
        $deleteForm = $this->createDeleteForm($CtlTipoInventario);

        return $this->render('ctlpais/show.html.twig', array(
            '$CtlTipoInventario' => $CtlTipoInventario,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing CtlTipoInventario entity.
     *
     * @Route("/{id}/edit", name="ctltipoinventario_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, CtlTipoInventario $CtlTipoInventario)
    {

        $deleteForm = $this->createDeleteForm($CtlTipoInventario);
        $editForm = $this->createForm('ERP\AdminBundle\Form\CtlTipoInventarioType', $CtlTipoInventario);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($CtlTipoInventario);
            $em->flush();

//            return $this->redirectToRoute('ctltipoinventario_edit', array('id' => $CtlTipoInventario->getId()));
            return $this->redirectToRoute('ctltipoinventario_index', array('id' => $CtlTipoInventario->getId()));
        }

        return $this->render('ERPInventarioBundle:tipoinventario/edit.html.twig', array(
            'CtlTipoInventario' => $CtlTipoInventario,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a CtlPais entity.
     *
     * @Route("/{id}", name="ctltipoinventario_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, CtlTipoInventario $CtlTipoInventario)
    {
        $form = $this->createDeleteForm($CtlTipoInventario);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($CtlTipoInventario);
            $em->flush();
        }

        return $this->redirectToRoute('ctltipoinventario_index');
    }

    /**
     * Creates a form to delete a CtlPais entity.
     *
     * @param CtlTipoInventario $CtlTipoInventario The CtlPais entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(CtlTipoInventario $CtlTipoInventario)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('ctlpais_delete', array('id' => $CtlTipoInventario->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /**
     *
     *
     * @Route("/tipoinventario/data", name="admin_tipoinventario_data")
     */
    public function dataterritorioAction(Request $request)
    {

        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Easy set variables
	 */

	/* Array of database columns which should be read and sent back to DataTables. Use a space where
	 * you want to insert a non-database field (for example a counter or static image)
	 */
        $entity = new CtlTipoInventario();

//
        //echo $output;
	//return new Response(json_encode( $output ));
    //echo json_encode( $output );
//    return array(
//            //'entities' => $entities,
//            'pacientes' => $output['aaData'],
//            'entity' => $entity,
//            'form'   => $form->createView(),
//        );
//       // $persona = new Persona();
//        //var_dump($request);
//        $entity = new Paciente();
//        var_dump($request);
        $start = $request->query->get('start');
        $draw = $request->query->get('draw');
        $longitud = $request->query->get('length');
        $busqueda = $request->query->get('search');

        $em = $this->getDoctrine()->getEntityManager();
        $territoriosTotal = $em->getRepository('ERPAdminBundle:CtlTerritorio')->findBy(array('estado'=>1));

        $territorio['draw']=$draw++;
        $territorio['recordsTotal'] = count($territoriosTotal);
        $territorio['recordsFiltered']= count($territoriosTotal);

        $territorio['data']= array();
        //var_dump($busqueda);
        //die();
        $arrayFiltro = explode(' ',$busqueda['value']);

        //echo count($arrayFiltro);
        $busqueda['value'] = str_replace(' ', '%', $busqueda['value']);
        if($busqueda['value']!=''){
            //foreach ($arrayFiltro as $row){
                //var_dump($row);
              //  if($row!=''){

                    $dql = "SELECT tin.id, tin.nombre ,concat(concat('<input type=\"checkbox\" class=\"checkbox idterritorio\" id=\"',tin.id), '\">' as link FROM ERPAdminBundle:CtlTipoInventario tin "
                        . "WHERE upper(tin.nombre) LIKE upper(:busqueda) and tin.estado=1 "
                        . "ORDER BY tin.nombre DESC ";
                   $territorio['data'] = $em->createQuery($dql)
                            ->setParameters(array('busqueda'=>"%".$busqueda['value']."%"))
                            ->getResult();

                   $territorio['recordsFiltered']= count($territorio['data']);

                   $dql = "SELECT tin.id, tin.nombre,concat(concat('<input type=\"checkbox\" class=\"checkbox idterritorio\" id=\"',tin.id), '\">' as link FROM ERPAdminBundle:CtlTipoInventario tin "
                        . "WHERE upper(tin.nombre) LIKE upper(:busqueda) and tin.estado=1 "
                        . "ORDER BY tin.nombre DESC ";

                   $territorio['data'] = $em->createQuery($dql)
                            ->setParameters(array('busqueda'=>"%".$busqueda['value']."%"))
                            ->setFirstResult($start)
                            ->setMaxResults($longitud)
                            ->getResult();

        }
        else{
            $dql = "SELECT tin.id , tin.nombre ,concat(concat('<input type=\"checkbox\" class=\"checkbox idterritorio\" id=\"',tin.id), '\">' as link FROM ERPAdminBundle:CtlTipoInventario tin "
                . " WHERE tin.estado=1 ORDER BY tin.nombre DESC ";
            $territorio['data'] = $em->createQuery($dql)
                    ->setFirstResult($start)
                    ->setMaxResults($longitud)
                    ->getResult();
        }

        return new Response(json_encode($territorio));
    }

    /**
     * Displays a form to edit an existing Orden entity.
     *
     * @Route("/admin/orders/delete/deletetipoinventario", name="delete_ctltipoinventario")
     */
    public function deleteTerritorioAction(Request $request)
    {

        $isAjax = $this->get('Request')->isXMLhttpRequest();
        //var_dump($isAjax);
        $response = new JsonResponse();
        //if($isAjax){
            //$id_territorio = $this->get('request')->request->get('id_territorio');
            $id_territorio = $request->request->get('id_territorio');
//            $ordenId = $this->get('request')->request->get('ordenId');

            foreach($id_territorio as $row){
                $em = $this->getDoctrine()->getManager();
                $detalleOrden = $em->getRepository('ERPAdminBundle:CtlTipoInventario')->find($row);
                $detalleOrden->setEstado(0);
                $em->persist($detalleOrden);
                $em->flush();

            }

            $response->setData(array(
                            'flag' => 0,

                    ));
            return $response;

    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `Window` struct in crate `glutin`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, Window">

    <title>glutin::Window - Rust</title>

    <link rel="stylesheet" type="text/css" href="../main.css">

glutin

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Struct glutin::<wbr>Window

                [−]

        [src]

pub struct Window {
    // some fields omitted
}

Represents an OpenGL context and the Window or environment around it.

Example

let window = Window::new().unwrap();

unsafe { window.make_current() };

loop {
    for event in window.poll_events() {
        match(event) {
            // process events here
            _ => ()
        }
    }

    // draw everything here

    window.swap_buffers();
    std::old_io::timer::sleep(17);
}

Methods

impl Window

fn new() -> Result<Window, CreationError>

Creates a new OpenGL context, and a Window for platforms where this is appropriate.

This function is equivalent to WindowBuilder::new().build().

Error should be very rare and only occur in case of permission denied, incompatible system,
 out of memory, etc.

fn is_closed(&self) -> bool

Returns true if the window has previously been closed by the user.

fn set_title(&self, title: &str)

Modifies the title of the window.

This is a no-op if the window has already been closed.

fn show(&self)

Shows the window if it was hidden.

Platform-specific

Has no effect on Android

fn hide(&self)

Hides the window if it was visible.

Platform-specific

Has no effect on Android

fn get_position(&self) -> Option<(i32, i32)>

Returns the position of the top-left hand corner of the window relative to the
 top-left hand corner of the desktop.

Note that the top-left hand corner of the desktop is not necessarily the same as
 the screen. If the user uses a desktop with multiple monitors, the top-left hand corner
 of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.

The coordinates can be negative if the top-left hand corner of the window is outside
 of the visible screen region.

Returns None if the window no longer exists.

fn set_position(&self, x: i32, y: i32)

Modifies the position of the window.

See get_position for more informations about the coordinates.

This is a no-op if the window has already been closed.

fn get_inner_size(&self) -> Option<(u32, u32)>

Returns the size in pixels of the client area of the window.

The client area is the content of the window, excluding the title bar and borders.
These are the dimensions of the frame buffer, and the dimensions that you should use
 when you call glViewport.

Returns None if the window no longer exists.

fn get_outer_size(&self) -> Option<(u32, u32)>

Returns the size in pixels of the window.

These dimensions include title bar and borders. If you don't want these, you should use
 use get_inner_size instead.

Returns None if the window no longer exists.

fn set_inner_size(&self, x: u32, y: u32)

Modifies the inner size of the window.

See get_inner_size for more informations about the values.

This is a no-op if the window has already been closed.

fn poll_events(&self) -> PollEventsIterator

Returns an iterator that poll for the next event in the window's events queue.
Returns None if there is no event in the queue.

Contrary to wait_events, this function never blocks.

fn wait_events(&self) -> WaitEventsIterator

Returns an iterator that returns events one by one, blocking if necessary until one is
available.

The iterator never returns None.

unsafe fn make_current(&self)

Sets the context as the current context.

fn is_current(&self) -> bool

Returns true if this context is the current one in this thread.

fn get_proc_address(&self, addr: &str) -> *const c_void

Returns the address of an OpenGL function.

Contrary to wglGetProcAddress, all available OpenGL functions return an address.

fn swap_buffers(&self)

Swaps the buffers in case of double or triple buffering.

You should call this function every time you have finished rendering, or the image
 may not be displayed on the screen.

Warning: if you enabled vsync, this function will block until the next time the screen
is refreshed. However drivers can choose to override your vsync settings, which means that
you can't know in advance whether swap_buffers will block or not.

unsafe fn platform_display(&self) -> *mut c_void

Gets the native platform specific display for this window.
This is typically only required when integrating with
other libraries that need this information.

unsafe fn platform_window(&self) -> *mut c_void

Gets the native platform specific window handle. This is
typically only required when integrating with other libraries
that need this information.

fn get_api(&self) -> Api

Returns the API that is currently provided by this window.

On Windows and OS/X, this always returns OpenGl.

On Android, this always returns OpenGlEs.

On Linux, it must be checked at runtime.

fn get_pixel_format(&self) -> PixelFormat

Returns the pixel format of this window.

fn create_window_proxy(&self) -> WindowProxy

Create a window proxy for this window, that can be freely
passed to different threads.

fn set_window_resize_callback(&mut self, callback: Option<fn(u32, u32)>)

Sets a resize callback that is called by Mac (and potentially other
operating systems) during resize operations. This can be used to repaint
during window resizing.

fn set_cursor(&self, cursor: MouseCursor)

Modifies the mouse cursor of the window.
Has no effect on Android.

fn hidpi_factor(&self) -> f32

Returns the ratio between the backing framebuffer resolution and the
window size in screen pixels. This is typically one for a normal display
and two for a retina display.

fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()>

Changes the position of the cursor in window coordinates.

fn set_cursor_state(&self, state: CursorState) -> Result<(), String>

Sets how glutin handles the cursor. See the documentation of CursorState for details.

Has no effect on Android.

Trait Implementations

impl Default for Window

fn default() -> Window

impl GlFunctionsSource for Window

fn get_proc_addr(&self, addr: &str) -> *const c_void

impl GlContext for Window

unsafe fn make_current(&self)

fn is_current(&self) -> bool

fn get_proc_address(&self, addr: &str) -> *const c_void

fn swap_buffers(&self)

fn get_api(&self) -> Api

fn get_pixel_format(&self) -> PixelFormat

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
using System;
using System.Collections.Generic;

namespace com.adjust.sdk
{
    public class AdjustEvent
    {
        internal string currency;
        internal string eventToken;

        internal List<string> partnerList;
        internal List<string> callbackList;

        internal double? revenue;

        // iOS specific members
        internal string receipt;
        internal string transactionId;

        internal bool isReceiptSet;

        public AdjustEvent(string eventToken)
        {
            this.eventToken = eventToken;
            this.isReceiptSet = false;
        }

        public void setRevenue(double amount, string currency)
        {
            this.revenue = amount;
            this.currency = currency;
        }

        public void addCallbackParameter(string key, string value)
        {
            if (callbackList == null)
            {
                callbackList = new List<string>();
            }

            callbackList.Add(key);
            callbackList.Add(value);
        }

        public void addPartnerParameter(string key, string value)
        {
            if (partnerList == null)
            {
                partnerList = new List<string>();
            }

            partnerList.Add(key);
            partnerList.Add(value);
        }

        public void setTransactionId(string transactionId)
        {
            this.transactionId = transactionId;
        }

        // iOS specific methods
        [Obsolete("This is an obsolete method. Please use the adjust purchase SDK for purchase verification (https://github.com/adjust/unity_purchase_sdk)")]
        public void setReceipt(string receipt, string transactionId)
        {
            this.receipt = receipt;
            this.transactionId = transactionId;
            this.isReceiptSet = true;
        }
    }
}


text:
Warns if a prop with a defined type isn't being used.

> **Note**: You can provide types in runtime types using [PropTypes] and/or
statically using [TypeScript] or [Flow]. This rule will validate your prop types
regardless of how you define them.

## Rule Details

Examples of **incorrect** code for this rule:

```jsx
class Hello extends React.Component {
  render() {
    return <div>Hello Bob</div>;
  }
}

Hello.propTypes = {
  name: PropTypes.string
};
```

```jsx
type Props = {
  firstname: string;
  middlename: string; // middlename is never used by the Hello component
  lastname: string;
}

class Hello extends React.Component<Props> {
  render() {
    return <div>Hello {this.props.firstname} {this.props.lastname}</div>;
  }
}
```

```jsx
type Props = {
  firstname: string;
  lastname: string;  // lastname isn't used by the Hello component
};

class Hello extends React.Component<Props> {
  render() {
    return <div>Hello {this.props.firstname}</div>;
  }
}

class Greetings extends React.Component<Props> {
  render() {
    return <div>Greetings  {this.props.firstname} {this.props.lastname}</div>;
  }
}
```

Examples of **correct** code for this rule:

```jsx
class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }
}

Hello.propTypes = {
  name: PropTypes.string
};
```

## Rule Options

This rule can take one argument to ignore some specific props during validation.

```js
...
"react/no-unused-prop-types": [<enabled>, { ignore: <ignore>, customValidators: <customValidator>, skipShapeProps: <skipShapeProps> }]
...
```

* `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0.
* `ignore`: optional array of props name to ignore during validation.
* `customValidators`: optional array of validators used for propTypes validation.
* `skipShapeProps`: In some cases it is impossible to accurately detect whether or not a `PropTypes.shape`'s values are being used. Setting this option to `true` will skip validation of `PropTypes.shape` (`true` by default).

## Known Issues/Limitations

- [False Positives: SFC (helper render methods)](#false-positives-sfc)

### False Positives SFC

Stateless Function Components (SFCs) accept props as an argument and return a JSX expression.
Even if the function gets called from a component, the props that are only used inside the component are not be considered used by a component.

Triggers false positive:

```js
function AComponent(props) {
  function helperRenderer(aProp) { // is considered SFC
    return (
      <span>{aProp}{props.bProp}</span>
    );
  }

  return (
    <div>
      {helperRenderer(props.aProp)}
    </div>
  );
}

AComponent.propTypes = {
  aProp: PropTypes.string,
  bProp: PropTypes.string // bProp is defined but never used
};
```
A suggested fix is to assign a bProp to a variable outside of the SFC.

```js
function AComponent(props) {
  const { bProp } = props
  function helperRenderer(aProp) { // is considered SFC
    return (
      <span>{aProp}{bProp}</span>
    );
  }

  return (
    <div>
      {helperRenderer(props.aProp)}
    </div>
  );
}

AComponent.propTypes = {
  aProp: PropTypes.string,
  bProp: PropTypes.string
};
```

[PropTypes]: https://reactjs.org/docs/typechecking-with-proptypes.html
[TypeScript]: https://www.typescriptlang.org/
[Flow]: https://flow.org/


text:
module Intrigue
module Entity
class Person < Intrigue::Model::Entity

  def metadata
    {
      :type => "Person",
      :required_attributes => ["name"]
    }
  end

  def validate(attributes)
    attributes["name"] =~ /^.*$/
  end

end
end
end


text:
import React from 'react';
import PropTypes from 'prop-types';

import ListGroup from 'react-bootstrap/ListGroup';

const PlayerList = (props) => {
  const users = props.users || [];

  return (

{props.isGame ? "Players" : "Users"}

      <ListGroup variant="flush" className="nav-sidebar">
        {
          users.map((user, index) => (
            <ListGroup.Item
              action
              key={index}
            >
              {user.username} {user.role}
            </ListGroup.Item>
          ))
        }
      </ListGroup>

  );
};

export default PlayerList;

PlayerList.propTypes = {
  users: PropTypes.arrayOf(PropTypes.object),
};


text:
//
//  HCPUpdateRequest.h
//
//  Created by Nikolay Demyankov on 24.05.16.
//

#import <Foundation/Foundation.h>

@interface HCPUpdateRequest : NSObject

/**
 *  URL to the application config on the server.
 */
@property (nonatomic, strong) NSURL *configURL;

/**
 *  Current working version of the web content.
 */
@property (nonatomic, strong) NSString *currentWebVersion;

/**
 *  Current native version of the app.
 */
@property (nonatomic) NSUInteger currentNativeVersion;

/**
 *  Additional request headers.
 */
@property (nonatomic, strong) NSDictionary *requestHeaders;

@end


text:
<TITLE>Review for Soul Food (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Soul Food (1997)

reviewed by
James Berardinelli

SOUL FOOD

A Film Review by James Berardinelli

RATING (0 TO 10): 7.0
Alternative Scale: *** out of ****

United States, 1997
U.S. Release Date: 9/26/97 (wide)
Running Length: 1:55
MPAA Classification: R (Profanity, sexual situations, brief violence)
Theatrical Aspect Ratio: 2.35:1

Cast: Vanessa L. Williams, Vivica Fox, Nia Long, Michael Beach,
      Mekhi Phifer, Jeffrey D. Sams, Brandon Hammond, Gina Ravera,
      Irma P. Hall
Director: George Tillman Jr.
Producer: Tracey E. Edmonds, Robert Teitel
Screenplay: George Tillman Jr.
Cinematography: Paul Elliott
Music: Lisa Coleman , Wendy Melvoin
U.S. Distributor: 20th Century Fox

     When it comes to "food" movies, you know the titles:  BABETTE'S
FEAST, EAT DRINK MAN WOMAN, BIG NIGHT, and so on...  You also know the
advice:  eat before coming to the theater or suffer a grumbling stomach
for ninety-plus minutes followed by a mad dash to the nearest restaurant
once the end credits start to roll.  And, while SOUL FOOD, the first
major release from director George Tillman Jr. (who previously made a
low-budget feature called SCENES FOR THE SOUL), isn't on the same level
as the previously-mentioned motion pictures, there's at least one scene
that's a literal feast for the eyes.

     Whether it's BOYZ 'N THE HOOD, DEAD PRESIDENTS, or SET IT OFF, the
tendency for movies aimed at black audiences is to make them fast-paced,
loud, and violent.  As a result, a kinder, gentler movie like SOUL FOOD
is something of a rarity (although, with entrees like THE PREACHER'S
WIFE and LOVE JONES, they are becoming a little more common).  This film
is a celebration of life and family, and a recognition that, through
good times and bad times, the ties of blood provide an unbreakable life-
line.

     SOUL FOOD tells the story of the trials of the Joseph family when
their beloved matriarch, Mama Joe (Irma P. Hall), slips into a diabetes-
induced coma.  Without Mama Joe's ritual Sunday dinners to keep everyone
together, the family begins to drift apart, with gaps widening between
sisters and spouses.  The film essentially follows the lives of Mama
Joe's three daughters.  Terri (Vanessa L. Williams), the eldest, is a
driven lawyer who puts work above her neglected husband, Miles (Michael
Beach).  Miles is tempted away from his steady, well-paying job by the
lure of his true love, music, and away from his wife by the proffered
charms of Terri's cousin, Faith (Gina Ravera).  Maxine (Viveca Fox) is
happily married to Kenny (Jeffrey D. Sams), and spends her days caring
for her husband and three children.  Bird (Nia Long) is newly hitched to
ex-con Lem (Mekhi Phifer), an intense, caring man whose volatile temper
often proves to be his undoing.

     SOUL FOOD is told from the point-of-view of young Ahmed (Brandon
Hammond), Maxine and Kenny's son.  While a few of his observations are
insightful, most of his voiceover narrative is superfluous and even
irritating.  75% of what he says is either needless exposition or
useless trivia.  Simply put, the kid won't shut up.  It's one thing to
open and close a film with a voiceover, but Ahmed's voice can be heard
throughout, dispensing pearls of wisdom that we could have easily done
without.

     Because the main characters are female, it's easy to compare SOUL
FOOD to the uneven WAITING TO EXHALE.  Both films feature their share of
small melodramas, and neither has an especially high opinion of the male
gender (although SOUL FOOD, which is written and directed by a man,
doesn't come as close to "male-bashing" as EXHALE did).  But, despite a
share of minor cliches and the occasional too-pat resolution, SOUL FOOD
is easily the better film.  The acting is more believable, the storyline
is more true-to-life, and the characters are more sympathetic.  SOUL
FOOD stays a cut above the average melodrama by keeping the characters
grounded and the situations from becoming too ripe.  There's a fine line
between good, solid drama and the sudsiness of a soap opera, and,
although there are times when SOUL FOOD crosses over, the movie remains
predominantly on the right side.

     With a uniformly attractive cast, SOUL FOOD isn't hard on the eyes.
Everyone (including Vanessa Williams, who isn't known as a stellar
actress) acquits themselves admirably, although it's worth noting that
none of the roles are terribly complex, so there's little need for
anyone to stretch their range.  And, while the meals don't take on the
same importance as in certain other food movies, we still get an eyeful:
deep-fried catfish, chicken and dumplings, cornbread, cakes, and other
assorted dishes.  SOUL FOOD contains enough diverse cinematic
ingredients to add a little zest and flavor to the pleasant-but-familiar
cinematic fare of an African American family drama.

Copyright 1997 James Berardinelli

- James Berardinelli
e-mail: berardin@mail.cybernex.net

The website has moved!!
The new address is: http://movie-reviews.colossus.net/

"The cinema is not an art which films life: the cinema is something between
art and life. Unlike painting and literature, the cinema both gives to life
and takes from it..."

- Jean-Luc Godard

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import {
    ArrayBindingPattern,
    ConstructorDeclaration,
    ExportDeclaration,
    ExternalModuleReference,
    FunctionDeclaration,
    GetAccessorDeclaration,
    Identifier,
    ImportDeclaration,
    ImportEqualsDeclaration,
    MethodDeclaration,
    MethodSignature,
    NamedExports,
    NamedImports,
    NamespaceImport,
    Node,
    ObjectBindingPattern,
    PropertyDeclaration,
    PropertySignature,
    SetAccessorDeclaration,
    StringLiteral,
    SyntaxKind,
} from 'typescript';

/**
 * Determines if the given node is an ImportDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is ImportDeclaration}
 */
export function isImportDeclaration(node?: Node): node is ImportDeclaration {
    return node !== undefined && node.kind === SyntaxKind.ImportDeclaration;
}

/**
 * Determines if the given node is an ImportEqualsDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is ImportEqualsDeclaration}
 */
export function isImportEqualsDeclaration(node?: Node): node is ImportEqualsDeclaration {
    return node !== undefined && node.kind === SyntaxKind.ImportEqualsDeclaration;
}

/**
 * Determines if the given node is a NamespaceImport.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is NamespaceImport}
 */
export function isNamespaceImport(node?: Node): node is NamespaceImport {
    return node !== undefined && node.kind === SyntaxKind.NamespaceImport;
}

/**
 * Determines if the given node are NamedImports.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is NamedImports}
 */
export function isNamedImports(node?: Node): node is NamedImports {
    return node !== undefined && node.kind === SyntaxKind.NamedImports;
}

/**
 * Determines if the given node are NamedExports.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is NamedExports}
 */
export function isNamedExports(node?: Node): node is NamedExports {
    return node !== undefined && node.kind === SyntaxKind.NamedExports;
}

/**
 * Determines if the given node is a StringLiteral.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is StringLiteral}
 */
export function isStringLiteral(node?: Node): node is StringLiteral {
    return node !== undefined && node.kind === SyntaxKind.StringLiteral;
}

/**
 * Determines if the given node is an Identifier.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is Identifier}
 */
export function isIdentifier(node?: Node): node is Identifier {
    return node !== undefined && node.kind === SyntaxKind.Identifier;
}

/**
 * Determines if the given node is an ExternalModuleReference.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is ExternalModuleReference}
 */
export function isExternalModuleReference(node?: Node): node is ExternalModuleReference {
    return node !== undefined && node.kind === SyntaxKind.ExternalModuleReference;
}

/**
 * Determines if the given node is an ExportDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is ExportDeclaration}
 */
export function isExportDeclaration(node?: Node): node is ExportDeclaration {
    return node !== undefined && node.kind === SyntaxKind.ExportDeclaration;
}

/**
 * Determines if the given node is an ObjectBindingPattern (i.e. let {x, y} = foo).
 *
 * @export
 * @param {Node} [node]
 * @returns {node is ObjectBindingPattern}
 */
export function isObjectBindingPattern(node?: Node): node is ObjectBindingPattern {
    return node !== undefined && node.kind === SyntaxKind.ObjectBindingPattern;
}

/**
 * Determines if the given node is an ArrayBindingPattern (i.e. let [x, y] = foo).
 *
 * @export
 * @param {Node} [node]
 * @returns {node is ArrayBindingPattern}
 */
export function isArrayBindingPattern(node?: Node): node is ArrayBindingPattern {
    return node !== undefined && node.kind === SyntaxKind.ArrayBindingPattern;
}

/**
 * Determines if the given node is a FunctionDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is FunctionDeclaration}
 */
export function isFunctionDeclaration(node?: Node): node is FunctionDeclaration {
    return node !== undefined && node.kind === SyntaxKind.FunctionDeclaration;
}

/**
 * Determines if the given node is a MethodSignature.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is MethodSignature}
 */
export function isMethodSignature(node?: Node): node is MethodSignature {
    return node !== undefined && node.kind === SyntaxKind.MethodSignature;
}

/**
 * Determines if the given node is a PropertySignature.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is PropertySignature}
 */
export function isPropertySignature(node?: Node): node is PropertySignature {
    return node !== undefined && node.kind === SyntaxKind.PropertySignature;
}

/**
 * Determines if the given node is a MethodDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is MethodDeclaration}
 */
export function isMethodDeclaration(node?: Node): node is MethodDeclaration {
    return node !== undefined && node.kind === SyntaxKind.MethodDeclaration;
}

/**
 * Determines if the given node is a PropertyDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is PropertyDeclaration}
 */
export function isPropertyDeclaration(node?: Node): node is PropertyDeclaration {
    return node !== undefined && node.kind === SyntaxKind.PropertyDeclaration;
}

/**
 * Determines if the given node is a ConstructorDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is ConstructorDeclaration}
 */
export function isConstructorDeclaration(node?: Node): node is ConstructorDeclaration {
    return node !== undefined && node.kind === SyntaxKind.Constructor;
}

/**
 * Determines if the given node is a isGetAccessorDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is isGetAccessorDeclaration}
 */
export function isGetAccessorDeclaration(node?: Node): node is GetAccessorDeclaration {
    return node !== undefined && node.kind === SyntaxKind.GetAccessor;
}

/**
 * Determines if the given node is a SetAccessorDeclaration.
 *
 * @export
 * @param {Node} [node]
 * @returns {node is SetAccessorDeclaration}
 */
export function isSetAccessorDeclaration(node?: Node): node is SetAccessorDeclaration {
    return node !== undefined && node.kind === SyntaxKind.SetAccessor;
}


text:
package gov.nasa.ensemble.common.mission;

import gov.nasa.ensemble.common.mission.MissionExtender.ConstructionException;

import java.util.ArrayList;

import junit.framework.TestCase;

public class TestMissionExtender extends TestCase {

	public void testConstruct() throws ConstructionException {

		MissionIndependentThing thing = MissionExtender.construct(MissionIndependentThing.class, "Two", new ArrayList<Object>());
		assertEquals(MissionSpecificThing.class, thing.getClass());
	}

	public static class MissionIndependentThing implements MissionExtendable {

		protected MissionIndependentThing(String arg1, ArrayList<Object> arg2) {
			// stub
		}

	}

	public static class MissionSpecificThing extends MissionIndependentThing {

		private MissionSpecificThing(String arg1, ArrayList<Object> arg2){
			super(arg1, arg2);
		}

	}

}


text:
    #***
  #*********************************************************************
#*************************************************************************
#***
#*** GizmoDaemon Config Script
#*** 	LIRCHauppauge Intercept config
#***
#*****************************************
  #*****************************************
    #***

"""

  Copyright (c) 2007, Gizmo Daemon Team
  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.

"""

############################
# Imports
##########################

from GizmoDaemon import *
from GizmoScriptDefault import *
from GizmoScriptAltTabber import *
import subprocess

ENABLED = True
VERSION_NEEDED = 3.2
INTERESTED_CLASSES = [GizmoEventClass.LIRC]
USES_LIRC_REMOTES = ["Hauppauge_350"]

############################
# LIRCHauppaugeIntercept Class definition
##########################

class LIRCHauppaugeIntercept(GizmoScriptDefault):
	"""
	Intercept LIRC Event Mapping for the Hauppauge remote
	"""

	############################
	# Public Functions
	##########################

	def onDeviceEvent(self, Event, Gizmo = None):
		"""
		Called from Base Class' onEvent method.
		See GizmodDispatcher.onEvent documention for an explanation of this function
		"""

		# if the event isn't from the remote we're interested in don't handle it
		if Event.Remote not in USES_LIRC_REMOTES:
			return False

		# process the key
	   	if   Event.Button == "Go" and self.AltTabber.isAltTabbing():
	   		self.AltTabber.doAltTab()
	   		return True
	   	else:
	   		# unmatched event, keep processing
			return False

	############################
	# Private Functions
	##########################

	def __init__(self):
		"""
		Default Constructor
		"""

		GizmoScriptDefault.__init__(self, ENABLED, VERSION_NEEDED, INTERESTED_CLASSES)
		self.AltTabber = GizmoScriptAltTabber()

############################
# LIRCHauppaugeIntercept class end
##########################

# register the user script
LIRCHauppaugeIntercept()


text:
using System;
using System.Collections.Generic;
using System.IO;

namespace Profiler.Data
{
    public class FrameHeader : EventData
    {
        public int ThreadIndex { get; private set; }

        public static FrameHeader Read(BinaryReader reader)
        {
            FrameHeader header = new FrameHeader();
            header.ThreadIndex = reader.ReadInt32();
            header.ReadEventData(reader);
            return header;
        }
    }

    public class EventFrame : Frame, ITick
    {
        public override DataResponse.Type ResponseType { get { return DataResponse.Type.EventFrame; } }

        public FrameHeader Header { get; private set; }
        public long Tick { get { return Header.Start; } }

        private List<Entry> entries = new List<Entry>();

        private EventTree root = null;
        public Profiler.Data.EventTree Root
        {
            get
            {
                if (root == null)
                    Load();

                return root;
            }
        }

        private BinaryReader reader = null;

        public long Start { get { return Header.Start; } }
        public long Finish { get { return Header.Finish; } }

        public override double Duration
        {
            get
            {
                return Header.Duration;
            }
        }

        public double SynchronizationDuration { get; set; }

        public override string Description
        {
            get
            {
                return String.Format("{0:0} ms", Header.Duration);
            }
        }

        public string DeatiledDescription
        {
            get
            {
                return String.Format("Work: {0:0.###}ms   Wait: {1:0.###}ms", Duration - SynchronizationDuration, SynchronizationDuration).Replace(',', '.');
            }
        }

        public EventDescriptionBoard DescriptionBoard { get; private set; }
        public FrameGroup Group { get; private set; }

        private Board<EventBoardItem, EventDescription, EventNode> board;
        public Board<EventBoardItem, EventDescription, EventNode> Board
        {
            get
            {
                if (board == null)
                    Load();

                return board;
            }
        }

        public List<Entry> Entries
        {
            get
            {
                if (entries == null)
                    Load();

                return entries;
            }
        }

        public List<Entry> Categories { get; private set; }
        public EventTree CategoriesTree { get; private set; }
        public List<EventData> Synchronization { get; private set; }

        Object loading = new object();

        public override void Load()
        {
            lock (loading)
            {
                if (!IsLoaded)
                {
                    entries = ReadEventList(reader, DescriptionBoard);

                    root = new EventTree(this, Entries);
                    board = new Board<EventBoardItem, EventDescription, EventNode>(root);

                    reader = null;
                    IsLoaded = true;
                }
            }
        }

        static List<EventData> ReadEventTimeList(BinaryReader reader)
        {
            int count = reader.ReadInt32();
            List<EventData> result = new List<EventData>(count);

            for (int i = 0; i < count; ++i)
                result.Add(EventData.Create(reader));

            return result;
        }

        static List<Entry> ReadEventList(BinaryReader reader, EventDescriptionBoard board)
        {
            int count = reader.ReadInt32();
            List<Entry> result = new List<Entry>(count);

            for (int i = 0; i < count; ++i)
                result.Add(Entry.Read(reader, board));

            return result;
        }

        List<EventData> LinearizeEventList(List<EventData> events)
        {
            List<EventData> result = new List<EventData>(events.Count);
            EventData currentRoot = null;

            foreach (EventData entry in events)
            {
                if (currentRoot == null)
                {
                    currentRoot = entry;
                    result.Add(entry);
                }
                else if (entry.Finish <= currentRoot.Finish)
                {
                    continue;
                }
                else if (Durable.TicksToMs(Math.Abs(entry.Start - currentRoot.Finish)) < 0.005)
                {
                    currentRoot.Finish = entry.Finish;
                }
                else
                {
                    currentRoot = entry;
                    result.Add(entry);
                }
            }

            return result;
        }

        protected void ReadInternal(BinaryReader reader)
        {
            Header = FrameHeader.Read(reader);
            Categories = ReadEventList(reader, DescriptionBoard);
            CategoriesTree = new EventTree(this, Categories);

            Synchronization = ReadEventTimeList(reader);
            Synchronization.Sort();
            Synchronization = LinearizeEventList(Synchronization);

            SynchronizationDuration = 0.0;
            foreach (EventData interval in Synchronization)
            {
                SynchronizationDuration += interval.Duration;
            }
        }

        public double CalculateFilteredTime(HashSet<Object> filter)
        {
            return Root.CalculateFilteredTime(filter);
        }

        public EventFrame(BinaryReader reader, FrameGroup group) : base(reader.BaseStream)
        {
            this.reader = reader;
            Group = group;
            DescriptionBoard = group.Board;
            ReadInternal(reader);
        }
    }
}