text:
package org.bpmscript.process.memory;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.bpmscript.BpmScriptException;
import org.bpmscript.IExecutorResult;
import org.bpmscript.IProcessDefinition;
import org.bpmscript.ProcessState;
import org.bpmscript.correlation.IConversationCorrelator;
import org.bpmscript.exec.java.IJavaProcessDefinition;
import org.bpmscript.exec.java.JavaProcessExecutor;
import org.bpmscript.exec.java.seriaize.JavaSerializingContinuationService;
import org.bpmscript.exec.js.IJavascriptProcessDefinition;
import org.bpmscript.exec.js.JavascriptProcessExecutor;
import org.bpmscript.exec.js.scope.ScopeService;
import org.bpmscript.exec.js.scope.memory.MemoryScopeStore;
import org.bpmscript.exec.js.serialize.JavascriptSerializingContinuationService;
import org.bpmscript.integration.IMessageBus;
import org.bpmscript.integration.internal.IInternalMessage;
import org.bpmscript.integration.internal.IMessageSender;
import org.bpmscript.integration.internal.adapter.BpmScriptFirstAdapter;
import org.bpmscript.integration.internal.adapter.BpmScriptNextAdapter;
import org.bpmscript.integration.internal.adapter.ConversationCorrelatorAdapter;
import org.bpmscript.integration.internal.adapter.LoggingAdapter;
import org.bpmscript.integration.internal.adapter.SpringAdapter;
import org.bpmscript.integration.internal.adapter.TimeoutAdapter;
import org.bpmscript.integration.internal.channel.InternalScriptChannel;
import org.bpmscript.integration.internal.correlation.ConversationCorrelator;
import org.bpmscript.integration.internal.memory.MemorySyncChannel;
import org.bpmscript.integration.internal.proxy.BpmScriptFacade;
import org.bpmscript.journal.IContinuationJournal;
import org.bpmscript.journal.IContinuationJournalEntry;
import org.bpmscript.js.reload.ILibraryToFile;
import org.bpmscript.js.reload.LibraryFileMonitor;
import org.bpmscript.paging.IPagedResult;
import org.bpmscript.paging.IQuery;
import org.bpmscript.paging.PagedResult;
import org.bpmscript.process.BpmScriptEngine;
import org.bpmscript.process.FolderDefinitionLoader;
import org.bpmscript.process.IAutoStartManager;
import org.bpmscript.process.IBpmScriptEngine;
import org.bpmscript.process.IBpmScriptFacade;
import org.bpmscript.process.IDefinition;
import org.bpmscript.process.IDefinitionManager;
import org.bpmscript.process.IInstance;
import org.bpmscript.process.IInstanceCallback;
import org.bpmscript.process.IInstanceKiller;
import org.bpmscript.process.IInstanceListener;
import org.bpmscript.process.IInstanceManager;
import org.bpmscript.process.IVersionedDefinitionManager;
import org.bpmscript.process.ProcessExecutorLookup;
import org.bpmscript.process.autostart.AutoStartManager;
import org.bpmscript.process.kill.InstanceKiller;
import org.bpmscript.process.spring.ApplicationContextDefinitionConfigurationLookup;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

/**
 *
 */
public class MemoryBpmScriptEngine implements InitializingBean, DisposableBean, ApplicationContextAware, IBpmScriptEngine,
        IVersionedDefinitionManager, IInstanceManager, IContinuationJournal, IMessageSender, IBpmScriptFacade, IConversationCorrelator, IAutoStartManager, IInstanceKiller {

    private ApplicationContext applicationContext;
    private MemoryVersionedDefinitionManager versionedDefinitionManager;
    private MemoryBpmScriptManager bpmScriptManager;
    private BpmScriptEngine engine;
    private String bpmScriptNextChannelName = "bpmscript-next";
    private String timeoutChannelName = "timeout";
    private String errorChannelName = "error";
    private String springChannelName = "spring";
    private String bpmScriptFirstChannelName = "bpmscript-first";
    private String syncChannelName = "sync";
    private String conversationChannelName = "conversation";
    private IMessageBus bus;
    private ConversationCorrelator conversationCorrelator;
    private Resource folder;
    private BpmScriptFacade bpmScriptFacade;
    private InstanceKiller instanceKiller;
    /**
     * @param name
     * @param autoKill
     * @see org.bpmscript.process.autostart.AutoStartManager#startup(java.lang.String, boolean)
     */
    public void startup(String name, boolean autoKill) {
        autoStartManager.startup(name, autoKill);
    }

    /**
     * @param definitionId
     * @param message
     * @return
     * @throws BpmScriptException
     * @see org.bpmscript.process.kill.InstanceKiller#killDefinitionInstances(java.lang.String, java.lang.String)
     */
    public int killDefinitionInstances(String definitionId, String message)
            throws BpmScriptException {
        return instanceKiller.killDefinitionInstances(definitionId, message);
    }

    /**
     * @param pid
     * @param message
     * @throws BpmScriptException
     * @see org.bpmscript.process.kill.InstanceKiller#killInstance(java.lang.String, java.lang.String)
     */
    public void killInstance(String pid, String message)
            throws BpmScriptException {
        instanceKiller.killInstance(pid, message);
    }

    private AutoStartManager autoStartManager;

    public MemoryBpmScriptEngine() {

    }

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {

        Assert.notNull(folder, "The folder property must be set");
        Assert.notNull(bus, "The bus property must be set");

        BlockingQueue<ILibraryToFile> libraryAssociationQueue = new LinkedBlockingQueue<ILibraryToFile>();
        BlockingQueue<ILibraryToFile> libraryChangeQueue = new LinkedBlockingQueue<ILibraryToFile>();

        versionedDefinitionManager = new MemoryVersionedDefinitionManager();
        bpmScriptManager = new MemoryBpmScriptManager();
        versionedDefinitionManager.setDefinitionManager(new MemoryDefinitionManager());
        InternalScriptChannel scriptChannel = new InternalScriptChannel();
        scriptChannel.setReplyTo(bus.getName() + ":" + bpmScriptNextChannelName);
        scriptChannel.setSender(bus);
        scriptChannel.setTimeoutAddress(bus.getName() + ":" + timeoutChannelName);
        scriptChannel.setErrorAddress(bus.getName() + ":" + errorChannelName);
        scriptChannel.setDefinitionConfigurationLookup(new ApplicationContextDefinitionConfigurationLookup(
                applicationContext));

        // javascript executor
        JavascriptProcessExecutor javascriptExecutor = new JavascriptProcessExecutor();
        JavascriptSerializingContinuationService javascriptContinuationService = new JavascriptSerializingContinuationService();
        javascriptContinuationService.setContinuationStore(bpmScriptManager);
        javascriptExecutor.setContinuationService(javascriptContinuationService);
        MemoryScopeStore scopeStore = new MemoryScopeStore();
        ScopeService scopeService = new ScopeService();
        scopeService.setLibraryAssociationQueue(libraryAssociationQueue);
        scopeService.setScopeStore(scopeStore);

        javascriptExecutor.setScopeService(scopeService);
        javascriptExecutor.setChannel(scriptChannel);

        // java executor
        JavaProcessExecutor javaExecutor = new JavaProcessExecutor();
        JavaSerializingContinuationService javaContinuationService = new JavaSerializingContinuationService();
        javaContinuationService.setContinuationJournal(bpmScriptManager);
        javaExecutor.setContinuationService(javaContinuationService);
        javaExecutor.setChannel(scriptChannel);

        engine = new BpmScriptEngine();
        engine.setInstanceManager(bpmScriptManager);
        ProcessExecutorLookup processExecutorLookup = new ProcessExecutorLookup();
        processExecutorLookup.addProcessExecutor(IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT,
                javascriptExecutor);
        processExecutorLookup.addProcessExecutor(IJavaProcessDefinition.DEFINITION_TYPE_JAVA, javaExecutor);
        engine.setProcessExecutorLookup(processExecutorLookup);
        engine.setContinuationJournal(bpmScriptManager);
        engine.setVersionedDefinitionManager(versionedDefinitionManager);

        MemorySyncChannel syncChannel = new MemorySyncChannel();

        bpmScriptFacade = new BpmScriptFacade();
        bpmScriptFacade.setAddress(bus.getName() + ":" + bpmScriptFirstChannelName);
        bpmScriptFacade.setReplyTo(bus.getName() + ":" + syncChannelName);
        bpmScriptFacade.setSender(bus);
        bpmScriptFacade.setSyncChannel(syncChannel);

        conversationCorrelator = new ConversationCorrelator();
        conversationCorrelator.setAddress(bus.getName() + ":" + bpmScriptNextChannelName);
        conversationCorrelator.setCorrelatorAddress(bus.getName() + ":" + conversationChannelName);
        conversationCorrelator.setReplyTo(bus.getName() + ":" + syncChannelName);
        conversationCorrelator.setSender(bus);
        conversationCorrelator.setSyncChannel(syncChannel);

        BpmScriptFirstAdapter bpmScriptFirstAdapter = new BpmScriptFirstAdapter(engine, bus);
        BpmScriptNextAdapter bpmScriptNextAdapter = new BpmScriptNextAdapter(engine, bus, bus.getName() + ":" + errorChannelName);

        TimeoutAdapter timeoutAdapter = new TimeoutAdapter(bus);

        ConversationCorrelatorAdapter conversationCorrelatorAdapter = new ConversationCorrelatorAdapter();
        conversationCorrelatorAdapter.setSender(bus);

        SpringAdapter springAdapter = new SpringAdapter(applicationContext, bus);
        bus.register(springChannelName, springAdapter);
        bus.register(bpmScriptFirstChannelName, bpmScriptFirstAdapter);
        bus.register(bpmScriptNextChannelName, bpmScriptNextAdapter);
        bus.register(timeoutChannelName, timeoutAdapter);
        bus.register(errorChannelName, new LoggingAdapter());
        bus.register(syncChannelName, syncChannel);
        bus.register(conversationChannelName, conversationCorrelatorAdapter);

        LibraryFileMonitor libraryFileMonitor = new LibraryFileMonitor();
        libraryFileMonitor.setLibraryAssociationQueue(libraryAssociationQueue);
        libraryFileMonitor.setLibraryChangeQueue(libraryChangeQueue);

        FolderDefinitionLoader folderDefinitionLoader = new FolderDefinitionLoader();
        folderDefinitionLoader.setEngine(engine);
        folderDefinitionLoader.setFolder(folder);
        folderDefinitionLoader.setLibraryChangeQueue(libraryChangeQueue);
        folderDefinitionLoader.setVersionedDefinitionManager(versionedDefinitionManager);
        folderDefinitionLoader.afterPropertiesSet();

        instanceKiller = new InstanceKiller();
        instanceKiller.setBpmScriptEngine(engine);
        instanceKiller.setContinuationJournal(bpmScriptManager);
        instanceKiller.setInstanceStatusManager(bpmScriptManager);

        autoStartManager = new AutoStartManager();
        autoStartManager.setBpmScriptFacade(bpmScriptFacade);
        autoStartManager.setInstanceKiller(instanceKiller);
        autoStartManager.setInstanceStatusManager(bpmScriptManager);
        autoStartManager.setVersionedDefinitionManager(versionedDefinitionManager);

    }

    public void setFolder(Resource folder) {
        this.folder = folder;
    }

    /**
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public String createBranch(String version) {
        return bpmScriptManager.createBranch(version);
    }

    public String createInstance(String parentVersion, String definitionId, String definitionName,
            String definitionType, String operation) throws BpmScriptException {
        return bpmScriptManager.createInstance(parentVersion, definitionId, definitionName, definitionType, operation);
    }

    public String createMainBranch(String pid) {
        return bpmScriptManager.createMainBranch(pid);
    }

    public String createVersion(String pid, String branch) {
        return bpmScriptManager.createVersion(pid, branch);
    }

    public IExecutorResult doWithInstance(String processInstanceId, IInstanceCallback callback) throws Exception {
        return bpmScriptManager.doWithInstance(processInstanceId, callback);
    }

    public Collection<String> getBranchesForPid(String pid) {
        return bpmScriptManager.getBranchesForPid(pid);
    }

    public List<IInstance> getChildInstances(String parentVersion) throws BpmScriptException {
        return bpmScriptManager.getChildInstances(parentVersion);
    }

    public byte[] getContinuationLatest(String branch) {
        return bpmScriptManager.getContinuationLatest(branch);
    }

    public Collection<IContinuationJournalEntry> getEntriesForPid(String pid) {
        return bpmScriptManager.getEntriesForPid(pid);
    }

    public IInstance getInstance(String pid) throws BpmScriptException {
        return bpmScriptManager.getInstance(pid);
    }

    public IPagedResult<IInstance> getInstances(IQuery query) throws BpmScriptException {
        return bpmScriptManager.getInstances(query);
    }

    public PagedResult<IInstance> getInstancesForDefinition(IQuery query, String definitionId)
            throws BpmScriptException {
        return bpmScriptManager.getInstancesForDefinition(query, definitionId);
    }

    public Collection<String> getLiveInstances(String definitionId) throws BpmScriptException {
        return bpmScriptManager.getLiveInstances(definitionId);
    }

    public Collection<IContinuationJournalEntry> getLiveResults(String pid) {
        return bpmScriptManager.getLiveResults(pid);
    }

    public ProcessState getProcessStateLatest(String branch) {
        return bpmScriptManager.getProcessStateLatest(branch);
    }

    public String getVersionLatest(String branch) {
        return bpmScriptManager.getVersionLatest(branch);
    }

    public void storeResult(byte[] continuation, IExecutorResult result) {
        bpmScriptManager.storeResult(continuation, result);
    }

    public void kill(String pid, String branch, String message) throws BpmScriptException {
        engine.kill(pid, branch, message);
    }

    public void sendFirst(String parentVersion, String definitionName, String operation, Object message)
            throws BpmScriptException {
        engine.sendFirst(parentVersion, definitionName, operation, message);
    }

    public void sendNext(String pid, String branch, Object message, String queueId) throws BpmScriptException {
        engine.sendNext(pid, branch, message, queueId);
    }

    public void setInstanceListener(IInstanceListener instanceListener) {
        engine.setInstanceListener(instanceListener);
    }

    public String validate(IProcessDefinition processDefinition) throws BpmScriptException {
        return engine.validate(processDefinition);
    }

    public void createDefinition(String id, IProcessDefinition processDefinition) throws BpmScriptException {
        versionedDefinitionManager.createDefinition(id, processDefinition);
    }

    public IDefinition getDefinition(String definitionId) throws BpmScriptException {
        return versionedDefinitionManager.getDefinition(definitionId);
    }

    public List<IDefinition> getDefinitionsByName(String name) throws BpmScriptException {
        return versionedDefinitionManager.getDefinitionsByName(name);
    }

    public IDefinition getPrimaryDefinition(String name) throws BpmScriptException {
        return versionedDefinitionManager.getPrimaryDefinition(name);
    }

    public List<IDefinition> getPrimaryDefinitions() throws BpmScriptException {
        return versionedDefinitionManager.getPrimaryDefinitions();
    }

    public void setDefinitionAsPrimary(String definitionId) throws BpmScriptException {
        versionedDefinitionManager.setDefinitionAsPrimary(definitionId);
    }

    public void setDefinitionManager(IDefinitionManager definitionManager) {
        versionedDefinitionManager.setDefinitionManager(definitionManager);
    }

    public void setBpmScriptNextChannelName(String bpmScriptNextChannelName) {
        this.bpmScriptNextChannelName = bpmScriptNextChannelName;
    }

    public void setTimeoutChannelName(String timeoutChannelName) {
        this.timeoutChannelName = timeoutChannelName;
    }

    public void setErrorChannelName(String errorChannelName) {
        this.errorChannelName = errorChannelName;
    }

    public void setSpringChannelName(String springChannelName) {
        this.springChannelName = springChannelName;
    }

    public void setBpmScriptFirstChannelName(String bpmScriptFirstChannelName) {
        this.bpmScriptFirstChannelName = bpmScriptFirstChannelName;
    }

    public void setSyncChannelName(String syncChannelName) {
        this.syncChannelName = syncChannelName;
    }

    public Object call(String toCorrelationId, long timeout, Object in) throws Exception {
        return conversationCorrelator.call(toCorrelationId, timeout, in);
    }

    /**
     * @see org.springframework.beans.factory.DisposableBean#destroy()
     */
    public void destroy() throws Exception {
        List<IDefinition> primaryDefinitions = versionedDefinitionManager.getPrimaryDefinitions();
        for (IDefinition primaryDefinition : primaryDefinitions) {
            List<IDefinition> definitionsByName = versionedDefinitionManager.getDefinitionsByName(primaryDefinition.getName());
            for (IDefinition definition : definitionsByName) {
                instanceKiller.killDefinitionInstances(definition.getId(), "Application Shutdown " + new Date());
            }
        }
    }

    /**
     * @see org.bpmscript.integration.internal.IMessageSender#send(java.lang.String, org.bpmscript.integration.internal.IInternalMessage)
     */
    public void send(String address, IInternalMessage internalMessage) {
        bus.send(address, internalMessage);
    }

    public Object call(String definitionName, String methodName, long timeout, Object... args) throws Exception {
        return bpmScriptFacade.call(definitionName, methodName, timeout, args);
    }

    public void callAsync(String definitionName, String methodName, Object... args) throws Exception {
        bpmScriptFacade.callAsync(definitionName, methodName, args);
    }

    public void setVersionedDefinitionManager(MemoryVersionedDefinitionManager versionedDefinitionManager) {
        this.versionedDefinitionManager = versionedDefinitionManager;
    }

    public void setBpmScriptManager(MemoryBpmScriptManager bpmScriptManager) {
        this.bpmScriptManager = bpmScriptManager;
    }

    public void setEngine(BpmScriptEngine engine) {
        this.engine = engine;
    }

    public void setConversationChannelName(String conversationChannelName) {
        this.conversationChannelName = conversationChannelName;
    }

    public void setBus(IMessageBus bus) {
        this.bus = bus;
    }

    public void setConversationCorrelator(ConversationCorrelator conversationCorrelator) {
        this.conversationCorrelator = conversationCorrelator;
    }

    public void setBpmScriptFacade(BpmScriptFacade bpmScriptFacade) {
        this.bpmScriptFacade = bpmScriptFacade;
    }

}


text:
#ifndef REMESHER_DELAUNAY_FLIPS_HEADER
#define REMESHER_DELAUNAY_FLIPS_HEADER

#include "defines.h"
#include "edgeflips.h"
#include "vertexinfo.h"

REMESHER_NAMESPACE_BEGIN

/*
 * This class performs edge flips directly on the 3D mesh to
 * obtain a delaunay triangulation of the mesh.
 * Edge flips are performed if the sum of the angles opposite
 * to the edge sum up to less than 180 degrees.
 */
class DelaunayFlips : public EdgeFlipsBase
{
  protected:
    bool check_flip_edge (std::size_t v1idx,
        std::size_t v2idx, std::size_t v0idx, std::size_t v3idx,
        std::size_t face1, std::size_t face2);

  public:
    DelaunayFlips (void);
    DelaunayFlips (TriangleMeshPtr mesh, VertexInfoListPtr vinfo);
};

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

inline
DelaunayFlips::DelaunayFlips (void)
{
  this->set_max_iterations(30);
  this->set_max_const_flips_iterations(3);
}

inline
DelaunayFlips::DelaunayFlips (TriangleMeshPtr mesh, VertexInfoListPtr vinfo)
{
  this->set_mesh(mesh);
  this->set_vertex_info(vinfo);
  this->set_max_iterations(30);
  this->set_max_const_flips_iterations(3);
}

REMESHER_NAMESPACE_END

#endif /* REMESHER_DELAUNAY_FLIPS_HEADER */

redpajama_set_name: RedPajamaGithub


text:
"""
@author: gallupliu
@contact: gallup-liu@hotmail.com

@version: 1.0
@license: Apache Licence
@file: model.py
@time: 2018/3/5 22:26

"""

import tensorflow as tf
import numpy as np

class TextCNN(object):
    """
    A CNN for text classification.
    Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
    """
    def __init__(
      self,inputs,labels,w2v_model, sequence_length, num_classes, filter_sizes, num_filters, l2_reg_lambda=0.0):

        # Placeholders for input, output and dropout
        self.embeddings = w2v_model
        self.input_x = inputs
        self.input_y = tf.cast(labels,tf.float32)
        # self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
        # self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
        self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")

        # Keeping track of l2 regularization loss (optional)
        l2_loss = tf.constant(0.0)

        # Embedding layer
        with tf.device('/cpu:0'), tf.name_scope("embedding"):
            self.W = tf.Variable(tf.to_float(self.embeddings), trainable=True, name="W")

            self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
            self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)

        # Create a convolution + maxpool layer for each filter size
        pooled_outputs = []
        for i, filter_size in enumerate(filter_sizes):
            with tf.name_scope("conv-maxpool-%s" % filter_size):
                # Convolution Layer
                filter_shape = [filter_size, 50, 1, num_filters]
                W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1),dtype=tf.float32, name="W")
                b = tf.Variable(tf.constant(0.1, shape=[num_filters]),dtype=tf.float32, name="b")
                conv = tf.nn.conv2d(
                    self.embedded_chars_expanded,
                    W,
                    strides=[1, 1, 1, 1],
                    padding="VALID",
                    name="conv")
                # Apply nonlinearity
                h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
                # Maxpooling over the outputs
                pooled = tf.nn.max_pool(
                    h,
                    ksize=[1, sequence_length - filter_size + 1, 1, 1],
                    strides=[1, 1, 1, 1],
                    padding='VALID',
                    name="pool")
                pooled_outputs.append(pooled)

        # Combine all the pooled features
        num_filters_total = num_filters * len(filter_sizes)
        self.h_pool = tf.concat(pooled_outputs, 3)
        self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])

        # Add dropout
        with tf.name_scope("dropout"):
            self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)

        # Final (unnormalized) scores and predictions
        with tf.name_scope("output"):
           W = tf.get_variable(
                        "W",
                        shape=[num_filters_total, num_classes],
                        initializer=tf.contrib.layers.xavier_initializer())
           b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
           l2_loss += tf.nn.l2_loss(b)
           self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
           self.predictions = tf.argmax(self.scores, 1, name="predictions")

        # CalculateMean cross-entropy loss
        with tf.name_scope("loss"):
            losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
            self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss

        # Accuracy
        with tf.name_scope("accuracy"):
            correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")

        self.train_op = self.train_op(self.loss)
    def train_op(self,loss):
        """
        :param loss:
        :return:
        """
        self.global_step = tf.Variable(0, name="globle_step", trainable=False)
        tvars = tf.trainable_variables()
        grads, _ = tf.clip_by_global_norm(tf.gradients(loss, tvars),5)

        # optimizer = tf.train.GradientDescentOptimizer(lstm.lr)
        self.lr = tf.train.exponential_decay(0.1,self.global_step,1000,0.95,staircase=True)
        optimizer = tf.train.GradientDescentOptimizer(self.lr)
        optimizer.apply_gradients(zip(grads, tvars))
        train_op = optimizer.apply_gradients(zip(grads, tvars), global_step=self.global_step)
        return train_op


text:
namespace Firebase.Xamarin.Database.Query
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;

    using Firebase.Xamarin.Database.Streaming;

    /// <summary>
    /// The FirebaseQuery interface.
    /// </summary>
    public interface IFirebaseQuery
    {
        /// <summary>
        /// Retrieves items which exist on the location specified by this query instance.
        /// </summary>
        /// <typeparam name="T"> Type of the items. </typeparam>
        /// <returns> Collection of <see cref="FirebaseObject{T}"/>. </returns>
        Task<IReadOnlyCollection<FirebaseObject<T>>> OnceAsync<T>();

        /// <summary>
        /// Returns current location as an observable which allows to real-time listening to events from the firebase server.
        /// </summary>
        /// <typeparam name="T"> Type of the items. </typeparam>
        /// <returns> Cold observable of <see cref="FirebaseEvent{T}"/>. </returns>
        IObservable<FirebaseEvent<T>> AsObservable<T>(string elementRoot = "");

        /// <summary>
        /// Builds the actual url of this query.
        /// </summary>
        /// <returns> The <see cref="string"/>. </returns>
        Task<string> BuildUrlAsync();
    }
}


text:
/*************************************************************************/ /*!
@Title          Resource Allocator API
@Copyright      Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@License        Dual MIT/GPLv2

The contents of this file are subject to the MIT license as set out below.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 ("GPL") in which case the provisions
of GPL are applicable instead of those above.

If you wish to allow use of your version of this file only under the terms of
GPL, and not to allow others to use your version of this file under the terms
of the MIT license, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by GPL as set
out in the file called "GPL-COPYING" included in this distribution. If you do
not delete the provisions above, a recipient may use your version of this file
under the terms of either the MIT license or GPL.

This License is also included in this distribution in the file called
"MIT-COPYING".

EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /**************************************************************************/

#ifndef _RA_H_
#define _RA_H_

#include "img_types.h"
#include "hash.h"
#include "osfunc.h"

/** Resource arena.
 *  struct _RA_ARENA_ deliberately opaque
 */
typedef struct _RA_ARENA_ RA_ARENA;			//PRQA S 3313
typedef struct _BM_MAPPING_ BM_MAPPING;

/** Enable support for arena statistics. */
#define RA_STATS

/** Resource arena statistics. */
struct _RA_STATISTICS_
{
    /** total number of segments add to the arena */
    IMG_SIZE_T uSpanCount;

    /** number of current live segments within the arena */
    IMG_SIZE_T uLiveSegmentCount;

    /** number of current free segments within the arena */
    IMG_SIZE_T uFreeSegmentCount;

    /** total number of resource within the arena */
    IMG_SIZE_T uTotalResourceCount;

    /** number of free resource within the arena */
    IMG_SIZE_T uFreeResourceCount;

    /** total number of resources allocated from the arena */
    IMG_SIZE_T uCumulativeAllocs;

    /** total number of resources returned to the arena */
    IMG_SIZE_T uCumulativeFrees;

    /** total number of spans allocated by the callback mechanism */
    IMG_SIZE_T uImportCount;

    /** total number of spans deallocated by the callback mechanism */
    IMG_SIZE_T uExportCount;
};
typedef struct _RA_STATISTICS_ RA_STATISTICS;

struct _RA_SEGMENT_DETAILS_
{
	IMG_SIZE_T      uiSize;
	IMG_CPU_PHYADDR sCpuPhyAddr;
	IMG_HANDLE      hSegment;
};
typedef struct _RA_SEGMENT_DETAILS_ RA_SEGMENT_DETAILS;

/**
 *  @Function   RA_Create
 *
 *  @Description
 *
 *  To create a resource arena.
 *
 *  @Input name - the name of the arena for diagnostic purposes.
 *  @Input base - the base of an initial resource span or 0.
 *  @Input uSize - the size of an initial resource span or 0.
 *  @Input pRef - the reference to return for the initial resource or 0.
 *  @Input uQuantum - the arena allocation quantum.
 *  @Input alloc - a resource allocation callback or 0.
 *  @Input free - a resource de-allocation callback or 0.
 *  @Input import_handle - handle passed to alloc and free or 0.
 *  @Return arena handle, or IMG_NULL.
 */
RA_ARENA *
RA_Create (IMG_CHAR *name,
           IMG_UINTPTR_T base,
           IMG_SIZE_T uSize,
           BM_MAPPING *psMapping,
           IMG_SIZE_T uQuantum,
           IMG_BOOL (*imp_alloc)(IMG_VOID *_h,
                                IMG_SIZE_T uSize,
                                IMG_SIZE_T *pActualSize,
                                BM_MAPPING **ppsMapping,
                                IMG_UINT32 uFlags,
								IMG_PVOID pvPrivData,
								IMG_UINT32 ui32PrivDataLength,
                                IMG_UINTPTR_T *pBase),
           IMG_VOID (*imp_free) (IMG_VOID *,
                                IMG_UINTPTR_T,
                                BM_MAPPING *),
           IMG_VOID (*backingstore_free) (IMG_VOID *,
                                          IMG_SIZE_T,
                                          IMG_SIZE_T,
                                          IMG_HANDLE),
           IMG_VOID *import_handle);

/**
 *  @Function   RA_Delete
 *
 *  @Description
 *
 *  To delete a resource arena. All resources allocated from the arena
 *  must be freed before deleting the arena.
 *
 *  @Input  pArena - the arena to delete.
 *  @Return None
 */
IMG_VOID
RA_Delete (RA_ARENA *pArena);

/**
 *  @Function   RA_TestDelete
 *
 *  @Description
 *
 *  To test whether it is safe to delete a resource arena. If any allocations
 *	have not been freed, the RA must not be deleted.
 *
 *  @Input  pArena - the arena to test.
 *  @Return IMG_BOOL - IMG_TRUE if is safe to go on and call RA_Delete.
 */
IMG_BOOL
RA_TestDelete (RA_ARENA *pArena);

/**
 *  @Function   RA_Add
 *
 *  @Description
 *
 *  To add a resource span to an arena. The span must not overlap with
 *  any span previously added to the arena.
 *
 *  @Input pArena - the arena to add a span into.
 *  @Input base - the base of the span.
 *  @Input uSize - the extent of the span.
 *  @Return IMG_TRUE - success, IMG_FALSE - failure
 */
IMG_BOOL
RA_Add (RA_ARENA *pArena, IMG_UINTPTR_T base, IMG_SIZE_T uSize);

/**
 *  @Function   RA_Alloc
 *
 *  @Description
 *
 *  To allocate resource from an arena.
 *
 *  @Input  pArena - the arena
 *  @Input  uRequestSize - the size of resource segment requested.
 *  @Output pActualSize - the actual_size of resource segment allocated,
 *          typcially rounded up by quantum.
 *  @Output ppsMapping - the user reference associated with allocated
 *          resource span.
 *  @Input  uFlags - flags influencing allocation policy.
 *  @Input  uAlignment - the alignment constraint required for the
 *          allocated segment, use 0 if alignment not required.
 *	@Input  uAlignmentOffset - the required alignment offset
 *  @Input  pvPrivData - private data passed to OS allocator
 *  @Input  ui32PrivData - length of private data
 *
 *  @Output pBase - allocated base resource
 *  @Return IMG_TRUE - success, IMG_FALSE - failure
 */
IMG_BOOL
RA_Alloc (RA_ARENA *pArena,
          IMG_SIZE_T uSize,
          IMG_SIZE_T *pActualSize,
          BM_MAPPING **ppsMapping,
          IMG_UINT32 uFlags,
          IMG_UINT32 uAlignment,
		  IMG_UINT32 uAlignmentOffset,
		  IMG_PVOID pvPrivData,
		  IMG_UINT32 ui32PrivDataLength,
          IMG_UINTPTR_T *pBase);

/**
 *  @Function   RA_Free
 *
 *  @Description    To free a resource segment.
 *
 *  @Input  pArena - the arena the segment was originally allocated from.
 *  @Input  base - the base of the resource span to free.
 *	@Input	bFreeBackingStore - Should backing store memory be freed?
 *
 *  @Return None
 */
IMG_VOID
RA_Free (RA_ARENA *pArena, IMG_UINTPTR_T base, IMG_BOOL bFreeBackingStore);

#ifdef RA_STATS

#define CHECK_SPACE(total)					\
{											\
	if((total)<100) 							\
		return PVRSRV_ERROR_INVALID_PARAMS;	\
}

#define UPDATE_SPACE(str, count, total)		\
{											\
	if((count) == -1)					 		\
		return PVRSRV_ERROR_INVALID_PARAMS;	\
	else									\
	{										\
		(str) += (count);						\
		(total) -= (count);						\
	}										\
}

/**
 * @Function    RA_GetNextLiveSegment
 *
 * @Description Returns details of the next live resource segments
 *
 * @Input       pArena - the arena the segment was originally allocated from.
 * @Output      psSegDetails - rtn details of segments
 *
 * @Return      IMG_TRUE if operation succeeded
 */
IMG_BOOL RA_GetNextLiveSegment(IMG_HANDLE hArena, RA_SEGMENT_DETAILS *psSegDetails);

/**
 *  @Function   RA_GetStats
 *
 *  @Description    gets stats on a given arena
 *
 *  @Input  pArena - the arena the segment was originally allocated from.
 *  @Input  ppszStr - string to write stats to
 *	@Input	pui32StrLen - length of string
 *
 *  @Return PVRSRV_ERROR
 */
PVRSRV_ERROR RA_GetStats(RA_ARENA *pArena,
							IMG_CHAR **ppszStr,
							IMG_UINT32 *pui32StrLen);

PVRSRV_ERROR RA_GetStatsFreeMem(RA_ARENA *pArena,
								IMG_CHAR **ppszStr,
								IMG_UINT32 *pui32StrLen);

#endif /* #ifdef RA_STATS */

#endif


text:
/*
 * 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 io.prestosql.plugin.hive;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import io.prestosql.spi.Page;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.BlockBuilder;
import io.prestosql.spi.block.ColumnarRow;
import io.prestosql.spi.block.LazyBlock;
import io.prestosql.spi.block.LazyBlockLoader;
import io.prestosql.spi.connector.ColumnHandle;
import io.prestosql.spi.type.Type;

import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.prestosql.spi.block.ColumnarRow.toColumnarRow;
import static java.util.Objects.requireNonNull;

public class ReaderProjectionsAdapter
{
    private final List<ChannelMapping> outputToInputMapping;
    private final List<Type> outputTypes;
    private final List<Type> inputTypes;

    public ReaderProjectionsAdapter(
            List<ColumnHandle> expectedColumns,
            ReaderColumns readColumns,
            ColumnTypeGetter typeGetter,
            ProjectionGetter projectionGetter)
    {
        requireNonNull(expectedColumns, "expectedColumns is null");
        requireNonNull(readColumns, "readColumns is null");

        ImmutableList.Builder<ChannelMapping> mappingBuilder = ImmutableList.builder();

        for (int i = 0; i < expectedColumns.size(); i++) {
            ColumnHandle projectedColumnHandle = readColumns.getForColumnAt(i);
            int inputChannel = readColumns.getPositionForColumnAt(i);
            List<Integer> dereferences = projectionGetter.get(expectedColumns.get(i), projectedColumnHandle);

            mappingBuilder.add(new ChannelMapping(inputChannel, dereferences));
        }

        outputToInputMapping = mappingBuilder.build();

        outputTypes = expectedColumns.stream()
                .map(typeGetter::get)
                .collect(toImmutableList());

        inputTypes = readColumns.get().stream()
                .map(typeGetter::get)
                .collect(toImmutableList());
    }

    public Page adaptPage(Page input)
    {
        if (input == null) {
            return null;
        }

        Block[] blocks = new Block[outputToInputMapping.size()];

        // Prepare adaptations to extract dereferences
        for (int i = 0; i < outputToInputMapping.size(); i++) {
            ChannelMapping mapping = outputToInputMapping.get(i);

            Block inputBlock = input.getBlock(mapping.getInputChannelIndex());
            blocks[i] = createAdaptedLazyBlock(inputBlock, mapping.getDereferenceSequence(), outputTypes.get(i));
        }

        return new Page(input.getPositionCount(), blocks);
    }

    private static Block createAdaptedLazyBlock(Block inputBlock, List<Integer> dereferenceSequence, Type type)
    {
        if (dereferenceSequence.size() == 0) {
            return inputBlock;
        }

        if (inputBlock == null) {
            return null;
        }

        return new LazyBlock(inputBlock.getPositionCount(), new DereferenceBlockLoader(inputBlock, dereferenceSequence, type));
    }

    private static class DereferenceBlockLoader
            implements LazyBlockLoader
    {
        private final List<Integer> dereferenceSequence;
        private final Type type;
        private boolean loaded;
        private Block inputBlock;

        DereferenceBlockLoader(Block inputBlock, List<Integer> dereferenceSequence, Type type)
        {
            this.inputBlock = requireNonNull(inputBlock, "inputBlock is null");
            this.dereferenceSequence = requireNonNull(dereferenceSequence, "dereferenceSequence is null");
            this.type = type;
        }

        @Override
        public Block load()
        {
            checkState(!loaded, "Already loaded");
            Block loadedBlock = loadInternalBlock(dereferenceSequence, inputBlock);
            inputBlock = null;
            loaded = true;
            return loadedBlock;
        }

        /**
         * Applies dereference operations on the input block to extract the required internal block. If the input block is lazy
         * in a nested manner, this implementation avoids loading the entire input block.
         */
        private Block loadInternalBlock(List<Integer> dereferences, Block parentBlock)
        {
            if (dereferences.size() == 0) {
                return parentBlock.getLoadedBlock();
            }

            ColumnarRow columnarRow = toColumnarRow(parentBlock);

            int dereferenceIndex = dereferences.get(0);
            List<Integer> remainingDereferences = dereferences.subList(1, dereferences.size());

            Block fieldBlock = columnarRow.getField(dereferenceIndex);
            Block loadedInternalBlock = loadInternalBlock(remainingDereferences, fieldBlock);

            // Field blocks provided by ColumnarRow can have a smaller position count, because they do not store nulls.
            // The following step adds null elements (when required) to the loaded block.
            return adaptNulls(columnarRow, loadedInternalBlock);
        }

        private Block adaptNulls(ColumnarRow columnarRow, Block loadedInternalBlock)
        {
            // TODO: The current implementation copies over data to a new block builder when a null row element is found.
            //  We can optimize this by using a Block implementation that uses a null vector of the parent row block and
            //  the block for the field.

            BlockBuilder newlyCreatedBlock = null;
            int fieldBlockPosition = 0;

            for (int i = 0; i < columnarRow.getPositionCount(); i++) {
                boolean isRowNull = columnarRow.isNull(i);

                if (isRowNull) {
                    // A new block is only created when a null is encountered for the first time.
                    if (newlyCreatedBlock == null) {
                        newlyCreatedBlock = type.createBlockBuilder(null, columnarRow.getPositionCount());

                        // Copy over all elements encountered so far to the new block
                        for (int j = 0; j < i; j++) {
                            type.appendTo(loadedInternalBlock, j, newlyCreatedBlock);
                        }
                    }
                    newlyCreatedBlock.appendNull();
                }
                else {
                    if (newlyCreatedBlock != null) {
                        type.appendTo(loadedInternalBlock, fieldBlockPosition, newlyCreatedBlock);
                    }
                    fieldBlockPosition++;
                }
            }

            if (newlyCreatedBlock == null) {
                // If there was no need to create a null, return the original block
                return loadedInternalBlock;
            }

            return newlyCreatedBlock.build();
        }
    }

    List<ChannelMapping> getOutputToInputMapping()
    {
        return outputToInputMapping;
    }

    List<Type> getOutputTypes()
    {
        return outputTypes;
    }

    List<Type> getInputTypes()
    {
        return inputTypes;
    }

    @VisibleForTesting
    static class ChannelMapping
    {
        private final int inputChannelIndex;
        private final List<Integer> dereferenceSequence;

        public ChannelMapping(int inputBlockIndex, List<Integer> dereferenceSequence)
        {
            checkArgument(inputBlockIndex >= 0, "inputBlockIndex cannot be negative");
            this.inputChannelIndex = inputBlockIndex;
            this.dereferenceSequence = ImmutableList.copyOf(requireNonNull(dereferenceSequence, "dereferences is null"));
        }

        public int getInputChannelIndex()
        {
            return inputChannelIndex;
        }

        public List<Integer> getDereferenceSequence()
        {
            return dereferenceSequence;
        }
    }

    public interface ColumnTypeGetter
    {
        Type get(ColumnHandle column);
    }

    public interface ProjectionGetter
    {
        List<Integer> get(ColumnHandle required, ColumnHandle read);
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.Extensions.Localization;

namespace OrchardCore.Autoroute.Models
{
    public static class AutoroutePartExtensions
    {
        public static IEnumerable<ValidationResult> ValidatePathFieldValue(this AutoroutePart autoroute, IStringLocalizer S)
        {
            if (autoroute.Path == "/")
            {
                yield return new ValidationResult(S["Your permalink can't be set to the homepage, please use the homepage option instead."], new[] { nameof(autoroute.Path) });
            }

            if (HasInvalidCharacters(autoroute.Path))
            {
                var invalidCharactersForMessage = string.Join(", ", AutoroutePart.InvalidCharactersForPath.Select(c => $"\"{c}\""));
                yield return new ValidationResult(S["Please do not use any of the following characters in your permalink: {0}. No spaces, or consecutive slashes, are allowed (please use dashes or underscores instead).", invalidCharactersForMessage], new[] { nameof(autoroute.Path) });
            }

            if (autoroute.Path?.Length > AutoroutePart.MaxPathLength)
            {
                yield return new ValidationResult(S["Your permalink is too long. The permalink can only be up to {0} characters.", AutoroutePart.MaxPathLength], new[] { nameof(autoroute.Path) });
            }
        }

        private static bool HasInvalidCharacters(string path)
        {
            // IndexOfAny performs culture-insensitive and case-sensitive search.
            if (path?.IndexOfAny(AutoroutePart.InvalidCharactersForPath) > -1)
            {
                return true;
            }

            if (path?.IndexOf(' ', StringComparison.Ordinal) > -1)
            {
                return true;
            }

            if (path?.IndexOf("//", StringComparison.Ordinal) > -1)
            {
                return true;
            }

            return false;
        }
    }
}


text:
namespace Citicon.Inventory
{
    partial class PriceHistoryForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PriceHistoryForm));
            this.dgvPriceHistory = new System.Windows.Forms.DataGridView();
            this.colDate = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colPrice = new System.Windows.Forms.DataGridViewTextBoxColumn();
            ((System.ComponentModel.ISupportInitialize)(this.dgvPriceHistory)).BeginInit();
            this.SuspendLayout();
            //
            // dgvPriceHistory
            //
            this.dgvPriceHistory.AllowUserToAddRows = false;
            this.dgvPriceHistory.AllowUserToDeleteRows = false;
            this.dgvPriceHistory.AllowUserToResizeRows = false;
            dataGridViewCellStyle1.BackColor = System.Drawing.Color.WhiteSmoke;
            this.dgvPriceHistory.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
            this.dgvPriceHistory.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.dgvPriceHistory.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells;
            this.dgvPriceHistory.BackgroundColor = System.Drawing.Color.Gainsboro;
            this.dgvPriceHistory.BorderStyle = System.Windows.Forms.BorderStyle.None;
            this.dgvPriceHistory.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.SingleVertical;
            this.dgvPriceHistory.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle2.BackColor = System.Drawing.Color.White;
            dataGridViewCellStyle2.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Red;
            dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
            this.dgvPriceHistory.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
            this.dgvPriceHistory.ColumnHeadersHeight = 50;
            this.dgvPriceHistory.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgvPriceHistory.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.colDate,
            this.colPrice});
            dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
            dataGridViewCellStyle3.BackColor = System.Drawing.Color.White;
            dataGridViewCellStyle3.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            dataGridViewCellStyle3.ForeColor = System.Drawing.Color.Red;
            dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
            dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.White;
            dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
            this.dgvPriceHistory.DefaultCellStyle = dataGridViewCellStyle3;
            this.dgvPriceHistory.EnableHeadersVisualStyles = false;
            this.dgvPriceHistory.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
            this.dgvPriceHistory.Location = new System.Drawing.Point(14, 15);
            this.dgvPriceHistory.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.dgvPriceHistory.MultiSelect = false;
            this.dgvPriceHistory.Name = "dgvPriceHistory";
            this.dgvPriceHistory.ReadOnly = true;
            this.dgvPriceHistory.RowHeadersVisible = false;
            this.dgvPriceHistory.RowTemplate.Height = 30;
            this.dgvPriceHistory.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dgvPriceHistory.Size = new System.Drawing.Size(808, 619);
            this.dgvPriceHistory.TabIndex = 13;
            //
            // colDate
            //
            this.colDate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
            this.colDate.HeaderText = "Date";
            this.colDate.Name = "colDate";
            this.colDate.ReadOnly = true;
            this.colDate.Width = 59;
            //
            // colPrice
            //
            this.colPrice.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
            this.colPrice.HeaderText = "Price";
            this.colPrice.Name = "colPrice";
            this.colPrice.ReadOnly = true;
            this.colPrice.Width = 60;
            //
            // PriceHistoryForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.White;
            this.ClientSize = new System.Drawing.Size(836, 602);
            this.Controls.Add(this.dgvPriceHistory);
            this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.ForeColor = System.Drawing.Color.Red;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.Name = "PriceHistoryForm";
            this.Text = "PriceHistoryForm";
            this.Load += new System.EventHandler(this.PriceHistoryForm_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dgvPriceHistory)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dgvPriceHistory;
        private System.Windows.Forms.DataGridViewTextBoxColumn colDate;
        private System.Windows.Forms.DataGridViewTextBoxColumn colPrice;
    }
}


text:
#ifndef PLATFORM_MUTEX_H
#define PLATFORM_MUTEX_H

#include "platform/NonCopyable.h"

/** \addtogroup platform
 * @{
 */

/** \defgroup platform_PlatformMutex PlatformMutex class
 * @{
 */

/** The PlatformMutex class is used to synchronize the execution of threads.
 *
 * Mbed drivers use the PlatformMutex class instead of rtos::Mutex.
 * This enables the use of drivers when the Mbed OS is compiled without the RTOS.
 *
 * @note
 * - When the RTOS is present, the PlatformMutex becomes a typedef for rtos::Mutex.
 * - When the RTOS is absent, all methods are defined as noop.
 */

#ifdef MBED_CONF_RTOS_PRESENT

#include "rtos/Mutex.h"
typedef rtos::Mutex PlatformMutex;

#else

class PlatformMutex: private mbed::NonCopyable<PlatformMutex> {
public:
    /** Create a PlatformMutex object.
     *
     * @note When the RTOS is present, this is an alias for rtos::Mutex::Mutex().
     */
    PlatformMutex()
    {
    }

    /** PlatformMutex destructor.
     *
     * @note When the RTOS is present, this is an alias for rtos::Mutex::~Mutex().
     */
    ~PlatformMutex()
    {
    }

    /** Wait until a PlatformMutex becomes available.
     *
     * @note
     * - When the RTOS is present, this is an alias for rtos::Mutex::lock().
     * - When the RTOS is absent, this is a noop.
     */
    void lock()
    {
    }

    /** Unlock a PlatformMutex that the same thread has previously locked.
     *
     * @note
     * - When the RTOS is present, this is an alias for rtos::Mutex::unlock().
     * - When the RTOS is absent, this is a noop.
     */
    void unlock()
    {
    }
};

#ifdef ARDUINO

#include "SingletonPtr.h"

template <>
struct SingletonPtr<PlatformMutex> {
    SingletonPtr<PlatformMutex>* get() { return this; }
    SingletonPtr<PlatformMutex>* operator->() { return this; }
    void lock() {}
    void unlock() {}
};

#endif

#endif

#endif

/**@}*/

/**@}*/


text:
'use strict';

const Watcher = require('./watcher');

class ServerWatcher extends Watcher {
  constructor(options) {
    super(options);

    this.watcher.on('add', this.didAdd.bind(this));
    this.watcher.on('delete', this.didDelete.bind(this));
  }

  constructWatcher(options) {
    return new (require('sane'))(this.watchedDir, options);
  }

  didChange(relativePath) {
    let description = `File changed: "${relativePath}"`;

    this.ui.writeLine(description);
    this.analytics.track({
      name: 'server file changed',
      description,
    });
  }

  didAdd(relativePath) {
    let description = `File added: "${relativePath}"`;

    this.ui.writeLine(description);
    this.analytics.track({
      name: 'server file addition',
      description,
    });
  }

  didDelete(relativePath) {
    let description = `File deleted: "${relativePath}"`;

    this.ui.writeLine(description);
    this.analytics.track({
      name: 'server file deletion',
      description,
    });
  }
}

module.exports = ServerWatcher;


text:
package main

import (
	"sync/atomic"
	"unsafe"
)

func TaintStepTest_SyncAtomicAddUintptr_B0I0O0(sourceCQL interface{}) interface{} {
	fromUintptr656 := sourceCQL.(uintptr)
	var intoUintptr414 *uintptr
	atomic.AddUintptr(intoUintptr414, fromUintptr656)
	return intoUintptr414
}

func TaintStepTest_SyncAtomicAddUintptr_B0I0O1(sourceCQL interface{}) interface{} {
	fromUintptr518 := sourceCQL.(uintptr)
	intoUintptr650 := atomic.AddUintptr(nil, fromUintptr518)
	return intoUintptr650
}

func TaintStepTest_SyncAtomicCompareAndSwapPointer_B0I0O0(sourceCQL interface{}) interface{} {
	fromPointer784 := sourceCQL.(unsafe.Pointer)
	var intoPointer957 *unsafe.Pointer
	atomic.CompareAndSwapPointer(intoPointer957, nil, fromPointer784)
	return intoPointer957
}

func TaintStepTest_SyncAtomicCompareAndSwapUintptr_B0I0O0(sourceCQL interface{}) interface{} {
	fromUintptr520 := sourceCQL.(uintptr)
	var intoUintptr443 *uintptr
	atomic.CompareAndSwapUintptr(intoUintptr443, 0, fromUintptr520)
	return intoUintptr443
}

func TaintStepTest_SyncAtomicLoadPointer_B0I0O0(sourceCQL interface{}) interface{} {
	fromPointer127 := sourceCQL.(*unsafe.Pointer)
	intoPointer483 := atomic.LoadPointer(fromPointer127)
	return intoPointer483
}

func TaintStepTest_SyncAtomicLoadUintptr_B0I0O0(sourceCQL interface{}) interface{} {
	fromUintptr989 := sourceCQL.(*uintptr)
	intoUintptr982 := atomic.LoadUintptr(fromUintptr989)
	return intoUintptr982
}

func TaintStepTest_SyncAtomicStorePointer_B0I0O0(sourceCQL interface{}) interface{} {
	fromPointer417 := sourceCQL.(unsafe.Pointer)
	var intoPointer584 *unsafe.Pointer
	atomic.StorePointer(intoPointer584, fromPointer417)
	return intoPointer584
}

func TaintStepTest_SyncAtomicStoreUintptr_B0I0O0(sourceCQL interface{}) interface{} {
	fromUintptr991 := sourceCQL.(uintptr)
	var intoUintptr881 *uintptr
	atomic.StoreUintptr(intoUintptr881, fromUintptr991)
	return intoUintptr881
}

func TaintStepTest_SyncAtomicSwapPointer_B0I0O0(sourceCQL interface{}) interface{} {
	fromPointer186 := sourceCQL.(unsafe.Pointer)
	var intoPointer284 *unsafe.Pointer
	atomic.SwapPointer(intoPointer284, fromPointer186)
	return intoPointer284
}

func TaintStepTest_SyncAtomicSwapPointer_B1I0O0(sourceCQL interface{}) interface{} {
	fromPointer908 := sourceCQL.(*unsafe.Pointer)
	intoPointer137 := atomic.SwapPointer(fromPointer908, nil)
	return intoPointer137
}

func TaintStepTest_SyncAtomicSwapUintptr_B0I0O0(sourceCQL interface{}) interface{} {
	fromUintptr494 := sourceCQL.(uintptr)
	var intoUintptr873 *uintptr
	atomic.SwapUintptr(intoUintptr873, fromUintptr494)
	return intoUintptr873
}

func TaintStepTest_SyncAtomicSwapUintptr_B1I0O0(sourceCQL interface{}) interface{} {
	fromUintptr599 := sourceCQL.(*uintptr)
	intoUintptr409 := atomic.SwapUintptr(fromUintptr599, 0)
	return intoUintptr409
}

func TaintStepTest_SyncAtomicValueLoad_B0I0O0(sourceCQL interface{}) interface{} {
	fromValue246 := sourceCQL.(atomic.Value)
	intoInterface898 := fromValue246.Load()
	return intoInterface898
}

func TaintStepTest_SyncAtomicValueStore_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface598 := sourceCQL.(interface{})
	var intoValue631 atomic.Value
	intoValue631.Store(fromInterface598)
	return intoValue631
}

func TaintStepTest_SyncAtomicValueSwap(sourceCQL interface{}) interface{} {
	fromInterface598 := sourceCQL.(interface{})
	var intoValue631 atomic.Value
	intoValue631.Swap(fromInterface598)
	return intoValue631
}

func TaintStepTest_SyncAtomicValueSwap2(sourceCQL interface{}) interface{} {
	fromValue246 := sourceCQL.(atomic.Value)
	intoInterface898 := fromValue246.Swap("clean")
	return intoInterface898
}

func TaintStepTest_SyncAtomicPointerLoad_B0I0O0(sourceCQL interface{}) interface{} {
	fromValue246 := sourceCQL.(atomic.Pointer[string])
	intoInterface898 := fromValue246.Load()
	return intoInterface898
}

func TaintStepTest_SyncAtomicPointerStore_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface598 := sourceCQL.(*string)
	var intoValue631 atomic.Pointer[string]
	intoValue631.Store(fromInterface598)
	return intoValue631
}

func TaintStepTest_SyncAtomicPointerSwap(sourceCQL interface{}) interface{} {
	fromInterface598 := sourceCQL.(*string)
	var intoValue631 atomic.Pointer[string]
	intoValue631.Swap(fromInterface598)
	return intoValue631
}

func TaintStepTest_SyncAtomicPointerSwap2(sourceCQL interface{}) interface{} {
	fromValue246 := sourceCQL.(atomic.Pointer[string])
	clean := "Clean"
	intoInterface898 := fromValue246.Swap(&clean)
	return intoInterface898
}

func TaintStepTest_SyncAtomicUintptrLoad_B0I0O0(sourceCQL interface{}) interface{} {
	fromValue246 := sourceCQL.(atomic.Uintptr)
	intoInterface898 := fromValue246.Load()
	return intoInterface898
}

func TaintStepTest_SyncAtomicUintptrStore_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface598 := sourceCQL.(uintptr)
	var intoValue631 atomic.Uintptr
	intoValue631.Store(fromInterface598)
	return intoValue631
}

func TaintStepTest_SyncAtomicUintptrSwap(sourceCQL interface{}) interface{} {
	fromInterface598 := sourceCQL.(uintptr)
	var intoValue631 atomic.Uintptr
	intoValue631.Swap(fromInterface598)
	return intoValue631
}

func TaintStepTest_SyncAtomicUintptrSwap2(sourceCQL interface{}) interface{} {
	fromValue246 := sourceCQL.(atomic.Uintptr)
	clean := "Clean"
	intoInterface898 := fromValue246.Swap(uintptr(unsafe.Pointer(&clean)))
	return intoInterface898
}

func RunAllTaints_SyncAtomic() {
	{
		source := newSource(0)
		out := TaintStepTest_SyncAtomicAddUintptr_B0I0O0(source)
		sink(0, out)
	}
	{
		source := newSource(1)
		out := TaintStepTest_SyncAtomicAddUintptr_B0I0O1(source)
		sink(1, out)
	}
	{
		source := newSource(2)
		out := TaintStepTest_SyncAtomicCompareAndSwapPointer_B0I0O0(source)
		sink(2, out)
	}
	{
		source := newSource(3)
		out := TaintStepTest_SyncAtomicCompareAndSwapUintptr_B0I0O0(source)
		sink(3, out)
	}
	{
		source := newSource(4)
		out := TaintStepTest_SyncAtomicLoadPointer_B0I0O0(source)
		sink(4, out)
	}
	{
		source := newSource(5)
		out := TaintStepTest_SyncAtomicLoadUintptr_B0I0O0(source)
		sink(5, out)
	}
	{
		source := newSource(6)
		out := TaintStepTest_SyncAtomicStorePointer_B0I0O0(source)
		sink(6, out)
	}
	{
		source := newSource(7)
		out := TaintStepTest_SyncAtomicStoreUintptr_B0I0O0(source)
		sink(7, out)
	}
	{
		source := newSource(8)
		out := TaintStepTest_SyncAtomicSwapPointer_B0I0O0(source)
		sink(8, out)
	}
	{
		source := newSource(9)
		out := TaintStepTest_SyncAtomicSwapPointer_B1I0O0(source)
		sink(9, out)
	}
	{
		source := newSource(10)
		out := TaintStepTest_SyncAtomicSwapUintptr_B0I0O0(source)
		sink(10, out)
	}
	{
		source := newSource(11)
		out := TaintStepTest_SyncAtomicSwapUintptr_B1I0O0(source)
		sink(11, out)
	}
	{
		source := newSource(12)
		out := TaintStepTest_SyncAtomicValueLoad_B0I0O0(source)
		sink(12, out)
	}
	{
		source := newSource(13)
		out := TaintStepTest_SyncAtomicValueStore_B0I0O0(source)
		sink(13, out)
	}
	{
		source := newSource(14)
		out := TaintStepTest_SyncAtomicValueSwap(source)
		sink(14, out)
	}
	{
		source := newSource(15)
		out := TaintStepTest_SyncAtomicValueSwap2(source)
		sink(15, out)
	}
	{
		source := newSource(16)
		out := TaintStepTest_SyncAtomicPointerLoad_B0I0O0(source)
		sink(16, out)
	}
	{
		source := newSource(17)
		out := TaintStepTest_SyncAtomicPointerStore_B0I0O0(source)
		sink(17, out)
	}
	{
		source := newSource(18)
		out := TaintStepTest_SyncAtomicPointerSwap(source)
		sink(18, out)
	}
	{
		source := newSource(19)
		out := TaintStepTest_SyncAtomicPointerSwap2(source)
		sink(19, out)
	}
	{
		source := newSource(20)
		out := TaintStepTest_SyncAtomicUintptrLoad_B0I0O0(source)
		sink(20, out)
	}
	{
		source := newSource(21)
		out := TaintStepTest_SyncAtomicUintptrStore_B0I0O0(source)
		sink(21, out)
	}
	{
		source := newSource(22)
		out := TaintStepTest_SyncAtomicUintptrSwap(source)
		sink(22, out)
	}
	{
		source := newSource(23)
		out := TaintStepTest_SyncAtomicUintptrSwap2(source)
		sink(23, out)
	}
}


text:
// Karma configuration
// Generated on Thu Sep 24 2015 11:23:30 GMT-0700 (PDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
   // frameworks: ['mocha', 'chai', 'requirejs'],

    frameworks: ['mocha', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
      // angular source
      'public/bower_components/angular/angular.js',
      'public/bower_components/angular-mocks/angular-mocks.js',
      'tests/scripts/socket.io-1.3.5.js',

      // app code
      'public/js/**/*.js',

      // our spec files
      'tests/**/*Spec.js'
    ],

    // list of files to exclude
    exclude: [
      'karma.conf.js',
      'tests/protractor-tests/**/*'
    ],

    //plugins: ['karma-mocha', 'karma-requirejs', 'karma-chai'],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome', 'PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};


text:
var Packet   = require('./packets/packet.js');

function PacketParser(onPacket)
{
  // array of last payload chunks
  // only used when corrent payload is not complete
  this.buffer = [];
  // total length of chunks on buffer
  this.bufferLength = 0;

  // incomplete header state: number of header bytes received
  this.headerLen = 0;

  // expected payload length
  this.length     = 0;

  this.onPacket = onPacket;
  this.execute  = PacketParser.prototype.executeStart;
}

function readPacketLength(b,off) {
  var b0 = b[off];
  var b1 = b[off+1];
  var b2 = b[off+2];
  if (b1 + b2 === 0)
    return b0;
  return b0 + (b1<<8) + (b2<<16);
}

//
PacketParser.prototype.executeStart = function executeStart(chunk) {
  var start = 0;
  var end = chunk.length;
  // if (start-end === 0) return;

  while (end - start >= 3) {
    this.length = readPacketLength(chunk, start);
    if (end - start >= this.length + 4) { // at least one more full packet
      this.onPacket(new Packet(chunk[start+3], chunk, start + 4, start + 4 + this.length));
      start += 4 + this.length;
    } else { // payload is incomplete
      this.buffer = [chunk.slice(start + 3, end)];
      this.bufferLength = end - start - 3;
      this.execute = PacketParser.prototype.executePayload;
      return;
    }
  }
  if (end - start > 0) { // there is start of length header, but it's not full 3 bytes
    this.headerLen = end - start; // 1 or 2 bytes
    this.length = chunk[start];
    if (this.headerLen == 2) {
      this.length = chunk[start] + (chunk[start+1] << 8);
      this.execute = PacketParser.prototype.executeHeader3;
    } else {
      this.execute = PacketParser.prototype.executeHeader2;
    }
  }
}

PacketParser.prototype.executePayload = function executePayload(chunk) {
  var start = 0;
  var end = chunk.length;
  var remainingPayload = this.length - this.bufferLength + 1;

  if (end - start >= remainingPayload) { // last chunk for payload
    var payload = new Buffer(this.length + 1);
    var offset = 0;
    for (var i=0; i < this.buffer.length; ++i) {
      this.buffer[i].copy(payload, offset);
      offset += this.buffer[i].length;
    }
    chunk.copy(payload, offset, start, start + remainingPayload);
    this.onPacket(new Packet(payload[0], payload, 1, this.length + 1));
    this.buffer = [];
    this.bufferLength = 0;
    this.execute = PacketParser.prototype.executeStart;
    start += remainingPayload;
    if (end - start > 0)
      return this.execute(chunk.slice(start, end));
  } else {
    this.buffer.push(chunk);
    this.bufferLength += chunk.length;
  }
}

PacketParser.prototype.executeHeader2 = function executeHeader2(chunk) {
  this.length += chunk[0] << 8;
  if (chunk.length > 1) {
    this.length += chunk[1] << 16;
    this.execute = PacketParser.prototype.executePayload;
    return this.executePayload(chunk.slice(2));
  } else {
    this.execute = PacketParser.prototype.executeHeader3;
  }
}

PacketParser.prototype.executeHeader3 = function executeHeader3(chunk) {
  this.length += chunk[0] << 16;
  this.execute = PacketParser.prototype.executePayload;
  return this.executePayload(chunk.slice(1));
}

module.exports = PacketParser;


text:
import * as Delir from '@ragg/delir-core'

export interface ParameterTarget {
    type: 'clip' | 'effect'
    entityId: string
    paramName: string
}

export interface ClipboardEntry {
    type: 'clip'
    entityClone: any
}


text:
using System;
using UnityEngine;

namespace UnitySampleAssets.Water
{
    [ExecuteInEditMode]
    public class WaterTile : MonoBehaviour
    {
        public PlanarReflection reflection;
        public WaterBase waterBase;

        public void Start()
        {
            AcquireComponents();
        }

        void AcquireComponents()
        {
            if (!reflection)
            {
                if (transform.parent)
                {
                    reflection = transform.parent.GetComponent<PlanarReflection>();
                }
                else
                {
                    reflection = transform.GetComponent<PlanarReflection>();
                }
            }

            if (!waterBase)
            {
                if (transform.parent)
                {
                    waterBase = transform.parent.GetComponent<WaterBase>();
                }
                else
                {
                    waterBase = transform.GetComponent<WaterBase>();
                }
            }
        }

#if UNITY_EDITOR
        public void Update()
        {
            AcquireComponents();
        }
#endif

        public void OnWillRenderObject()
        {
            if (reflection)
            {
                reflection.WaterTileBeingRendered(transform, Camera.current);
            }
            if (waterBase)
            {
                waterBase.WaterTileBeingRendered(transform, Camera.current);
            }
        }
    }
}


text:
namespace util {
    namespace detail {
        struct rdtsc_struct {
            double cycle() const {
                return (uint64_t(hi) << 32) + lo;
            }
            uint32_t hi;
            uint32_t lo;
        };
        inline double operator-(rdtsc_struct const & end, rdtsc_struct const & begin) {
            return end.cycle() - begin.cycle();
        }
    }// end namespace detail

    class rdtsc_timer {
        using chrono_clock = std::chrono::high_resolution_clock;
    public:
        //--------------------------- methods ----------------------------------
        void start() {
            chrono_start_ = chrono_clock::now();
            asm volatile ("cpuid" : : "a" (0) : "bx", "cx", "dx" ); // CPUID exec-barrier
            asm volatile ("rdtsc" : "=a" ((cyc_start_).lo), "=d"((cyc_start_).hi)); // RDTSC
        }
        void stop() {
            asm volatile ("rdtsc" : "=a" ((cyc_stop_).lo), "=d"((cyc_stop_).hi)); // RDTSC
            asm volatile ("cpuid" : : "a" (0) : "bx", "cx", "dx" ); // CPUID exec-barrier
            chrono_stop_ = chrono_clock::now();
        }
        //------------------------- const methods ------------------------------
        double cycles() const {
            return cyc_stop_ - cyc_start_;
        }
        double sec() const {
            using sec_dur = std::chrono::duration<double, std::ratio<1, 1>>;
            auto res = std::chrono::duration_cast<sec_dur>(chrono_stop_ - chrono_start_);
            return res.count();
        }
        double usec() const {
            using usec_dur = std::chrono::duration<double, std::ratio<1, 1000000>>;
            auto res = std::chrono::duration_cast<usec_dur>(chrono_stop_ - chrono_start_);
            return res.count();
        }
        double nsec() const {
            using usec_dur = std::chrono::duration<double, std::ratio<1, 1000000000>>;
            auto res = std::chrono::duration_cast<usec_dur>(chrono_stop_ - chrono_start_);
            return res.count();
        }
    private:
        detail::rdtsc_struct cyc_start_, cyc_stop_;
        chrono_clock::time_point chrono_start_, chrono_stop_;
    };

    //------------------------- stream operator --------------------------------
    inline std::ostream & operator<<(std::ostream & os, rdtsc_timer const & arg) {
        os << "cycles measured with rdtsc:        " << arg.cycles() << " cycles" << std::endl;
        os << "time measured with high res clock: " << arg.sec() << " seconds";
        return os;
    }
} // end namespace util

#endif // UTIL_RDTSC_TIMER_HEADER


text:
"""
Python model "BusinessStructures.py"
Translated using PySD version 0.9.0
"""
from __future__ import division
import numpy as np
from pysd import utils
import xarray as xr

from pysd.py_backend.functions import cache
from pysd.py_backend import functions

_subscript_dict = {}

_namespace = {
    'TIME':
    'time',
    'Time':
    'time',
    'Actual Growth Rate':
    'actual_growth_rate',
    'Business Construction':
    'business_construction',
    'Business Demolition':
    'business_demolition',
    'Business Structures':
    'business_structures',
    'Demolition Fraction':
    'demolition_fraction',
    'Effect of Land Fraction Occupied on Growth Rate':
    'effect_of_land_fraction_occupied_on_growth_rate',
    'Initial Structures':
    'initial_structures',
    'Land Fraction Occupied':
    'land_fraction_occupied',
    'Land Required Per Business':
    'land_required_per_business',
    'Normal Growth Rate':
    'normal_growth_rate',
    'Total Available Land':
    'total_available_land',
    'FINAL TIME':
    'final_time',
    'INITIAL TIME':
    'initial_time',
    'SAVEPER':
    'saveper',
    'TIME STEP':
    'time_step'
}

__pysd_version__ = "0.9.0"

@cache('step')
def actual_growth_rate():
    """
    Real Name: b'Actual Growth Rate'
    Original Eqn: b'Normal Growth Rate*Effect of Land Fraction Occupied on Growth Rate'
    Units: b'1/Year'
    Limits: (None, None)
    Type: component

    b''
    """
    return normal_growth_rate() * effect_of_land_fraction_occupied_on_growth_rate()

@cache('step')
def business_construction():
    """
    Real Name: b'Business Construction'
    Original Eqn: b'Actual Growth Rate*Business Structures'
    Units: b'structure/Year'
    Limits: (None, None)
    Type: component

    b''
    """
    return actual_growth_rate() * business_structures()

@cache('step')
def business_demolition():
    """
    Real Name: b'Business Demolition'
    Original Eqn: b'Business Structures*Demolition Fraction'
    Units: b'structure/Year'
    Limits: (None, None)
    Type: component

    b''
    """
    return business_structures() * demolition_fraction()

@cache('step')
def business_structures():
    """
    Real Name: b'Business Structures'
    Original Eqn: b'INTEG ( Business Construction-Business Demolition, Initial Structures)'
    Units: b'structure'
    Limits: (None, None)
    Type: component

    b''
    """
    return integ_business_structures()

@cache('run')
def demolition_fraction():
    """
    Real Name: b'Demolition Fraction'
    Original Eqn: b'0.01'
    Units: b'1/Year'
    Limits: (None, None)
    Type: constant

    b''
    """
    return 0.01

@cache('step')
def effect_of_land_fraction_occupied_on_growth_rate():
    """
    Real Name: b'Effect of Land Fraction Occupied on Growth Rate'
    Original Eqn: b'1-Land Fraction Occupied'
    Units: b'Dmnl'
    Limits: (None, None)
    Type: component

    b''
    """
    return 1 - land_fraction_occupied()

@cache('run')
def initial_structures():
    """
    Real Name: b'Initial Structures'
    Original Eqn: b'1000'
    Units: b''
    Limits: (None, None)
    Type: constant

    b''
    """
    return 1000

@cache('step')
def land_fraction_occupied():
    """
    Real Name: b'Land Fraction Occupied'
    Original Eqn: b'Business Structures*Land Required Per Business/Total Available Land'
    Units: b'Dmnl'
    Limits: (None, None)
    Type: component

    b''
    """
    return business_structures() * land_required_per_business() / total_available_land()

@cache('run')
def land_required_per_business():
    """
    Real Name: b'Land Required Per Business'
    Original Eqn: b'0.2'
    Units: b'sqkm/structure'
    Limits: (None, None)
    Type: constant

    b''
    """
    return 0.2

@cache('run')
def normal_growth_rate():
    """
    Real Name: b'Normal Growth Rate'
    Original Eqn: b'0.13'
    Units: b'1/Year'
    Limits: (None, None)
    Type: constant

    b''
    """
    return 0.13

@cache('run')
def total_available_land():
    """
    Real Name: b'Total Available Land'
    Original Eqn: b'10000'
    Units: b'sqkm'
    Limits: (None, None)
    Type: constant

    b''
    """
    return 10000

@cache('run')
def final_time():
    """
    Real Name: b'FINAL TIME'
    Original Eqn: b'100'
    Units: b'Year'
    Limits: (None, None)
    Type: constant

    b'The final time for the simulation.'
    """
    return 100

@cache('run')
def initial_time():
    """
    Real Name: b'INITIAL TIME'
    Original Eqn: b'0'
    Units: b'Year'
    Limits: (None, None)
    Type: constant

    b'The initial time for the simulation.'
    """
    return 0

@cache('step')
def saveper():
    """
    Real Name: b'SAVEPER'
    Original Eqn: b'TIME STEP'
    Units: b'Year'
    Limits: (0.0, None)
    Type: component

    b'The frequency with which output is stored.'
    """
    return time_step()

@cache('run')
def time_step():
    """
    Real Name: b'TIME STEP'
    Original Eqn: b'0.125'
    Units: b'Year'
    Limits: (0.0, None)
    Type: constant

    b'The time step for the simulation.'
    """
    return 0.125

integ_business_structures = functions.Integ(
    lambda: business_construction() - business_demolition(), lambda: initial_structures())


text:
import TomSelect from './tom-select';
export default TomSelect;


text:
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>
            Informed Citizen

Search Bills

Legislator Info

User Home

My Bills

Admin

            <login-toolbar></login-toolbar>


text:
{-# OPTIONS_GHC -Wall -fno-warn-name-shadowing #-}
{-# LANGUAGE RankNTypes, ScopedTypeVariables, GADTs, EmptyDataDecls, PatternGuards, TypeFamilies, NamedFieldPuns , FlexibleInstances, MultiParamTypeClasses, TypeSynonymInstances #-}

module Eval (evalProg, ErrorM) where

import Control.Monad.Error
import qualified Data.Map    as M
import Prelude hiding (succ)

import EvalMonad
import Compiler.Hoopl
import IR

-- Evaluation functions
evalProg :: EvalTarget v => [Proc] -> [v] -> String -> [v] -> ErrorM (State v, [v])
evalProg procs vs main args = runProg procs vs $ evalProc main args

evalProc :: EvalTarget v => String -> [v] -> EvalM v [v]
evalProc proc_name actuals =
  do event $ CallEvt proc_name actuals
     proc <- get_proc proc_name
     evalProc' proc actuals
evalProc' :: EvalTarget v => Proc -> [v] -> EvalM v [v]
evalProc' (Proc {name=_, args, body, entry}) actuals =
  if length args == length actuals then
    evalBody (M.fromList $ zip args actuals) body entry
  else throwError $ "Param/actual mismatch: " ++ show args ++ " = " ++ show actuals

-- Responsible for allocating and deallocating its own stack frame.
evalBody :: EvalTarget v => VarEnv v -> Graph Insn C C -> Label -> EvalM v [v]
evalBody vars graph entry = inNewFrame vars graph $ get_block entry >>= evalB

evalB :: forall v . EvalTarget v => Block Insn C C -> EvalM v [v]
evalB b = foldBlockNodesF3 (lift evalF, lift evalM, lift evalL) b $ return ()
  where
    lift :: forall e x y . (Insn e x -> EvalM v y) -> Insn e x -> EvalM v () -> EvalM v y
    lift f n z = z >> f n

evalF :: EvalTarget v => Insn C O -> EvalM v ()
evalF (Label _) = return ()

evalM :: EvalTarget v => Insn O O -> EvalM v ()
evalM (Assign var e) =
  do v_e <- eval e
     set_var var v_e
evalM (Store addr e) =
  do v_addr <- eval addr >>= toAddr
     v_e    <- eval e
     -- StoreEvt recorded in set_heap
     set_heap v_addr v_e

evalL :: EvalTarget v => Insn O C -> EvalM v [v]
evalL (Branch bid) =
  do b <- get_block bid
     evalB b
evalL (Cond e t f) =
  do v_e <- eval e >>= toBool
     evalL $ Branch $ if v_e then t else f
evalL (Call ress f args succ) =
  do v_args <- mapM eval args
     -- event is recorded in evalProc
     f_ress <- evalProc f v_args
     if length ress == length f_ress then return ()
      else throwError $ "function " ++ f ++ " returned unexpected # of args"
     _ <- mapM (uncurry set_var) $ zip ress f_ress
     evalL $ Branch succ
evalL (Return es) =
  do vs <- mapM eval es
     event $ RetEvt vs
     return vs

class Show v => EvalTarget v where
  toAddr :: v    -> EvalM v Integer
  toBool :: v    -> EvalM v Bool
  eval   :: Expr -> EvalM v v

instance EvalTarget Value where
  toAddr (I i) = return i
  toAddr (B _) = throwError "conversion to address failed"
  toBool (B b) = return b
  toBool (I _) = throwError "conversion to bool failed"
  eval (Lit (Int  i)) = return $ I i
  eval (Lit (Bool b)) = return $ B b
  eval (Var var) = get_var var
  eval (Load addr) =
    do v_addr <- eval addr >>= toAddr
       get_heap v_addr
  eval (Binop bop e1 e2) =
    do v1 <- eval e1
       v2 <- eval e2
       liftBinOp bop v1 v2
    where
      liftBinOp = liftOp
        where liftOp Add  = i (+)
              liftOp Sub  = i (-)
              liftOp Mul  = i (*)
              liftOp Div  = i div
              liftOp Eq   = b (==)
              liftOp Ne   = b (/=)
              liftOp Gt   = b (>)
              liftOp Lt   = b (<)
              liftOp Gte  = b (>=)
              liftOp Lte  = b (<=)
              i = liftX I fromI
              b = liftX B fromB

              liftX :: Monad m => (a -> b) -> (b -> m a) -> (a -> a -> a) -> b -> b -> m b
              liftX up dwn = \ op x y -> do v_x <- dwn x
                                            v_y <- dwn y
                                            return $ up $ op v_x v_y
              fromI (I x) = return x
              fromI (B _) = throwError "fromI: got a B"

              fromB (I _) = throwError "fromB: got an I"
              fromB (B x) = return x

-- I'm under no delusion that the following example is useful,
-- but it demonstrates how the evaluator can use a new kind
-- of evaluator.
instance EvalTarget Integer where
  toAddr i = return i
  toBool i = return $ i /= 0
  eval (Lit (Int i)) = return i
  eval (Lit (Bool True)) = return 1
  eval (Lit (Bool False)) = return 0
  eval (Var var) = get_var var
  eval (Load addr) =
    do v_addr <- eval addr >>= toAddr
       get_heap v_addr
  eval (Binop bop e1 e2) =
    do v1 <- eval e1
       v2 <- eval e2
       return $ liftBinOp bop v1 v2
    where
      liftBinOp = liftOp
        where liftOp Add  = i (+)
              liftOp Sub  = i (-)
              liftOp Mul  = i (*)
              liftOp Div  = i div
              liftOp Eq   = b (==)
              liftOp Ne   = b (/=)
              liftOp Gt   = b (>)
              liftOp Lt   = b (<)
              liftOp Gte  = b (>=)
              liftOp Lte  = b (<=)
              i = id
              b opr x y = if opr x y then 1 else 0

-- Symbolic evaluation.
-- Hard questions:
--  - how do we get heap addresses?
--  - how do we get conditionals?
--  - how do we compare symbolic expressions?
data Sym = L  Lit
         | In Integer -- In x indicates a value on entry to the program
         | Ld Sym
         | BO BinOp Sym Sym
  deriving Show
-- sym_vsupply :: [Sym]
-- sym_vsupply = [In n | n <- [0..]]

instance EvalTarget Sym where
  toAddr _ = undefined
  toBool _ = undefined
  eval (Lit l) = return $ L l
  eval (Var var) = get_var var
  eval (Load addr) =
    do v_addr <- eval addr >>= toAddr
       get_heap v_addr
  eval (Binop bop e1 e2) =
    do v1 <- eval e1
       v2 <- eval e2
       return $ BO bop v1 v2


text:
package org.apache.accumulo.core.spi.file.rfile.compression;

public interface CompressionAlgorithmConfiguration {

  /**
   * @return algorithm alias
   */
  String getName();

  /**
   * @return name of property that can be specified in configuration or in system properties to
   *         override class name of codec
   */
  String getCodecClassName();

  /**
   * @return fully qualified class name of codec
   */
  String getCodecClassNameProperty();

  /**
   * @return default buffer size for compression algorithm
   */
  int getDefaultBufferSize();

  /**
   * @return name of property that can be specified in configuration or in system properties to
   *         override default buffer size
   */
  String getBufferSizeProperty();

  /**
   * @return true if codecs with non-default buffer sizes should be cached
   */
  default boolean cacheCodecsWithNonDefaultSizes() {
    return false;
  }

}


text:
class FacultyReview < ActiveRecord::Base
  attr_accessible :content, :review_mapping_id

  has_one :review_mapping

end


text:
<!DOCTYPE html>

  <title>Matthew Chan| Web Developer</title>
  <link rel="stylesheet" type="text/css" href="./stylesheets/blog_template.css">
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
  <link href='http://fonts.googleapis.com/css?family=Lora' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

        home
        about
        blog
        projects
        resources

Marionette.js

Marionette + Backbone

Backbone is unopinionated and trying to figure out what function belongs to which component and how to modularize your code(as you'll have alot of boilerplate for your various views, models, and collections) can be a pain. Enter Marionette.js, a composite application framework built for Backbone.js.

Marionette will...

allow you to scale Backbone applications.

Eliminate boilerplate view code with specialized views.

Give more components than the standard that comes with Backbone.

Below is a visualization of the components found in Backbone vs. Marionette.


text:
//
//  AppCell.m
//  ASiST
//
//  Created by Oliver Drobnik on 12.01.09.
//  Copyright 2009 drobnik.com. All rights reserved.
//

#import "AppCell.h"
#import "App.h"
#import "ASiSTAppDelegate.h"
#import "Report_v1.h"
#import "YahooFinance.h"
#import "BadgeView.h"

@implementation AppCell

@synthesize app;

#define LEFT_COLUMN_OFFSET 75.0
#define RIGHT_MARGIN 10.0
#define VERTICAL_MARGIN 8.0
#define MAIN_FONT_SIZE 14.0

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = TABLEVIEWCELL_PLAIN_INIT)
	{
		// create label views to contain the various pieces of text that make up the cell.
		// Add these as subviews.
		appTitleLabel = [[UILabel alloc] initWithFrame:CGRectZero];	// layoutSubViews will decide the final frame
		//appTitleLabel.backgroundColor = [UIColor clearColor];  // otherwise it's in a white box
		appTitleLabel.font = [UIFont boldSystemFontOfSize:MAIN_FONT_SIZE + 4.0];
		appTitleLabel.shadowColor = [UIColor whiteColor];
		appTitleLabel.shadowOffset = CGSizeMake(0, 1);
		[self.contentView addSubview:appTitleLabel];

		UIFont *smallerFont = [UIFont systemFontOfSize:14.0];
		UIColor *darkColor = [UIColor colorWithRed:58.0/256.0 green:58.0/256.0 blue:58.0/256.0 alpha:1.0];
		//UIColor *darkShadowColor = [UIColor colorWithRed:145.0/256.0 green:145.0/256.0 blue:145.0/256.0 alpha:1.0];

		subTextLabel = [[UILabel alloc] initWithFrame:CGRectZero];	// layoutSubViews will decide the final frame
		subTextLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
		//subTextLabel.backgroundColor = [UIColor clearColor];
		subTextLabel.textColor = darkColor; //[UIColor colorWithWhite:0.3 alpha:1.0];
		//subTextLabel.shadowColor = darkShadowColor;
		//subTextLabel.shadowOffset = CGSizeMake(1, 1);
		subTextLabel.adjustsFontSizeToFitWidth = YES;
		subTextLabel.font = smallerFont;
		[self.contentView addSubview:subTextLabel];

		royaltiesLabel = [[UILabel alloc] initWithFrame:CGRectZero];	// layoutSubViews will decide the final frame
		royaltiesLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
		royaltiesLabel.backgroundColor = [UIColor clearColor];
		royaltiesLabel.textColor = darkColor; //[UIColor colorWithWhite:0.3 alpha:1.0];
		//royaltiesLabel.shadowColor = darkShadowColor;
		//royaltiesLabel.shadowOffset = CGSizeMake(1, 1);
		royaltiesLabel.adjustsFontSizeToFitWidth = YES;
		royaltiesLabel.textAlignment = UITextAlignmentRight;
		royaltiesLabel.font = smallerFont;
		[self.contentView addSubview:royaltiesLabel];

		totalUnitsLabel = [[UILabel alloc] initWithFrame:CGRectZero];	// layoutSubViews will decide the final frame
		totalUnitsLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
		totalUnitsLabel.backgroundColor = [UIColor clearColor];
		totalUnitsLabel.textColor = darkColor; //[UIColor colorWithWhite:0.3 alpha:1.0];
		//totalUnitsLabel.shadowColor = darkShadowColor;
		//totalUnitsLabel.shadowOffset = CGSizeMake(1, 1);
		totalUnitsLabel.adjustsFontSizeToFitWidth = YES;
		totalUnitsLabel.font = smallerFont;
		[self.contentView addSubview:totalUnitsLabel];

		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emptyCache:) name:@"EmptyCache" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appReviewsUpdated:) name:@"AppReviewsUpdated" object:nil];

		badge = [[BadgeView alloc] initWithFrame:CGRectMake(40, 5, 40, 30)];
		//badge.center = CGPointMake(60, 60);
		[self addSubview:badge];  //naughty: we want to be above the standard imageview

    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)layoutSubviews
{
	[super layoutSubviews];
    CGRect contentRect = [self.contentView bounds];

	CGFloat lineHeight = (contentRect.size.height - VERTICAL_MARGIN*2.0)/3.0;

	appTitleLabel.frame = CGRectMake(contentRect.origin.x + LEFT_COLUMN_OFFSET, contentRect.origin.y + VERTICAL_MARGIN,  contentRect.size.width -  LEFT_COLUMN_OFFSET - RIGHT_MARGIN, lineHeight);
	subTextLabel.frame = CGRectMake(contentRect.origin.x + LEFT_COLUMN_OFFSET, contentRect.origin.y+lineHeight + VERTICAL_MARGIN,  contentRect.size.width -  LEFT_COLUMN_OFFSET - RIGHT_MARGIN, lineHeight);
	CGFloat width = (contentRect.size.width -  LEFT_COLUMN_OFFSET - RIGHT_MARGIN - 5.0);
	royaltiesLabel.frame = CGRectMake(contentRect.origin.x + LEFT_COLUMN_OFFSET + width*0.6, contentRect.origin.y+2.0*lineHeight + VERTICAL_MARGIN,  width*0.4, lineHeight);
	totalUnitsLabel.frame = CGRectMake(contentRect.origin.x + LEFT_COLUMN_OFFSET, contentRect.origin.y+2.0*lineHeight + VERTICAL_MARGIN,  width*0.6, lineHeight);

  self.imageView.frame = CGRectMake(9.0, 9.0, 56.0, 56.0);
}

- (void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[royaltiesLabel release];
	[totalUnitsLabel release];
	[appTitleLabel release];
	[subTextLabel release];
	[app release];

    [super dealloc];
}

- (App *)app
{
	return app;
}

- (void)setBackgroundColor:(UIColor *)newColor
{
	[super setBackgroundColor:newColor];
	appTitleLabel.backgroundColor = newColor;
	royaltiesLabel.backgroundColor = newColor;
	totalUnitsLabel.backgroundColor = newColor;
	subTextLabel.backgroundColor = newColor;
}

- (void)setBadge
{
	if (app.countNewReviews)
	{
		badge.text = [NSString stringWithFormat:@"%d", app.countNewReviews];
		CGRect frame = badge.frame;
		frame.origin.x = 74.0 - frame.size.width;
		badge.frame = frame;
		badge.hidden = NO;
	}
	else
	{
		badge.hidden = YES;
	}
}

- (void) showDisclosureIndicatorIfNeeded
{
	// show disclosure indicator if there are reviews

	// always show for now, we don't want to trigger loading of reviews
	self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

	/*
	if ([app.reviews count])
	{
		self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}
	else
	{
		self.accessoryType = UITableViewCellAccessoryNone;
	}
	 */
}

- (void)setApp:(App *)inApp
{
	//if (self.app != inApp)  // would prevent update for main currency change
	{
		[app release];
		app = [inApp retain];

		appTitleLabel.text = app.title;

		double converted = [[YahooFinance sharedInstance] convertToCurrency:[[YahooFinance sharedInstance] mainCurrency] amount:app.averageRoyaltiesPerDay fromCurrency:@"EUR"];
		subTextLabel.text = [NSString stringWithFormat:@"%@ per day", [[YahooFinance sharedInstance]  formatAsCurrency:[[YahooFinance sharedInstance] mainCurrency] amount:converted]];

		double royalties_converted = [[YahooFinance sharedInstance] convertToCurrency:[[YahooFinance sharedInstance] mainCurrency] amount:app.totalRoyalties fromCurrency:@"EUR"];
		if (royalties_converted)
		{
			royaltiesLabel.text = [NSString stringWithFormat:@"%0@", [[YahooFinance sharedInstance] formatAsCurrency:[[YahooFinance sharedInstance] mainCurrency] amount:royalties_converted]];
			totalUnitsLabel.text = [NSString stringWithFormat:@"%d sold", app.totalUnits];
		}
		else
		{
			royaltiesLabel.text = @"free";
			totalUnitsLabel.text = [NSString stringWithFormat:@"%d downloaded", app.totalUnits];
		}

		[self setBadge];

		if (app.iconImage)
		{
			self.CELL_IMAGE = app.iconImage;
		}
		else
		{
			self.CELL_IMAGE = [UIImage imageNamed:@"Empty.png"];
		}

		[self showDisclosureIndicatorIfNeeded];

	}
}

#pragma mark Notifications
- (void)emptyCache:(NSNotification *) notification
{
	self.CELL_IMAGE = nil;
}

- (void)appReviewsUpdated:(NSNotification *)notifications
{
	[self setBadge];
	[self showDisclosureIndicatorIfNeeded];

	//[self setNeedsDisplay];
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotVVM.Framework.ViewModel;
using SnowFur.BL.Facades;
using SnowFur.BL.Dtos;
using DotVVM.Framework.Controls;

namespace SnowFur.ViewModels
{
	public class Attendees : PageViewModelBase
	{
        private ConventionInfoFacade infoFacade;

        public GridViewDataSet<AttendeeListItemDto> AttendeeDataSet { get; set; }
            = new GridViewDataSet<AttendeeListItemDto>() {
                SortExpression = nameof(AttendeeListItemDto.Count),
                PageSize = 60
            };

        public Attendees(ConventionInfoFacade infoFacade)
        {
            this.infoFacade = infoFacade;

            SubpageTitle = "Účastnici";
            RabitBackgroundCssClass = "sf-bg-ucastnici";
        }

        public override Task PreRender()
        {
            infoFacade.FillAttendees(AttendeeDataSet);

            return base.PreRender();
        }
    }
}