text:
package org.devgateway.toolkit.persistence.excel;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.devgateway.toolkit.persistence.excel.annotation.ExcelExport;
import org.devgateway.toolkit.persistence.excel.info.ClassFields;
import org.devgateway.toolkit.persistence.excel.info.ClassFieldsDefault;
import org.devgateway.toolkit.persistence.excel.info.ClassFieldsExcelExport;
import org.devgateway.toolkit.persistence.excel.service.TranslateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Persistable;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author idobre
 * @since 10/11/2017
 */
public final class ExcelFieldService {
    private static final Logger logger = LoggerFactory.getLogger(ExcelFieldService.class);

    private static Map<Field, FieldType> fieldsTypeCache;

    private static Map<Field, Class> fieldsClassCache;

    private static Map<Class, List<Field>> fieldsCache;

    static {
        fieldsTypeCache = new HashMap<>();
        fieldsClassCache = new HashMap<>();
        fieldsCache = new HashMap<>();
    }

    /**
     * Utility classes should not have a public or default constructor.
     */
    private ExcelFieldService() {

    }

    /**
     * Return the {@link FieldType} of a Field
     * This is used to determine the writing strategy for this particular field.
     *
     * @param field
     * @return {@link FieldType}
     */
    public static FieldType getFieldType(final Field field) {
        FieldType fieldType;

        if (fieldsTypeCache.get(field) != null) {
            fieldType = fieldsTypeCache.get(field);
        } else {
            fieldType = FieldType.basic;        // default field type
            final Class fieldClass = getFieldClass(field);

            // first we check if we have a basic type
            if (FieldType.BASICTYPES.contains(fieldClass) || fieldClass.isEnum()) {
                fieldType = FieldType.basic;
            } else {
                final ExcelExport excelExport = field.getAnnotation(ExcelExport.class);
                if (excelExport != null) {
                    fieldType = FieldType.object;

                    // if we just want to export a field (toString) we consider it a basic type.
                    if (excelExport.justExport()) {
                        fieldType = FieldType.basic;
                    }

                    // check if we want to export the object in a separate sheet
                    if (excelExport.separateSheet()) {
                        fieldType = FieldType.objectSeparateSheet;
                    }
                }
            }

            fieldsTypeCache.put(field, fieldType);
        }

        return fieldType;
    }

    /**
     * Return the Class of a field.
     *
     * @param field
     * @return {@link Class}
     */
    public static Class getFieldClass(final Field field) {
        Class fieldClass = null;

        if (fieldsClassCache.get(field) != null) {
            fieldClass = fieldsClassCache.get(field);
        } else {
            if (isCollection(field)) {
                final ParameterizedType genericListType = (ParameterizedType) field.getGenericType();
                try {
                    fieldClass = Class.forName(genericListType.getActualTypeArguments()[0].getTypeName());
                } catch (ClassNotFoundException e) {
                    logger.error("getFieldClass Error!", e);
                }
            } else {
                fieldClass = field.getType();
            }

            fieldsClassCache.put(field, fieldClass);
        }

        return fieldClass;
    }

    /**
     * Returns an Iterator with the Fields of a Class.
     * The fields are filtered with the {@link ClassFieldsExcelExport} class.
     *
     * @param clazz
     * @return {@link Iterator}
     */
    public static Iterator<Field> getFields(final Class clazz) {
        final Iterator<Field> fields;

        if (fieldsCache.get(clazz) != null) {
            final List<Field> fieldsList = fieldsCache.get(clazz);
            fields = fieldsList.iterator();
        } else {
            final ClassFields classFields = new ClassFieldsExcelExport(new ClassFieldsDefault(clazz, true));
            fields = classFields.getFields();

            fieldsCache.put(clazz, Lists.newArrayList(classFields.getFields()));
        }

        return fields;
    }

    /**
     * Get the ID for an Entity - {@link Persistable}.
     *
     * Return -1 if everything wrong happened.
     *
     * @param object
     * @return Entity ID
     */
    public static Long getObjectID(final Object object) {
        Long objectId = Long.valueOf(-1);

        if (object == null || !(Persistable.class.isAssignableFrom(object.getClass()))) {
            return Long.valueOf(-1);
        }

        try {
            final Method idMethod = object.getClass().getMethod("getId");
            if (idMethod != null) {
                objectId = (Long) idMethod.invoke(object);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            logger.error("getObjectID error", e);
        }

        return objectId;
    }

    /**
     * Returns the name that we should use as a header for this {@link Field}.
     *
     * @param field
     */
    public static String getFieldName(final Class clazz, final Field field, final TranslateService translateService) {
        final ExcelExport excelExport = field.getAnnotation(ExcelExport.class);
        if (excelExport != null) {
            String label = null;
            if (excelExport.useTranslation()) {
                label = translateService.getTranslation(clazz, field);
            }
            if (!excelExport.name().isEmpty()) {
                if (StringUtils.isEmpty(label)) {
                    return excelExport.name();
                } else {
                    return excelExport.name() + " - " + label;
                }

            }
        }

        return field.getName();
    }

    /**
     * Returns the onlyForClass prop of the {@link Field}.
     *
     * @param field
     */
    public static Class[] getFieldClazz(final Field field) {
        final ExcelExport excelExport = field.getAnnotation(ExcelExport.class);
        if (excelExport != null) {
            if (excelExport.onlyForClass().length != 0
                    && !excelExport.onlyForClass()[0].getSimpleName().equals("void")) {
                return excelExport.onlyForClass();
            }
        }

        return null;
    }

    /**
     * Check if a {@link Field} Type is a Collection.
     *
     * @param field
     * @return {@link Boolean}
     */
    public static Boolean isCollection(final Field field) {
        return field.getType().equals(java.util.Collection.class)
                || field.getType().equals(java.util.Set.class)
                || field.getType().equals(java.util.List.class);
    }
}


text:
module Maptastic
  module Generators
    class UpdateGenerator < Rails::Generators::Base #:nodoc:
      desc "Updates the required javascript files."

      def self.source_root
        File.expand_path("../../templates", __FILE__)
      end

      def copy_javascripts
        remove_file "public/javascripts/maptastic.js"
        copy_file "maptastic.js", "public/javascripts/maptastic.js"
      end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
//javascript对storage进行增删改查的操作
var storageHelper = function () {
}

storageHelper.addStorage = function (key, value, isSession) {
    switch (typeof value) {
        case "object":
            value = JSON.stringify(value);
            break;
    }

    storageHelper.delStorage(key);
    if (isSession) {
        sessionStorage.setItem(key, value);
    }
    else {
        localStorage.setItem(key, value);
    }
}

storageHelper.getStorage = function (key) {
    var result = "";
    var localValue = localStorage.getItem(key);
    switch (localValue) {
        case null:
            result = sessionStorage.getItem(key);
            break;
        default:
            result = localValue;
            break;
    }

    try {
        return eval("(" + result + ")");
    }
    catch (e) {
        return result;
    }
}

storageHelper.delStorage = function (key) {
    switch (localStorage.getItem(key)) {
        case null:
            return sessionStorage.removeItem(key);
            break;
        default:
            return localStorage.removeItem(key);
            break;
    }
}


text:
class WithOnStatic {
	static boolean foo;
	static int bar;
}


text:
package org.apache.flink.table.runtime.operators.sort;

import org.apache.flink.api.common.typeutils.base.NormalizedKeyUtil;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.table.data.DecimalData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
import org.apache.flink.table.data.binary.BinaryStringData;

import java.nio.ByteOrder;

import static org.apache.flink.core.memory.MemoryUtils.UNSAFE;

/**
 * Util for sort.
 */
public class SortUtil {

	private static final int BYTE_ARRAY_BASE_OFFSET = UNSAFE.arrayBaseOffset(byte[].class);
	private static final boolean LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN;
	private static final int LONG_BYTES = 8;

	public static void minNormalizedKey(MemorySegment target, int offset, int numBytes) {
		//write min value.
		for (int i = 0; i < numBytes; i++) {
			target.put(offset + i, (byte) 0);
		}
	}

	/**
	 * Max unsigned byte is -1.
	 */
	public static void maxNormalizedKey(MemorySegment target, int offset, int numBytes) {
		//write max value.
		for (int i = 0; i < numBytes; i++) {
			target.put(offset + i, (byte) -1);
		}
	}

	public static void putShortNormalizedKey(short value, MemorySegment target, int offset,
			int numBytes) {
		NormalizedKeyUtil.putShortNormalizedKey(value, target, offset, numBytes);
	}

	public static void putByteNormalizedKey(byte value, MemorySegment target, int offset,
			int numBytes) {
		NormalizedKeyUtil.putByteNormalizedKey(value, target, offset, numBytes);
	}

	public static void putBooleanNormalizedKey(boolean value, MemorySegment target, int offset,
			int numBytes) {
		NormalizedKeyUtil.putBooleanNormalizedKey(value, target, offset, numBytes);
	}

	/**
	 * UTF-8 supports bytes comparison.
	 */
	public static void putStringNormalizedKey(
			StringData value, MemorySegment target, int offset, int numBytes) {
		BinaryStringData binaryString = (BinaryStringData) value;
		final int limit = offset + numBytes;
		final int end = binaryString.getSizeInBytes();
		for (int i = 0; i < end && offset < limit; i++) {
			target.put(offset++, binaryString.byteAt(i));
		}

		for (int i = offset; i < limit; i++) {
			target.put(i, (byte) 0);
		}
	}

	/**
	 * Just support the compact precision decimal.
	 */
	public static void putDecimalNormalizedKey(
			DecimalData record, MemorySegment target, int offset, int len) {
		assert record.isCompact();
		putLongNormalizedKey(record.toUnscaledLong(), target, offset, len);
	}

	public static void putIntNormalizedKey(int value, MemorySegment target, int offset, int numBytes) {
		NormalizedKeyUtil.putIntNormalizedKey(value, target, offset, numBytes);
	}

	public static void putLongNormalizedKey(long value, MemorySegment target, int offset,
			int numBytes) {
		NormalizedKeyUtil.putLongNormalizedKey(value, target, offset, numBytes);
	}

	/**
	 * See http://stereopsis.com/radix.html for more details.
	 */
	public static void putFloatNormalizedKey(float value, MemorySegment target, int offset,
			int numBytes) {
		int iValue = Float.floatToIntBits(value);
		iValue ^= ((iValue >> (Integer.SIZE - 1)) | Integer.MIN_VALUE);
		NormalizedKeyUtil.putUnsignedIntegerNormalizedKey(iValue, target, offset, numBytes);
	}

	/**
	 * See http://stereopsis.com/radix.html for more details.
	 */
	public static void putDoubleNormalizedKey(double value, MemorySegment target, int offset,
			int numBytes) {
		long lValue = Double.doubleToLongBits(value);
		lValue ^= ((lValue >> (Long.SIZE - 1)) | Long.MIN_VALUE);
		NormalizedKeyUtil.putUnsignedLongNormalizedKey(lValue, target, offset, numBytes);
	}

	public static void putBinaryNormalizedKey(
			byte[] value, MemorySegment target, int offset, int numBytes) {
		final int limit = offset + numBytes;
		final int end = value.length;
		for (int i = 0; i < end && offset < limit; i++) {
			target.put(offset++, value[i]);
		}

		for (int i = offset; i < limit; i++) {
			target.put(i, (byte) 0);
		}
	}

	/**
	 * Support the compact precision TimestampData.
	 */
	public static void putTimestampNormalizedKey(
			TimestampData value, MemorySegment target, int offset, int numBytes) {
		assert value.getNanoOfMillisecond() == 0;
		putLongNormalizedKey(value.getMillisecond(), target, offset, numBytes);
	}

	public static int compareBinary(byte[] a, byte[] b) {
		return compareBinary(a, 0, a.length, b, 0, b.length);
	}

	public static int compareBinary(
			byte[] buffer1, int offset1, int length1,
			byte[] buffer2, int offset2, int length2) {
		// Short circuit equal case
		if (buffer1 == buffer2 &&
				offset1 == offset2 &&
				length1 == length2) {
			return 0;
		}
		int minLength = Math.min(length1, length2);
		int minWords = minLength / LONG_BYTES;
		int offset1Adj = offset1 + BYTE_ARRAY_BASE_OFFSET;
		int offset2Adj = offset2 + BYTE_ARRAY_BASE_OFFSET;

        /*
         * Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a
         * time is no slower than comparing 4 bytes at a time even on 32-bit.
         * On the other hand, it is substantially faster on 64-bit.
         */
		for (int i = 0; i < minWords * LONG_BYTES; i += LONG_BYTES) {
			long lw = UNSAFE.getLong(buffer1, offset1Adj + (long) i);
			long rw = UNSAFE.getLong(buffer2, offset2Adj + (long) i);
			long diff = lw ^ rw;

			if (diff != 0) {
				if (!LITTLE_ENDIAN) {
					return lessThanUnsigned(lw, rw) ? -1 : 1;
				}

				// Use binary search
				int n = 0;
				int y;
				int x = (int) diff;
				if (x == 0) {
					x = (int) (diff >>> 32);
					n = 32;
				}

				y = x << 16;
				if (y == 0) {
					n += 16;
				} else {
					x = y;
				}

				y = x << 8;
				if (y == 0) {
					n += 8;
				}
				return (int) (((lw >>> n) & 0xFFL) - ((rw >>> n) & 0xFFL));
			}
		}

		// The epilogue to cover the last (minLength % 8) elements.
		for (int i = minWords * LONG_BYTES; i < minLength; i++) {
			int result = unsignedByteToInt(buffer1[offset1 + i]) -
					unsignedByteToInt(buffer2[offset2 + i]);
			if (result != 0) {
				return result;
			}
		}
		return length1 - length2;
	}

	private static int unsignedByteToInt(byte value) {
		return value & 0xff;
	}

	private static boolean lessThanUnsigned(long x1, long x2) {
		return (x1 + Long.MIN_VALUE) < (x2 + Long.MIN_VALUE);
	}
}


text:
export const handleJSON = res => {
  return error => {
    console.error(error.stack || error)

    if (!('customError' in error)) error = { message: 'An unknown server error occured.' }

    res.json({ success: false, error })
  }
}


text:
using System;
namespace Practice.DataStructures
{
    public class TreeNode<T>
    {
        public T key;
        public TreeNode<T> Left;
        public TreeNode<T> Right;

        public TreeNode(T key)
        {
            this.key = key;
            Left = Right = null;
        }
    }
}


text:
require "securerandom"

module Ed25519
  # Private key for producing digital signatures
  class SigningKey
    attr_reader :seed, :keypair, :verify_key

    # Generate a random Ed25519 signing key (i.e. private scalar)
    def self.generate
      new SecureRandom.random_bytes(Ed25519::KEY_SIZE)
    end

    # Create a SigningKey from a 64-byte Ed25519 keypair (i.e. public + private)
    #
    # @param keypair [String] 64-byte keypair value containing both seed + public key
    def self.from_keypair(keypair)
      raise TypeError, "expected String, got #{keypair.class}" unless keypair.is_a?(String)
      raise ArgumentError, "expected 64-byte String, got #{keypair.bytesize}" unless keypair.bytesize == 64

      new(keypair[0, KEY_SIZE]).tap do |key|
        raise ArgumentError, "corrupt keypair" unless keypair[KEY_SIZE, KEY_SIZE] == key.verify_key.to_bytes
      end
    end

    # Create a new Ed25519::SigningKey from the given seed value
    #
    # @param seed [String] 32-byte seed value from which the key should be derived
    def initialize(seed)
      Ed25519.validate_key_bytes(seed)

      @seed = seed
      @keypair = Ed25519.provider.create_keypair(seed)
      @verify_key = VerifyKey.new(@keypair[32, 32])
    end

    # Sign the given message, returning an Ed25519 signature
    #
    # @param message [String] message to be signed
    #
    # @return [String] 64-byte Ed25519 signature
    def sign(message)
      Ed25519.provider.sign(@keypair, message)
    end

    # String inspection that does not leak secret values
    def inspect
      to_s
    end

    # Return a bytestring representation of this signing key
    #
    # @return [String] signing key converted to a bytestring
    def to_bytes
      seed
    end
    alias to_str to_bytes
  end
end


text:
			<img  src="<?php echo base_url('images/logo.png')?>">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

			</button>
			Administrator Control Panel

<a href="<?php base_url('hiremetro');?>"> Home

						 ADMIN

<a href="<?php echo base_url('hiremetro/view_profile');?>">Profile

 Logout

						<button type="button" class="close" data-dismiss="modal"> × </button>

 LOGOUT

Attention

Are you sure ?

						<a href="<?php echo base_url('hiremetro/logout');?>"><button class="btn btn-default">Yes</button>
						<button class="btn btn-default" data-dismiss="modal">No</button>

	<div class="container-fluid pagee" style="background-image: url('<?php echo base_url('images/bg_admin.png')?>');">

<a href="<?php echo base_url('hiremetro/admin')?>"> Dashboard

 Profiles

<a href="<?php echo base_url('hiremetro/admin_reports')?>"> Reports

<a href="<?php echo base_url('hiremetro/admin_suggestions')?>"> Suggestions

<a href="<?php echo base_url('hiremetro/admin_settings')?>">Settings

hiremetro © 2017 | Designed by Group 4

						<img  width="60px" height="60px" id="setlogo" src="<?php echo base_url('images/suggestions.png')?>">

Suggestions

							<button type="button" class="btn btn-primary"> Save</button>
							<button type="button" class="btn btn-danger"> Delete</button>

 SubjectLine

January 18, 2013

Yes Sir mga kaibigan! So ayun po ano?! Paaaaaaaaaweeeer!!


text:
package pl.skifo.mconsole;

import pl.skifo.mconsole.CommandResponseEvaluator.EvaluatorType;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;

public class ServerFragment extends Fragment implements OnClickListener {

    private ActionBarActivity ctx;
    private CommandPrompt prompt;
    private EditText sec;

    /*
     * action bar:
     * banlist/pardon
     * say
     *
     * menu:
     * save
     * stop

     * Commands to be supported:
     * time add/set
     * gamerule
     * weather
     * difficulty
     * spawnpoint
     * toggledownfall
     */

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ctx = (ActionBarActivity) activity;
        if (activity instanceof CommandPrompt) {
            prompt = (CommandPrompt)activity;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_server, container, false);

        ImageButton ib = (ImageButton)rootView.findViewById(R.id.weather_sun_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.weather_rain_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.weather_thunder_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.weather_toggle_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.time_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.time_15min_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.time_1h_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.time_dawn_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.time_noon_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.time_dusk_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.time_midnight_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.diff_peaceful_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.diff_easy_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.diff_normal_button);
        ib.setOnClickListener(this);
        ib = (ImageButton)rootView.findViewById(R.id.diff_hard_button);
        ib.setOnClickListener(this);
        sec = (EditText)rootView.findViewById(R.id.weather_seconds);
        return rootView;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
// difficulty
            case R.id.diff_peaceful_button:
                prompt.sendCommand(CommandSet.getCommand(CommandSet.DIFFICULTY)+"peaceful",
                                   new ResponseToastGenerator(ctx,
                                   new CommandResponseEvaluator(EvaluatorType.difficulty),
                                   R.string.diff_set_to_peace, R.string.diff_set_failed));
                break;

            case R.id.diff_easy_button:
                prompt.sendCommand(CommandSet.getCommand(CommandSet.DIFFICULTY)+"easy",
                                   new ResponseToastGenerator(ctx,
                                   new CommandResponseEvaluator(EvaluatorType.difficulty),
                                   R.string.diff_set_to_easy, R.string.diff_set_failed));
                break;

            case R.id.diff_normal_button:
                prompt.sendCommand(CommandSet.getCommand(CommandSet.DIFFICULTY)+"normal",
                                   new ResponseToastGenerator(ctx,
                                   new CommandResponseEvaluator(EvaluatorType.difficulty),
                                   R.string.diff_set_to_normal, R.string.diff_set_failed));
                break;

            case R.id.diff_hard_button:
                prompt.sendCommand(CommandSet.getCommand(CommandSet.DIFFICULTY)+"hard",
                                   new ResponseToastGenerator(ctx,
                                   new CommandResponseEvaluator(EvaluatorType.difficulty),
                                   R.string.diff_set_to_hard, R.string.diff_set_failed));
                break;
//weather
            case R.id.weather_sun_button:
                weatherSet("clear", R.string.weather_set_to_clear);
                break;
            case R.id.weather_rain_button:
                weatherSet("rain", R.string.weather_set_to_rain);
                break;
            case R.id.weather_thunder_button:
                weatherSet("thunder", R.string.weather_set_to_thunder);
                break;
            case R.id.weather_toggle_button:
                prompt.sendCommand("toggledownfall",
                        new ResponseToastGenerator(ctx,
                        new CommandResponseEvaluator(EvaluatorType.toggledownfall),
                        R.string.toggledownfall_ok, R.string.toggledownfall_failed));
                break;

//time
            case R.id.time_button:
                DialogFragment dialog = new TimeSetDialog(prompt);
                dialog.show(ctx.getSupportFragmentManager(), "TimeSetDialog");
                break;
            case R.id.time_15min_button:
                advanceTime(15 * 60);
                break;
            case R.id.time_1h_button:
                advanceTime(60 * 60);
                break;
            case R.id.time_dawn_button:
                setTime(0);
                break;
            case R.id.time_noon_button:
                setTime(6000);
                break;
            case R.id.time_dusk_button:
                setTime(12000);
                break;
            case R.id.time_midnight_button:
                setTime(18000);
                break;
        }
    }

    // units 0 - 24000
    // dawn = 0
    // noon = 6000
    // dusk = 12000
    // midnight = 18000
    private void setTime(int units) {
        prompt.sendCommand(CommandSet.getCommand(CommandSet.TIME) + "set "+units,
                new ResponseToastGenerator(ctx,
                new CommandResponseEvaluator(EvaluatorType.time),
                R.string.time_set_ok, R.string.time_set_failed));
    }

    private void advanceTime(int seconds) {
        prompt.sendCommand(CommandSet.getCommand(CommandSet.TIME)+"add "+((seconds * 1000)/3600),
                new ResponseToastGenerator(ctx,
                new CommandResponseEvaluator(EvaluatorType.time_add),
                R.string.time_set_ok, R.string.time_set_failed));
    }

    private void weatherSet(String kind, int okId) {
        String s = sec.getText().toString();
        String timeValue = "";
        try {
            int t = Integer.parseInt(s);
            timeValue = " "+t;
        }
        catch (NumberFormatException ignore){};

        prompt.sendCommand(CommandSet.getCommand(CommandSet.WEATHER)+kind+timeValue,
                           new ResponseToastGenerator(ctx,
                           new CommandResponseEvaluator(EvaluatorType.weather),
                           okId, R.string.weather_set_failed));
    }

}


text:
<?php
$type = str_replace('/', '', url_string());
$description = "The " . $type . " page has been automatically generated using SimpleSite. This software is freely available on GitHub (github.com/markjones112358/simpleSite). Putting a plain text file in this folder (titled ’description’) will overwrite this message with its contents.";
$files = scan_filesByExtensions(PATH_WATCH . '/' . $type, 'txt');
foreach ($files as $file) {
    if (strpos(strtolower($file), 'desc') !== False) {
        $description = limit_text(retrieve_text(PATH_WATCH . '/' . $type . '/' . $file), 160);
    }
}
$p = new BasePage(ucfirst($type),
                  $description,
                  header_small($experienceList->types()),
                  footer());

$recent = ExperienceList::ordered_byDate($experienceList->experiences[$type]);
foreach($recent AS $experience) $p->append($experience->displayBox());
$p->wrap('div', Array('class'=>'c', 'style'=>'margin-bottom: 140px'));


text:
const tokenChecker = require('./token');

module.exports = function ensureAuth (req, res, next) {
  if (req.method === 'OPTIONS') return next();

  const authHeader = req.headers.authorization;
  const token = authHeader ? authHeader.replace('Bearer ', '') : '';

  if(!token) {
    return res.status(403).send({message: 'Authorization failed, token missing.'});
  }

  tokenChecker.verify(token)
    .then(payload => {
      req.user = payload;
      next();
    })
    .catch(error => {
      console.log('Error verifying token:',error);
      res.status(403).send({message: 'Authorization failed, token invalid.'});
    });

};


text:
use parsetree::*;
use op::*;
use span::*;

/// Builds an `EBinOp` node and attaches the correct span. This requires that `lhs` and `rhs` are
/// in the right "order" concerning their spans.
fn mknode<'a>(lhs: Expr<'a>, op: BinOp, rhs: Expr<'a>) -> Expr<'a> {
    let start = lhs.span.start;
    let end = rhs.span.start + rhs.span.len;
    mkspanned(ExprKind::BinOp(Box::new(lhs), op, Box::new(rhs)), start, end)
}

/// Builds an expression tree out of a given `lhs` and operator-expr-pairs applied on the
/// right-hand side.
pub fn build_tree<'a>(left: Expr<'a>, rest: Vec<(BinOp, Expr<'a>)>) -> Expr<'a> {
    let mut operands: Vec<Expr> = vec![left];
    let mut operators: Vec<BinOp> = vec![];

    for (op, rhs) in rest {
        // While the operator on the stack has higher or equal precedence, pop it, pop
        // 2 operands and replace the operands with a newly built operand node
        while operators.len() > 0 {
            let stackop = operators[operators.len() - 1];
            let stackprec = stackop.get_precedence();
            let opprec = op.get_precedence();
            if opprec < stackprec || (opprec == stackprec && op.get_assoc() == Assoc::Left) {
                operators.pop();
                let rhs = operands.pop().unwrap();
                let lhs = operands.pop().unwrap();

                operands.push(mknode(lhs, stackop, rhs));
            } else { break; }
        }

        // Always the new operator and operand on the stack
        operators.push(op);
        operands.push(rhs);
    }

    // Pop all operators and build nodes
    while !operators.is_empty() {
        let op = operators.pop().unwrap();
        let rhs = operands.pop().unwrap();
        let lhs = operands.pop().unwrap();

        // PUSH UNTIL THERE IS NOTHING LEFT TO PUSH
        operands.push(mknode(lhs, op, rhs));
    }

    // If this algorithm works correctly, this always holds, since the input data can
    // always be turned into a tree (since there is always one operand and any number
    // of operator-operand pairs)
    assert_eq!(operands.len(), 1);

    operands.pop().unwrap()
}


text:
package org.diretto.api.client.main.feed.binding;

import java.util.ArrayList;

import org.diretto.api.client.main.core.binding.resources.APIResource;
import org.diretto.api.client.main.core.binding.resources.DeploymentResource;
import org.diretto.api.client.main.core.binding.resources.ParametersResource;
import org.diretto.api.client.main.core.binding.resources.ServiceResource;
import org.diretto.api.client.main.core.binding.resources.TitledLinkResource;

/**
 * This class represents a POJO based {@code FeedServiceInstanceDataResource}.
 *

 *
 * It is used for operating with the data interchange format JSON. So it is
 * possible to marshal Java objects into JSON representation and to unmarshal
 * JSON messages into Java objects.

 *
 * Annotation: This is also called (full) data binding
 *
 * @author Tobias Schlecht
 */
public final class FeedServiceInstanceDataResource
{
	private APIResource api;
	private ServiceResource service;
	private DeploymentResource deployment;
	private ArrayList<TitledLinkResource> links;
	private ParametersResource parameters;

	public APIResource getAPI()
	{
		return api;
	}

	public void setAPI(APIResource api)
	{
		this.api = api;
	}

	public ServiceResource getService()
	{
		return service;
	}

	public void setService(ServiceResource service)
	{
		this.service = service;
	}

	public DeploymentResource getDeployment()
	{
		return deployment;
	}

	public void setDeployment(DeploymentResource deployment)
	{
		this.deployment = deployment;
	}

	public ArrayList<TitledLinkResource> getLinks()
	{
		return links;
	}

	public void setLinks(ArrayList<TitledLinkResource> links)
	{
		this.links = links;
	}

	public ParametersResource getParameters()
	{
		return parameters;
	}

	public void setParameters(ParametersResource parameters)
	{
		this.parameters = parameters;
	}
}


text:
#include <cstdint>
#include <iostream>

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "mlir/IR/Attributes.h"  // from @llvm-project
#include "mlir/IR/Builders.h"  // from @llvm-project
#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/IR/BuiltinTypes.h"  // from @llvm-project
#include "mlir/IR/Location.h"  // from @llvm-project
#include "mlir/IR/MLIRContext.h"  // from @llvm-project
#include "mlir/IR/Operation.h"  // from @llvm-project
#include "mlir/IR/OperationSupport.h"  // from @llvm-project
#include "mlir/IR/PatternMatch.h"  // from @llvm-project
#include "mlir/IR/TypeUtilities.h"  // from @llvm-project
#include "mlir/IR/Types.h"  // from @llvm-project
#include "mlir/IR/Value.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Pass/PassRegistry.h"  // from @llvm-project
#include "mlir/Support/LLVM.h"  // from @llvm-project
#include "mlir/Support/LogicalResult.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/convert_tensor.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/tpu_rewrite_device_util.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/util/device_name_utils.h"

namespace mlir {
namespace TFTPU {

namespace {

constexpr char kDeviceAttr[] = "device";
typedef std::pair<TF::Conv2DOp, int64_t> Conv2DWithBlockSize;

struct BlockArgumentInfo {
  unsigned arg_num;
  unsigned num_users;
};

// A pass that applies automatic space to depth transform for the first or
// frontier convolutions consume host inputs on TPU.
// This is done by adding space to depth transform op after host input and
// applying space to depth transform for the first convolution and its backprop
// filter on TPU.
//
// Example: original program:
//
// module {
//   func @while_body {
//     %input = "tf.IteratorGetNext"(...) {device = "/CPU:0"}:
//              -> tensor<2x224x224x3xf32>
//     %device_launch = "tf_device.cluster_func"(%input,...) {func = @_func,...)
//     return ...
//   }
//   func @_func(%input: tensor<2x224x224x3xf32>,
//               %filter: tensor<7x7x3x64xf32>) {
//     %6 = "tf.Conv2D"(%input, %filter)  {strides = [1, 2, 2, 1]}:
//      (tensor<2x230x230x3xf32>, tensor<7x7x3x64xf32>) ->
//      tensor<2x112x112x64xf32>
//   }
// }
//
// With this pass, the program will be transformed into:
// module {
//   func @while_body {
//     %input = "tf.IteratorGetNext"(...) {device = "/CPU:0"}
//               -> tensor<2x224x224x3xf32>
//     %space_to_depth = "tf.SpaceToDepth"(%input) {block_size = 2, ...}:
//        (tensor<2x224x224x3xf32>) -> tensor<2x112x112x12xf32>
//     %device_launch = "tf_device.cluster_func"(%space_to_depth,...)
//       {func = @_func,...)
//     return ...
//   }
//   func @_func(%input: tensor<2x112x112x12xf32>,
//               %filter: tensor<7x7x3x64xf32>) {
//     %filter_transform = "tf.Pad/tf.Transpose/tf.Reshape"(%filter):
//       tensor<7x7x3x64xf32>) -> tensor<4x4x12x64xf32>
//     %conv = "tf.Conv2D"(%input, %filter_transfrom) {strides = [1, 1, 1, 1]}:
//       (tensor<2x112x112x12xf32>, tensor<4x4x12x64xf32>) ->
//       tensor<2x112x112x64xf32>
//   }
// }
//
// This way, the first convolution with 3 feature dimension will be transformed
// to 12 feature dimension, which has better performance on TPU.
//
// TODO(wangtao): add a pass to check if it is profitable to space to depth
// transform and invoke the transform if it is needed.
struct TPUSpaceToDepthPass
    : public PassWrapper<TPUSpaceToDepthPass, OperationPass<ModuleOp>> {
  void runOnOperation() override;
};

// Updates func argument type to have the updated input shape.
void UpdateFuncType(FuncOp func) {
  auto arg_types = func.front().getArgumentTypes();
  auto result_types = func.front().getTerminator()->getOperandTypes();
  func.setType(FunctionType::get(arg_types, result_types, func.getContext()));
}

void HandleFuncOp(Operation* op) {
  auto func = llvm::cast<FuncOp>(op);
  UpdateFuncType(func);
}

// Handles cast op between the first convolution and the block argument.
LogicalResult HandleCast(TF::CastOp cast_op, ArrayRef<int64_t> new_shape) {
  auto cast_input = cast_op.x();
  // Update input type.
  auto transform_result_type =
      RankedTensorType::get(new_shape, getElementTypeOrSelf(cast_input));
  cast_input.setType(transform_result_type);
  auto block_arg = cast_input.dyn_cast<mlir::BlockArgument>();
  auto cast_op_input = dyn_cast_or_null<TF::CastOp>(cast_input.getDefiningOp());
  while (block_arg || cast_op_input) {
    if (block_arg) {
      // Change on device function type/shape.
      HandleFuncOp(block_arg.getOwner()->getParentOp());
      block_arg = nullptr;
      cast_op_input = nullptr;
    } else {
      auto cast_input = cast_op_input.x();
      // Update input type.
      auto transform_result_type =
          RankedTensorType::get(new_shape, getElementTypeOrSelf(cast_input));
      cast_input.setType(transform_result_type);
      // Update block arg and cast_op_input.
      block_arg = cast_input.dyn_cast<mlir::BlockArgument>();
      cast_op_input = dyn_cast_or_null<TF::CastOp>(cast_input.getDefiningOp());
    }
  }
  return success();
}

// Handles padding before convolution for space to depth transform.
LogicalResult HandlePad(TF::PadOp op, int32_t kernel_size, int32_t block_size) {
  auto ranked_type = op.input().getType().dyn_cast<RankedTensorType>();
  if (!ranked_type) return failure();
  auto pad_input_shape = ranked_type.getShape();
  Location loc = op.getLoc();
  OpBuilder builder(op);
  builder.setInsertionPoint(op);
  auto padding_type = RankedTensorType::get({4, 2}, builder.getIntegerType(32));

  // Calculate paddings.
  int32_t pad_total = kernel_size - 1;
  int32_t pad_beg = (pad_total / 2 + 1) / block_size;
  int32_t pad_end = (pad_total / 2) / block_size;
  SmallVector<int32_t, 8> values = {0,       0,       pad_beg, pad_end,
                                    pad_beg, pad_end, 0,       0};
  auto paddings = DenseIntElementsAttr::get(padding_type, values);
  // Update pad_op paddings.
  op.setOperand(1, builder.create<TF::ConstOp>(loc, paddings));

  // Set input type.
  auto input = op.getOperand(0);
  SmallVector<int64_t, 4> transform_shape = {
      pad_input_shape[0], pad_input_shape[1] / block_size,
      pad_input_shape[2] / block_size,
      pad_input_shape[3] * block_size * block_size};
  // Input of the pad op could be a cast op.
  if (auto cast_op = dyn_cast_or_null<TF::CastOp>(input.getDefiningOp()))
    if (failed(HandleCast(cast_op, transform_shape))) return failure();

  auto transform_result_type =
      RankedTensorType::get(transform_shape, getElementTypeOrSelf(input));
  input.setType(transform_result_type);
  op.setOperand(0, input);
  return success();
}

// Handles stride for the first convolution for the transform.
void HandleConv2DStride(TF::Conv2DOp conv2d) {
  MLIRContext* context = conv2d.getContext();
  SmallVector<int64_t, 4> values = {1, 1, 1, 1};
  auto attrs = llvm::map_range(values, [context](int64_t v) -> Attribute {
    return IntegerAttr::get(IntegerType::get(64, context), v);
  });
  // TODO(b/157276506): change type of strides to DenseElementsAttr
  auto strides = ArrayAttr::get(llvm::to_vector<4>(attrs), context);
  conv2d->setAttr("strides", strides);
}

// Transforms input shape for the first convolution.
void HandleConv2DInput(TF::Conv2DOp conv2d, int64_t block_size) {
  auto input = conv2d.input();
  auto input_shape = input.getType().cast<RankedTensorType>().getShape();
  SmallVector<int64_t, 4> transform_shape = {
      input_shape[0], input_shape[1] / block_size, input_shape[2] / block_size,
      input_shape[3] * block_size * block_size};
  auto transform_result_type =
      RankedTensorType::get(transform_shape, getElementTypeOrSelf(input));
  input.setType(transform_result_type);
}

// Adds padding for convolution filter for space to depth transform.
TF::PadOp GetPadOpForConv2DFilter(ArrayRef<int64_t> filter_shape, Value filter,
                                  OpBuilder* builder, int32_t pad_h,
                                  int32_t pad_w) {
  SmallVector<int32_t, 8> values = {pad_h, 0, pad_w, 0, 0, 0, 0, 0};
  auto padding_type =
      RankedTensorType::get({4, 2}, builder->getIntegerType(32));
  auto paddings = DenseIntElementsAttr::get(padding_type, values);
  auto paddings_value = builder->create<TF::ConstOp>(filter.getLoc(), paddings);
  std::vector<int64_t> pad_shape = {filter_shape[0] + pad_h,
                                    filter_shape[1] + pad_w, filter_shape[2],
                                    filter_shape[3]};
  SmallVector<int64_t, 4> expand_shape(pad_shape.begin(), pad_shape.end());

  auto expand_result_type =
      RankedTensorType::get(expand_shape, getElementTypeOrSelf(filter));
  return builder->create<TF::PadOp>(filter.getLoc(), expand_result_type, filter,
                                    paddings_value);
}

// Creates reshape op for space to depth transform.
TF::ReshapeOp GetReshapeOpForConv2DFilter(ArrayRef<int64_t> new_shape,
                                          Value input, OpBuilder* builder) {
  auto reshape_result_type =
      RankedTensorType::get(new_shape, getElementTypeOrSelf(input));
  auto reshape_type = RankedTensorType::get(
      {static_cast<int64_t>(new_shape.size())}, builder->getIntegerType(64));
  auto reshape_sizes = DenseIntElementsAttr::get(reshape_type, new_shape);
  auto reshape_value =
      builder->create<TF::ConstOp>(input.getLoc(), reshape_sizes);
  return builder->create<TF::ReshapeOp>(input.getLoc(), reshape_result_type,
                                        input, reshape_value);
}

// Creates transpose op for shape to depth transform.
TF::TransposeOp GetTransposeOpForConv2DFilter(OpBuilder* builder, Value input) {
  SmallVector<int32_t, 6> permutation = {0, 2, 1, 3, 4, 5};
  auto permute_type = RankedTensorType::get({6}, builder->getIntegerType(32));
  auto permute_attr = DenseIntElementsAttr::get(permute_type, permutation);
  auto permute_value =
      builder->create<TF::ConstOp>(input.getLoc(), permute_attr);
  return builder->create<TF::TransposeOp>(input.getLoc(), input, permute_value);
}

void HandleConv2DFilter(TF::Conv2DOp conv2d, int64_t block_size) {
  // For example, if filter shape is [7, 7, 3, 64] with block_size 2,
  // will apply below transforms to the filter:
  // 1. Pad the filter to [8, 8, 3, 64]
  // 2. Reshape to [4, 2, 4, 2, 3, 64]
  // 3. Transpose to [4, 4, 2, 2, 3, 64]
  // 4. Reshape to [4, 4, 12, 64]
  auto filter = conv2d.filter();
  OpBuilder builder(conv2d);
  builder.setInsertionPoint(conv2d);
  // Book keeping filter information.
  auto filter_shape = filter.getType().cast<RankedTensorType>().getShape();
  int64_t height = filter_shape[0];
  int64_t width = filter_shape[1];
  int64_t channel = filter_shape[2];
  int64_t out_channel = filter_shape[3];
  // Value/Op before reshape op.
  Value before_reshape_value = filter;
  if (height % block_size != 0 || width % block_size != 0) {
    // Calculate paddings for height and width.
    int32_t pad_h = block_size - height % block_size;
    int32_t pad_w = block_size - width % block_size;
    auto pad_op =
        GetPadOpForConv2DFilter(filter_shape, filter, &builder, pad_h, pad_w);
    // Update op, height and width before reshape.
    before_reshape_value = pad_op;
    height = height + pad_h;
    width = width + pad_w;
  }

  // Reshape.
  SmallVector<int64_t, 6> new_shape = {
      height / block_size, block_size, width / block_size,
      block_size,          channel,    out_channel};
  auto reshape_op =
      GetReshapeOpForConv2DFilter(new_shape, before_reshape_value, &builder);

  // Transpose.
  auto transpose_op = GetTransposeOpForConv2DFilter(&builder, reshape_op);

  // Reshape Back.
  SmallVector<int64_t, 4> final_shape = {
      height / block_size, width / block_size,
      channel * block_size * block_size, out_channel};
  auto final_reshape_op =
      GetReshapeOpForConv2DFilter(final_shape, transpose_op, &builder);
  // Update filter of Conv2D.
  conv2d.setOperand(1, final_reshape_op);
}

// Creates slice op for filter in back prop pass.
TF::SliceOp GetSliceOpForConv2DBackPropFilter(
    ArrayRef<int32_t> old_filter_shape, Value input, OpBuilder* builder) {
  SmallVector<int64_t, 4> slice_size(old_filter_shape.begin(),
                                     old_filter_shape.end());
  auto slice_result_type =
      RankedTensorType::get(slice_size, getElementTypeOrSelf(input));
  auto slice_size_op = builder->create<TF::ConstOp>(
      input.getLoc(),
      DenseIntElementsAttr::get(
          RankedTensorType::get({4}, builder->getIntegerType(32)),
          old_filter_shape));
  SmallVector<int64_t, 4> slice_start_position = {0, 0, 0, 0};
  auto start_position_type =
      RankedTensorType::get({4}, builder->getIntegerType(64));
  auto start_position = builder->create<TF::ConstOp>(
      input.getLoc(),
      DenseIntElementsAttr::get(start_position_type, slice_start_position));
  return builder->create<TF::SliceOp>(input.getLoc(), slice_result_type, input,
                                      start_position, slice_size_op);
}

// Transforms Conv2DBackPropFilter for space to depth.
void HandleConv2DBackPropFilter(TF::Conv2DBackpropFilterOp backprop,
                                ArrayRef<int32_t> old_filter_shape,
                                ArrayRef<int32_t> new_filter_shape,
                                int64_t block_size) {
  OpBuilder builder(backprop);
  builder.setInsertionPoint(backprop);

  auto input = backprop.input();
  // Get new filter size from new_filter_shape.
  auto new_filter_sizes = builder.create<TF::ConstOp>(
      backprop.getLoc(),
      DenseIntElementsAttr::get(
          RankedTensorType::get({4}, builder.getIntegerType(32)),
          new_filter_shape));

  // Set stride to [1, 1, 1, 1].
  MLIRContext* context = backprop.getContext();
  SmallVector<int64_t, 4> values = {1, 1, 1, 1};
  auto attrs = llvm::map_range(values, [context](int64_t v) -> Attribute {
    return IntegerAttr::get(IntegerType::get(64, context), APInt(64, v));
  });
  auto strides = ArrayAttr::get(llvm::to_vector<4>(attrs), context);

  // new result type.
  SmallVector<int64_t, 4> new_shape(new_filter_shape.begin(),
                                    new_filter_shape.end());
  auto new_result_type =
      RankedTensorType::get(new_shape, getElementTypeOrSelf(input));

  // Build new BackPropFilterOp.
  auto loc = backprop.getLoc();
  auto new_backprop = builder.create<TF::Conv2DBackpropFilterOp>(
      loc, new_result_type, input, new_filter_sizes, backprop.out_backprop(),
      strides, backprop.use_cudnn_on_gpu(), backprop.padding(),
      backprop.explicit_paddings(), backprop.data_format(),
      backprop.dilations());

  // For example, if new filter shape is [4, 4, 12, 64], old filter shape
  // is [7, 7, 3, 64] with block_size 2.
  // Below transforms will be applied to the filter:
  // 1. Reshape to [4, 4, 2, 2, 3, 64];
  // 2. Transpose to [4, 2, 4, 2, 3, 64];
  // 3. Reshape to [8, 8, 3, 64];
  // 4. Slice to [7, 7, 3, 64].
  SmallVector<int64_t, 6> first_reshape_shape = {
      new_filter_shape[0],
      new_filter_shape[1],
      block_size,
      block_size,
      new_filter_shape[2] / (block_size * block_size),
      new_filter_shape[3]};
  auto first_reshape_op =
      GetReshapeOpForConv2DFilter(first_reshape_shape, new_backprop, &builder);

  // Transpose.
  auto transpose_op = GetTransposeOpForConv2DFilter(&builder, first_reshape_op);

  // Last Reshape op.
  SmallVector<int64_t, 4> last_reshape_shape = {
      new_filter_shape[0] * block_size, new_filter_shape[1] * block_size,
      new_filter_shape[2] / (block_size * block_size), new_filter_shape[3]};
  auto final_reshape_op =
      GetReshapeOpForConv2DFilter(last_reshape_shape, transpose_op, &builder);

  // create slice op.
  auto slice_op = GetSliceOpForConv2DBackPropFilter(old_filter_shape,
                                                    final_reshape_op, &builder);

  // Update backprop's user with the slice op.
  backprop.replaceAllUsesWith(slice_op.getResult());
}

// Checks if the input producer op is supported in this transform. Right now, we
// only check if it is a host tf.IteratorGetNext.
bool IsSupportedHostInputOp(Operation* op) {
  TF::IteratorGetNextOp iter = llvm::dyn_cast<TF::IteratorGetNextOp>(op);
  if (!iter) return false;
  auto device = op->getAttrOfType<StringAttr>(kDeviceAttr);
  if (!device) return false;
  tensorflow::DeviceNameUtils::ParsedName parsed_device;
  if (!tensorflow::DeviceNameUtils::ParseFullName(device.getValue().str(),
                                                  &parsed_device)) {
    return false;
  }
  return parsed_device.type == "CPU";
}

// Builds a SpaceToDepthOp with the given get_layout op and input.
TF::SpaceToDepthOp BuildSpaceToDepth(tf_device::ClusterFuncOp cluster_func,
                                     Value input, int32_t block_size,
                                     ArrayRef<int64_t> input_shape) {
  auto input_op = input.getDefiningOp();
  OpBuilder builder(input_op);
  builder.setInsertionPointAfter(input_op);
  SmallVector<int64_t, 4> transform_shape = {
      input_shape[0], input_shape[1] / block_size, input_shape[2] / block_size,
      input_shape[3] * block_size * block_size};
  auto transform_result_type =
      RankedTensorType::get(transform_shape, getElementTypeOrSelf(input));
  return builder.create<TF::SpaceToDepthOp>(
      cluster_func.getLoc(), transform_result_type, input, block_size);
}

// Performs transformation for a non-replicated input.
TF::SpaceToDepthOp HandleHostInput(Value input, int64_t index,
                                   tf_device::ClusterFuncOp cluster_func,
                                   int32_t block_size,
                                   ArrayRef<int64_t> input_shape) {
  auto space_to_depth =
      BuildSpaceToDepth(cluster_func, input, block_size, input_shape);
  cluster_func.setOperand(index, space_to_depth);
  return space_to_depth;
}

// Performs transformation for replicated inputs. Returns true if this is a
// supported case (thus transform happened).
bool HandleHostReplicatedInputs(int64_t index,
                                tf_device::ClusterFuncOp cluster_func,
                                BlockArgument block_arg,
                                tf_device::ReplicateOp replicate,
                                int32_t block_size) {
  int64_t replicate_arg_index = block_arg.getArgNumber();
  // We need to know the devices to copy to.
  if (!replicate.devices()) return false;
  int64_t num_replicas = replicate.n();
  // Gets inputs at replicate_arg_index for each replica.
  auto inputs = replicate.getOperands()
                    .drop_front(replicate_arg_index * num_replicas)
                    .take_front(num_replicas);
  for (auto input : inputs) {
    auto input_op = input.getDefiningOp();
    if (!input_op || !IsSupportedHostInputOp(input_op)) return false;
  }
  for (auto entry : llvm::enumerate(inputs)) {
    auto ranked_type = entry.value().getType().dyn_cast<RankedTensorType>();
    if (!ranked_type) return false;
    auto input_shape = ranked_type.getShape();
    auto space_to_depth =
        BuildSpaceToDepth(cluster_func, entry.value(), block_size, input_shape);
    replicate.setOperand(num_replicas * replicate_arg_index + entry.index(),
                         space_to_depth);
    block_arg.setType(space_to_depth.getType());
  }
  return true;
}

// Performs transformation on a pair of execute and compile ops. The compile
// should not have other uses.
void HandleCluster(tf_device::ClusterFuncOp cluster_func, int32_t block_size,
                   unsigned arg_num) {
  auto maybe_replicate =
      llvm::dyn_cast<tf_device::ReplicateOp>(cluster_func->getParentOp());

  llvm::SmallVector<int64_t, 8> transform_input_indices;
  for (auto input : llvm::enumerate(cluster_func.operands())) {
    if (auto block_arg = input.value().dyn_cast<BlockArgument>()) {
      if (block_arg.getArgNumber() != arg_num) continue;
      // For a block argument, consider transforms only when it is a replicated
      // input (defining ops will be outside the replicate node).
      if (maybe_replicate == block_arg.getParentRegion()->getParentOp()) {
        HandleHostReplicatedInputs(input.index(), cluster_func, block_arg,
                                   maybe_replicate, block_size);
      }
    } else {
      // For an op output, consider transforms only when 1) there is no
      // replicateion or 2) it is outside the replicate node that encloses the
      // execute node. (Because if the op is inside replicate, it is probably
      // not on the host.)
      if (input.index() != arg_num) continue;
      auto input_op = input.value().getDefiningOp();
      if (maybe_replicate &&
          maybe_replicate.body().isAncestor(input_op->getParentRegion())) {
        continue;
      }
      if (!IsSupportedHostInputOp(input_op)) continue;
      auto ranked_type = input.value().getType().dyn_cast<RankedTensorType>();
      if (!ranked_type) continue;
      auto input_shape = ranked_type.getShape();
      HandleHostInput(input.value(), input.index(), cluster_func, block_size,
                      input_shape);
    }
  }
}

// Checks if input shape of convolution is good for space to depth transform.
bool Conv2DInputShapeCanTransform(Value input) {
  auto ranked_type = input.getType().dyn_cast<RankedTensorType>();
  if (!ranked_type) return false;
  auto input_shape = ranked_type.getShape();
  int32_t batch_size = input_shape[0];
  int32_t channel = input_shape[3];
  if (batch_size > 8 || channel > 8) {
    return false;
  }
  return true;
}

// Get block argument id and number of users for the input arg.
Optional<BlockArgumentInfo> GetBlockArgNum(Value arg) {
  if (auto block_arg = arg.dyn_cast<mlir::BlockArgument>()) {
    if (!Conv2DInputShapeCanTransform(arg)) return None;
    unsigned num_users =
        std::distance(block_arg.getUsers().begin(), block_arg.getUsers().end());
    BlockArgumentInfo block_arg_info = {block_arg.getArgNumber(), num_users};
    return block_arg_info;
  }
  return None;
}

// Gets input block argument id and number of users for the input recursively.
// Current supported ops between convolution input and the block arguments are
// PadOp and CastOp.
Optional<BlockArgumentInfo> GetInputBlockArgNum(Value input) {
  auto block_arg_num = GetBlockArgNum(input);
  if (block_arg_num.hasValue()) return block_arg_num;

  Value next_input = input;
  auto pad_op = dyn_cast_or_null<TF::PadOp>(next_input.getDefiningOp());
  auto cast_op = dyn_cast_or_null<TF::CastOp>(next_input.getDefiningOp());

  while (pad_op || cast_op) {
    if (pad_op) {
      auto block_arg_num = GetBlockArgNum(pad_op.input());
      if (block_arg_num.hasValue()) return block_arg_num;
      next_input = pad_op.input();
    } else {
      auto block_arg_num = GetBlockArgNum(cast_op.x());
      if (block_arg_num.hasValue()) return block_arg_num;
      next_input = cast_op.x();
    }
    pad_op = dyn_cast_or_null<TF::PadOp>(next_input.getDefiningOp());
    cast_op = dyn_cast_or_null<TF::CastOp>(next_input.getDefiningOp());
  }

  return None;
}

// Checks if a convoluton can apply SpaceToDepth transform.
// Only the first convolution in the graph whose batch size smaller than 8
// and its input feature size smaller than 8 can be transformed.
Optional<BlockArgumentInfo> GetConv2DInputArgNum(TF::Conv2DOp conv2d) {
  if (conv2d.data_format() != "NHWC" || conv2d.strides().size() != 4) {
    return None;
  }
  // Current supported ops between convolution input and the block arguments are
  // PadOp and CastOp.
  return GetInputBlockArgNum(conv2d.input());
}

// Applies space to depth transform for the first convolution on TPU device.
void HandleFirstConvolution(TF::Conv2DOp conv2d, int64_t block_size) {
  // Check if input and filter type are RankedTensorType.
  auto input_tensor_type =
      conv2d.input().getType().dyn_cast<RankedTensorType>();
  auto filter_tensor_type =
      conv2d.filter().getType().dyn_cast<RankedTensorType>();
  if (!input_tensor_type || !filter_tensor_type) return;
  // Book keeping filter shape for padding and backprop filter rewrite.
  auto filter_shape = filter_tensor_type.getShape();
  SmallVector<int32_t, 4> old_filter_shape(filter_shape.begin(),
                                           filter_shape.end());
  // Handles input.
  auto conv2d_input = conv2d.input();
  if (auto block_arg = conv2d_input.dyn_cast<mlir::BlockArgument>()) {
    // Change on device function type/shape.
    HandleFuncOp(block_arg.getOwner()->getParentOp());
  }

  if (auto pad_op = dyn_cast_or_null<TF::PadOp>(conv2d_input.getDefiningOp())) {
    // Rewrite pad_op before Convolutioin.
    if (failed(HandlePad(pad_op, filter_shape[0], block_size))) return;
    auto pad_input = pad_op.input();
    if (auto block_arg = pad_input.dyn_cast<mlir::BlockArgument>()) {
      // Change on device function type/shape.
      HandleFuncOp(block_arg.getOwner()->getParentOp());
    }
  }

  // Handle Conv2D input, stride and filter.
  HandleConv2DInput(conv2d, block_size);
  HandleConv2DStride(conv2d);
  HandleConv2DFilter(conv2d, block_size);

  // Book keeping new filter shape for backprop filter rewrite.
  // Filter shape is defined in HandleConv2DFilter, thus it is RankedTensorType.
  filter_shape = conv2d.filter().getType().cast<RankedTensorType>().getShape();
  SmallVector<int32_t, 4> new_filter_shape(filter_shape.begin(),
                                           filter_shape.end());

  // Rewrite Conv2DBackPropFilter that is the user of first convolution's input.
  if (!conv2d_input.getDefiningOp()) return;
  for (Operation* user : conv2d_input.getDefiningOp()->getUsers()) {
    if (auto backprop = dyn_cast<TF::Conv2DBackpropFilterOp>(user)) {
      HandleConv2DBackPropFilter(backprop, old_filter_shape, new_filter_shape,
                                 block_size);
    }
  }
}

// Gets block size that is equal to stride from spatial dimension
// from convolution.
// Space to depth transform won't be triggered if block size <= 1.
int32_t GetConv2DBlockSize(TF::Conv2DOp conv2d) {
  SmallVector<int32_t, 4> strides(4, 1);
  for (int i = 0; i < 3; ++i) {
    strides[i] = conv2d.strides()[i].cast<mlir::IntegerAttr>().getInt();
  }

  // Space to depth only supports striding at spatial dimension.
  if (strides[0] != 1 || strides[3] != 1) return 1;

  // Space to depth only supports height_stride == width_stride case.
  if (strides[1] != strides[2]) return 1;

  return strides[1];
}

void TPUSpaceToDepthPass::runOnOperation() {
  Optional<tf_device::ClusterFuncOp> cluster_func;
  // Space to depth only supports training loop.
  auto func_result = getOperation().walk([&](tf_device::ClusterFuncOp cluster) {
    cluster_func = cluster;
    return WalkResult::interrupt();
  });

  // Return if there is no tf_device::ClusterFuncOp in training loop.
  if (!func_result.wasInterrupted() || !cluster_func.hasValue()) {
    return;
  }

  // Get the function on device.
  auto device_func = cluster_func->getFunc();
  if (!device_func) return;

  TF::Conv2DOp first_conv;
  // A map maps block argument id to the convolutions consumes them.
  llvm::SmallDenseMap<unsigned, std::vector<Conv2DWithBlockSize>>
      argnum_and_convolutions;
  // A map maps block argument id to the number of users.
  llvm::SmallDenseMap<unsigned, int> argnum_num_users;

  // Find out the qualified convolutions and its block argument ids.
  auto conv2d_result = device_func.walk([&](TF::Conv2DOp conv2d) {
    Optional<BlockArgumentInfo> arg_num_and_num_users =
        GetConv2DInputArgNum(conv2d);
    if (arg_num_and_num_users.hasValue()) {
      // Get block size for the first convolution.
      int64_t block_size = GetConv2DBlockSize(conv2d);
      auto arg_num = arg_num_and_num_users.getValue().arg_num;
      auto num_users = arg_num_and_num_users.getValue().num_users;
      argnum_and_convolutions[arg_num].emplace_back(conv2d, block_size);
      argnum_num_users[arg_num] = num_users;
      return WalkResult::interrupt();
    }
    return WalkResult::advance();
  });
  if (!conv2d_result.wasInterrupted()) {
    return;
  }

  // Iterate through block argument and its convolution users. Space to depth
  // transform will be applied only if all the below conditions are satisfied:
  //  1. All the users of the block argument will lead to convolutions;
  //  2. block_size of for the space to depth transform for these convolutions
  //     are the same;
  //  3. block_size of for the space to depth transform for these convolutions
  //     are larger than 1.
  for (auto argnum_and_convolution : argnum_and_convolutions) {
    auto arg_num = argnum_and_convolution.getFirst();
    auto conv2d_and_block_sizes = argnum_and_convolution.getSecond();
    // Continue if number of users of the block argment doesn't equal to number
    // of transformable convolutions and there is no qualified convolution
    // for transform or block size is smaller than 2.
    if (argnum_num_users[arg_num] != conv2d_and_block_sizes.size() ||
        conv2d_and_block_sizes.empty()) {
      argnum_and_convolutions.erase(arg_num);
      continue;
    }
    int64_t block_size = conv2d_and_block_sizes[0].second;
    if (block_size < 2) {
      argnum_and_convolutions.erase(arg_num);
      continue;
    }
    // Continue if not all the block sizes for space to depth transform are the
    // same.
    for (auto conv2d_and_block_size : conv2d_and_block_sizes) {
      if (conv2d_and_block_size.second != block_size) {
        argnum_and_convolutions.erase(arg_num);
        break;
      }
    }
  }

  // If there is no qualified space to depth transform.
  if (argnum_and_convolutions.empty()) {
    return;
  }

  // Apply space to depth transform.
  for (auto argnum_and_convolution : argnum_and_convolutions) {
    auto conv2d_and_block_sizes = argnum_and_convolution.getSecond();
    int64_t block_size = conv2d_and_block_sizes[0].second;
    // Apply space to depth transform to the input on the host.
    HandleCluster(cluster_func.getValue(), block_size,
                  argnum_and_convolution.getFirst());
    // Transform the convolution.
    for (auto conv2d_and_block_size : conv2d_and_block_sizes) {
      HandleFirstConvolution(conv2d_and_block_size.first,
                             conv2d_and_block_size.second);
    }
  }
}

}  // namespace

std::unique_ptr<OperationPass<ModuleOp>> CreateTPUSpaceToDepthPass() {
  return std::make_unique<TPUSpaceToDepthPass>();
}

static PassRegistration<TPUSpaceToDepthPass> pass(
    "tf-tpu-space-to-depth-pass",
    "Adds ops that allow TPU program enable automaic space to depth for the"
    "convolution determined at JIT compile time.");

}  // namespace TFTPU
}  // namespace mlir


text:
package com.tnovoselec.beautifulweather.model;

import com.tnovoselec.beautifulweather.ui.IconViewEnum;

public class DaySectionData {

  private final DaySection daySection;
  private final float temperature;
  private final String description;
  private final double wind;
  private final double humidity;
  private final int background;
  private final IconViewEnum iconViewEnum;

  public DaySectionData(DaySection daySection, float temperature, String description, double wind, double humidity, int background, IconViewEnum iconViewEnum) {
    this.daySection = daySection;
    this.temperature = temperature;
    this.description = description;
    this.wind = wind;
    this.humidity = humidity;
    this.background = background;
    this.iconViewEnum = iconViewEnum;
  }

  public DaySection getDaySection() {
    return daySection;
  }

  public float getTemperature() {
    return temperature;
  }

  public String getDescription() {
    return description;
  }

  public double getWind() {
    return wind;
  }

  public double getHumidity() {
    return humidity;
  }

  public int getBackground() {
    return background;
  }

  public IconViewEnum getIconViewEnum() {
    return iconViewEnum;
  }
}


text:
<?php

namespace Kdig\OrientBundle\Form\Potteryvoc;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class VocPotteryDecorationinType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('decorationoption', null, array(
                'label' => 'Decoration Option',
                'required' => false,
                'widget_type'  => "inline"
            ))
            ->add('color', null, array(
                'label' => 'Color',
                'required' => false,
                'widget_type'  => "inline"
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Kdig\OrientBundle\Entity\Potteryvoc\VocPotteryDecorationin'
        ));
    }

    public function getName()
    {
        return 'kdig_orientbundle_potteryvoc_vocpotterydecorationintype';
    }
}


text:
<?php
namespace app\controllers;

use app\models\BlindsStructureLevel;
use yii\web\Controller;

class BlindStructureController extends Controller
{
    public function actionIndex()
    {
        $model = new BlindsStructureLevel();

        $levels = $model->getLevels();
        return $this->render('index', [
            'model' => $model,
            'levels' => $levels,
            'order' => count($levels),
            'breaksCount' => $model->getCount($model::TYPE_BREAK),
            'blindsCount' => $model->getCount($model::TYPE_BLINDS),
        ]);
    }

    public function actionAddLevel()
    {
        $model = BlindsStructureLevel::model();
        $levelData = \Yii::$app->request->post();

        if ($model->load($levelData) && $model->save()) {
           return $this->redirect('index');
        }
    }
}


text:
'''
some tests for pyBPMN20engine
'''

print 'importing Core'
import Core.Foundation.models
import Core.Common.models
import Core.Common.fonctions
import Core.Service.models
print 'OK\n'
print 'importing Conversation'
import Conversation.models
print 'OK\n'
print 'importing Process'
import Process.models
print 'OK\n'
print 'importing Actvities'
import Activities.models
print 'OK\n'
print 'importing Collaboration'
import Collaboration.models
print 'OK\n'
print 'importing Infrastructure'
import Infrastructure.models
print 'OK\n'
print 'importing HumanInteraction'
import HumanInteraction.models
print 'OK\n'


text: java -cp "cljs.jar;src" clojure.main node_repl.clj


text:
define([
    'amber/deploy',
    // --- packages to be deployed begin here ---
    'amber-knockout-demo/KnockoutDemo'
    // --- packages to be deployed end here ---
], function (amber) {
    return amber;
});


text:
layout: default
---

{{ page.title }}

  {{ content }}

  {% for post in site.posts %}
    {% if post.category == "news" or post.category == "announcement" or post.category == "essay" or post.category == "interview" %}

      {{ post.date | date: "%b %-d, %Y" }} | {{ post.category }}

{{ post.title | escape }}

by {% assign author = site.contributors | where:'short-name', post.author  | first %}{{ author.credit-name }}

{{ item.teaser | markdownify | remove: '
' | remove: '
' }}

    {% endif %}
    {% if post.category == "#Blackspecfic" %}

      {{ post.date | date: "%b %-d, %Y" }} | {{ post.category }}

{{ post.title | escape }}

by {{ post.author }}

{{ item.teaser | markdownify | remove: '
' | remove: '
' }}

    {% endif %}
  {% endfor %}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.atomique.ksar.Solaris;

import javax.swing.tree.DefaultMutableTreeNode;
import net.atomique.ksar.AllGraph;
import net.atomique.ksar.GraphDescription;
import net.atomique.ksar.kSar;
import net.atomique.ksar.kSarConfig;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

/**
 *
 * @author alex
 */
public class swapingSar extends AllGraph {

    public swapingSar(final kSar hissar) {
        super(hissar);
        Title = "Swapping";
        swpin = new TimeSeries("LWP in", org.jfree.data.time.Second.class);
        mysar.dispo.put("LWP swap in", swpin);
        bswin = new TimeSeries("pages in", org.jfree.data.time.Second.class);
        mysar.dispo.put("Swap page in", bswin);
        swpot = new TimeSeries("LWP out", org.jfree.data.time.Second.class);
        mysar.dispo.put("LWP swap out", swpot);
        bswot = new TimeSeries("pages out", org.jfree.data.time.Second.class);
        mysar.dispo.put("Swap page out", bswot);
        pswch = new TimeSeries("LWP switch", org.jfree.data.time.Second.class);
        mysar.dispo.put("LWP switch", pswch);
        // Collection
        ts_collection = new TimeSeriesCollection();
        ts_collection.addSeries(this.swpin);
        ts_collection.addSeries(this.bswin);
        ts_collection.addSeries(this.swpot);
        ts_collection.addSeries(this.bswot);
        ts_collection.addSeries(this.pswch);

    }

    public void add(final Second now,final Float swpinInt,final Float bswinInt,final Float swpotInt,final Float bswotInt,final Float pswchInt) {
        swpin.add(now, swpinInt, do_notify());
        bswin.add(now, bswinInt.floatValue() * 512, do_notify());
        swpot.add(now, swpotInt, do_notify());
        bswot.add(now, bswotInt.floatValue() * 512, do_notify());
        pswch.add(now, pswchInt, do_notify());
        number_of_sample++;
    }

    public void addtotree(final DefaultMutableTreeNode myroot) {
        mynode = new DefaultMutableTreeNode(new GraphDescription(this, "SOLARISSWAP", this.Title, null));
        mysar.add2tree(myroot,mynode);
    }

    public JFreeChart makegraph(final Second g_start,final  Second g_end) {
        mygraph = ChartFactory.createTimeSeriesChart(this.getGraphTitle(), "", "per second", ts_collection, true, true, false);
        setbackgroundimage(mygraph);
        XYPlot xyplot = (XYPlot) mygraph.getPlot();
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
        renderer.setBaseStroke(kSarConfig.DEFAULT_STROKE);
        renderer.setSeriesPaint(0, kSarConfig.color1);
        renderer.setSeriesPaint(1, kSarConfig.color2);
        renderer.setSeriesPaint(2, kSarConfig.color3);
        renderer.setSeriesPaint(3, kSarConfig.color4);
        renderer.setSeriesPaint(4, kSarConfig.color5);
        if (g_start != null) {
            DateAxis dateaxis1 = (DateAxis) mygraph.getXYPlot().getDomainAxis();
            dateaxis1.setRange(g_start.getStart(), g_end.getEnd());
        }
        return mygraph;
    }

    private final TimeSeries swpin;
    private final TimeSeries bswin;
    private final TimeSeries swpot;
    private final TimeSeries bswot;
    private final TimeSeries pswch;
    private final  TimeSeriesCollection ts_collection;
}


text:
USING_NS_CC;
using namespace CocosDenshion;

typedef enum{
	kEffectSwichCannon = 0,
	kEffectShoot,
	kEffectFishNet,
	kEffectCoins
}EffectType;

class PersonalAudioEngine :
	public SimpleAudioEngine
{
public:
	PersonalAudioEngine(void);
	~PersonalAudioEngine(void);
	static PersonalAudioEngine* sharedEngine();

	bool init();

	//ÊÇ·ñ¿ªÆô±³¾°ÒôÀÖ
	void setBackgroundMusic(bool isOn);

	//ÊÇ·ñ¿ªÆôÒôЧ
	//void setEffects(bool isOn);

	void playEffects(EffectType type);

	void purge();

	CC_SYNTHESIZE(unsigned int, _bgMusicId, BgMusicId);
	CC_SYNTHESIZE(unsigned int, _netSoundId, NetSoundId);
	CC_SYNTHESIZE(unsigned int, _fireSoundId, FireSoundId);
	CC_SYNTHESIZE(unsigned int, _btnSoundId, BtnSoundId);

};


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_2752221</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753462212</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Kroonprinshoeve</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Kroonprinshoeve</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Kroonprinshoeve</Appelation>
        <LocationNameType>farm</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>4.803319999999999</Longitude>
        <Latitude>51.787729999999996</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/2752221</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
package commander

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/steelseries/golisp"
	"github.com/timburks/gott/operations"
	gott "github.com/timburks/gott/types"
)

// file-global pointers to editor objects
var commander *Commander
var editor gott.Editor

func makePrimitiveFunction(name string, action func()) {
	golisp.MakePrimitiveFunction(name, "0",
		func(args *golisp.Data, env *golisp.SymbolTableFrame) (result *golisp.Data, err error) {
			action()
			return nil, err
		})
}

func argumentCountValue(name string, args *golisp.Data, env *golisp.SymbolTableFrame) (int, error) {
	n := 1
	val := golisp.Car(args)
	if val != nil {
		if !golisp.IntegerP(val) {
			return 0, errors.New(fmt.Sprintf("%s requires an integer argument", name))
		}
		n = int(golisp.IntegerValue(val))
	} else {
		n = commander.getMultiplier()
	}
	return n, nil
}

func makePrimitiveFunctionWithMultiplier(name string, action func(multiplier int)) {
	golisp.MakePrimitiveFunction(name, "0|1",
		func(args *golisp.Data, env *golisp.SymbolTableFrame) (result *golisp.Data, err error) {
			if n, err := argumentCountValue(name, args, env); err == nil {
				action(n)
			}
			return nil, err
		})
}

func argumentStringValue(name string, args *golisp.Data, env *golisp.SymbolTableFrame) (string, error) {
	n := ""
	val := golisp.Car(args)
	if val != nil {
		if !golisp.StringP(val) {
			return "", errors.New(fmt.Sprintf("%s requires a string argument", name))
		}
		n = golisp.StringValue(val)
	}
	return n, nil
}

func makePrimitiveFunctionWithString(name string, action func(s string)) {
	golisp.MakePrimitiveFunction(name, "1",
		func(args *golisp.Data, env *golisp.SymbolTableFrame) (result *golisp.Data, err error) {
			if n, err := argumentStringValue(name, args, env); err == nil {
				action(n)
			}
			return nil, err
		})
}

func init() {
	golisp.Global.BindTo(
		golisp.SymbolWithName("TWO"),
		golisp.IntegerWithValue(2))

	makePrimitiveFunctionWithMultiplier("down", func(m int) {
		editor.MoveCursor(gott.MoveDown, m)
	})

	makePrimitiveFunctionWithMultiplier("up", func(m int) {
		editor.MoveCursor(gott.MoveUp, m)
	})

	makePrimitiveFunctionWithMultiplier("left", func(m int) {
		editor.MoveCursor(gott.MoveLeft, m)
	})

	makePrimitiveFunctionWithMultiplier("right", func(m int) {
		editor.MoveCursor(gott.MoveRight, m)
	})

	makePrimitiveFunctionWithMultiplier("page-down", func(m int) {
		editor.PageDown(m)
	})

	makePrimitiveFunctionWithMultiplier("page-up", func(m int) {
		editor.PageUp(m)
	})

	makePrimitiveFunctionWithMultiplier("half-page-down", func(m int) {
		editor.HalfPageDown(m)
	})

	makePrimitiveFunctionWithMultiplier("half-page-up", func(m int) {
		editor.HalfPageUp(m)
	})

	makePrimitiveFunctionWithMultiplier("beginning-of-line", func(m int) {
		editor.MoveToBeginningOfLine()
	})

	makePrimitiveFunctionWithMultiplier("end-of-line", func(m int) {
		editor.MoveToEndOfLine()
	})

	makePrimitiveFunctionWithMultiplier("next-word", func(m int) {
		editor.MoveCursorToNextWord(m)
	})

	makePrimitiveFunctionWithMultiplier("previous-word", func(m int) {
		editor.MoveCursorToPreviousWord(m)
	})

	makePrimitiveFunctionWithMultiplier("change-window", func(m int) {
		editor.SelectWindow(m)
	})

	makePrimitiveFunctionWithMultiplier("insert-at-cursor", func(m int) {
		editor.Perform(&operations.Insert{Position: gott.InsertAtCursor, Commander: commander}, m)
	})

	makePrimitiveFunctionWithMultiplier("insert-after-cursor", func(m int) {
		editor.Perform(&operations.Insert{Position: gott.InsertAfterCursor, Commander: commander}, m)
	})

	makePrimitiveFunctionWithMultiplier("insert-at-start-of-line", func(m int) {
		editor.Perform(&operations.Insert{Position: gott.InsertAtStartOfLine, Commander: commander}, m)
	})

	makePrimitiveFunctionWithMultiplier("insert-after-end-of-line", func(m int) {
		editor.Perform(&operations.Insert{Position: gott.InsertAfterEndOfLine, Commander: commander}, m)
	})

	makePrimitiveFunctionWithMultiplier("insert-at-new-line-below-cursor", func(m int) {
		editor.Perform(&operations.Insert{Position: gott.InsertAtNewLineBelowCursor, Commander: commander}, m)
	})

	makePrimitiveFunctionWithMultiplier("insert-at-new-line-above-cursor", func(m int) {
		editor.Perform(&operations.Insert{Position: gott.InsertAtNewLineAboveCursor, Commander: commander}, m)
	})

	makePrimitiveFunctionWithMultiplier("delete-character", func(m int) {
		editor.Perform(&operations.DeleteCharacter{}, m)
	})

	makePrimitiveFunctionWithMultiplier("join-line", func(m int) {
		editor.Perform(&operations.JoinLine{}, m)
	})

	makePrimitiveFunctionWithMultiplier("paste", func(m int) {
		editor.Perform(&operations.Paste{}, m)
	})

	makePrimitiveFunctionWithMultiplier("reverse-case-character", func(m int) {
		editor.Perform(&operations.ReverseCaseCharacter{}, m)
	})

	makePrimitiveFunctionWithMultiplier("undo", func(m int) {
		editor.PerformUndo()
	})

	makePrimitiveFunctionWithMultiplier("repeat", func(m int) {
		editor.Repeat()
	})

	makePrimitiveFunctionWithMultiplier("change-word", func(m int) {
		editor.Perform(&operations.ChangeWord{Commander: commander}, m)
	})

	makePrimitiveFunctionWithMultiplier("delete-row", func(m int) {
		editor.Perform(&operations.DeleteRow{}, m)
	})

	makePrimitiveFunctionWithMultiplier("delete-word", func(m int) {
		editor.Perform(&operations.DeleteWord{}, m)
	})

	makePrimitiveFunctionWithMultiplier("yank-row", func(m int) {
		editor.YankRow(m)
	})

	makePrimitiveFunction("command-mode", func() {
		commander.mode = gott.ModeCommand
		commander.commandText = ""
	})

	makePrimitiveFunction("lisp-mode", func() {
		commander.mode = gott.ModeLisp
		commander.lispText = "("
	})

	makePrimitiveFunction("search-forward-mode", func() {
		commander.mode = gott.ModeSearchForward
		commander.searchText = ""
	})

	makePrimitiveFunction("search-backward-mode", func() {
		commander.mode = gott.ModeSearchBackward
		commander.searchText = ""
	})

	makePrimitiveFunction("repeat-search-forward", func() {
		editor.PerformSearchForward(commander.searchText)
	})

	makePrimitiveFunction("repeat-search-backward", func() {
		editor.PerformSearchBackward(commander.searchText)
	})

	makePrimitiveFunctionWithMultiplier("replace-character", func(m int) {
		if commander.getLastKey() == gott.KeySpace {
			editor.Perform(&operations.ReplaceCharacter{Character: rune(' ')}, m)
		} else {
			editor.Perform(&operations.ReplaceCharacter{Character: rune(commander.getLastCh())}, m)
		}
	})

	makePrimitiveFunctionWithString("print", func(s string) {
		if commander.batch {
			// if we are running in batch (eval) mode, write to output
			os.Stdout.Write([]byte(s + "\n"))
		} else {
			// if we are running in the editor, write to buffer 0
			editor.SelectWindow(0)
			editor.AppendBytes([]byte(s))
		}
	})
}

func (c *Commander) parseEval(command string) string {
	commander = c
	editor = c.editor
	value, err := golisp.ParseAndEvalAll(command)
	if err != nil {
		return fmt.Sprintf("ERR %+v", err)
	} else {
		return golisp.String(value)
	}
}

func (c *Commander) ParseEvalFile(filename string) string {
	bytes, err := ioutil.ReadFile(filename)
	if err == nil {
		contents := string(bytes)
		c.batch = true
		return c.parseEval(contents)
	} else {
		return err.Error()
	}
}


text:
package org.gbif.population.spark;

import java.awt.geom.Point2D;

/**
 * Utilities when dealing with Mercator projected tiles.
 */
public class MercatorUtils {

  /**
   * For the given coordinates return the address of the tile on which they would appear at the zoom.
   *
   * @param lat  Decimal latitude
   * @param lng  Decimal longitude
   * @param zoom Zoom level of the target tile
   *
   * @return The x,y coordinate address of the target tile at the given zoom level or null if not plotable
   */
  public static Point2D toXY(Double lat, Double lng, int zoom) {

    if (!isPlottable(lat, lng)) {
      return null;
    }

    Point2D normalizedPixels = toNormalisedPixelCoords(lat, lng);
    int scale = 1 << zoom;
    // truncating to int removes the fractional pixel offset
    int x = (int) (normalizedPixels.getX() * scale);
    int y = (int) (normalizedPixels.getY() * scale);
    return new Point2D.Double(x, y);
  }

  /**
   * Google maps cover +/- 85 degrees only.
   *
   * @return true if the location is plottable on a map
   */
  static boolean isPlottable(Double lat, Double lng) {
    return lat != null && lng != null && lat >= -85d && lat <= 85d && lng >= -180 && lng <= 180;
  }

  /**
   * Returns the lat/lng as an "Offset Normalized Mercator" pixel coordinate.
   * This is a coordinate that runs from 0..1 in latitude and longitude with 0,0 being
   * top left. Normalizing means that this routine can be used at any zoom level and
   * then multiplied by a power of two to get actual pixel coordinates.
   */
  static Point2D toNormalisedPixelCoords(double lat, double lng) {
    if (lng > 180) {
      lng -= 360;
    }
    lng /= 360;
    lng += 0.5;
    lat = 0.5 - ((Math.log(Math.tan((Math.PI / 4) + ((0.5 * Math.PI * lat) / 180))) / Math.PI) / 2.0);
    return new Point2D.Double(lng, lat);
  }
}


text:
import path from 'path'
import sqlite3 from 'sqlite3'

const client = sqlite3.verbose()

const db = new client.Database(path.resolve(__dirname, '../../databases/database.sqlite3'))

db.serialize(() => {
  // create default table
  db.run("CREATE TABLE if not exists token (token TEXT)");
  db.run(``)
})
db.close()

class DB {
  execCommand(cmds) {
    let commands = cmds
    if (!Array.isArray(commands)) {
      commands = [commands]
    }
    db.serialize(() => {
      commands.forEach(cmd => {
        db.run(cmd)
      })
    })
    db.close()
  }
  refreshToken() {
    let cmd = `
      upldate set where account = '' and type = ''
    `

  }

}


text:
---
title: Wrapping JavaScript Functions
date: 2014-01-13 23:00
author: Blake Embrey
template: article.jade
---

In the modern age of web applications and development, it seems we are constantly adding side effects to every part of our applications - everything from analytics to event triggering. Unfortunately in a lot of cases, we tend to cram this functionality into function with the useful stuff. As programmers, this causes numerous issues down the line - especially when it comes to refactoring and code comprehensibility.

A simple way to keep this functionality apart from the core code is create a helpful utility function to manage it for you. And to keep our code readability, we shouldn't allow anything advanced that can break our understanding of the original function. That means we don't want to be able to alter the original function, but we can still trigger any side effects we need to inline with the original function.

```javascript
var before = function (before, fn) {
  return function () {
    before.apply(this, arguments);
    return fn.apply(this, arguments);
  };
};
```

To use the function, we can pass any function in as the first argument and the original function we want to wrap as the second argument. For example, we could do `before(logger, add)`. Even without seeing the `logger` or `add` functions, we can imagine what each do. And because we are passing all the arguments to the side effect function, we can do stuff with the information.

One thing I find myself doing is checking what arguments were passed to a certain function. To do this now, we can `before(console.log.bind(console), fn)`. Now, let's implement the reverse functionality.

```javascript
var after = function (fn, after) {
  return function () {
    var result = fn.apply(this, arguments);
    after.call(this, result);
    return result;
  };
};
```

This is extremely similar to the first example. The main difference is that the first function passed in is the side effect, but now we have the side effect running after our wrapped function. Adapting the previous example, we can now do `after(add, logger)` and the logger will execute after the result is computed with the same arguments.

One cool thing we could actually do, is to run argument validation in the `before` function. Consider this.

```javascript
var validAdd = before(function () {
  for (var i = 0; i < arguments.length; i++) {
    if (typeof arguments[i] !== 'number') {
      throw new TypeError('Expected a number');
    }
  }
}, add);
```

We can also put these two functions together and create a new utility. This one allows us to pass both a function before and after our core functionality. E.g. `around(logger, add, logger)`.

```javascript
var around = function (under, fn, over) {
  return before(under, after(fn, over));
};
```

## Allow unlimited before and after functions

We can also adapt the functions to accept a variable number of arguments as the `before` and `after` functions. However, we can't do this to the `around` utility since we wouldn't know which argument is the core function.

```javascript
var __slice = Array.prototype.slice;

var before = function (/* ...before, fn */) {
  var fn     = arguments[arguments.length - 1];
  var before = __slice.call(arguments, -1);

  return function () {
    for (var i = 0; i < before.length; i++) {
      before[i].apply(this, arguments);
    }

    return fn.apply(this, arguments);
  };
};

var after = function (fn /*, ...after */) {
  var after = __slice.call(arguments, 1);

  return function () {
    var result = fn.apply(this, arguments);

    for (var i = 0; i < after.length; i++) {
      after.call(this, result);
    }

    return result;
  };
};
```

## Advanced wrapping utility

So far we've seen some function wrapping utilities that are purely for side effects. They have no capability to alter the main function arguments or change the function result. For something more advanced than trigger side-effects, we might to want to use something a little different.

```javascript
var __slice = Array.prototype.slice;

var wrap = function (fn, wrap) {
  return function () {
    return wrap.apply(this, [fn].concat(__slice.call(arguments)));
  };
};
```

This is actually pretty similar the `wrap` function used in Prototype.js. It allows us to call a custom wrapper function with the original function and all the arguments. But, how do we even use this?

```javascript
var addAndMultiplyBy2 = wrap(add, function (originalFn, a, b) {
  return 2 * originalFn(a, b);
});
```


text:
'use strict'

module.exports = {
	"info": require('./info.js'),
	"curl": require('./curl.js'),
	"httpie": require('./httpie.js'),
	"wget": require('./wget.js')
}


text:
using std::string;
#include <utility>
#include <vector>

#include <iostream>
#include <fst/fstlib.h>
#include "stringcompile.h"
#include "stringfile.h"
#include "prefix_tree.h"

namespace fst {
namespace internal {

// Helper class for constructing string maps.
template <class Arc>
class StringMapCompiler {
 public:
  using Label = typename Arc::Label;
  using Weight = typename Arc::Weight;

  explicit StringMapCompiler(StringTokenType itype = BYTE,
                             StringTokenType otype = BYTE,
                             const SymbolTable *isyms = nullptr,
                             const SymbolTable *osyms = nullptr)
      : itype_(itype),
        otype_(otype),
        isyms_(GetSymbolTable(itype_, isyms)),
        osyms_(GetSymbolTable(otype_, osyms)) {}

  bool Add(const string &istring, const string &ostring,
           const Weight &weight = Weight::One()) {
    if (!StringToLabels<Label>(istring, &ilabels_, itype_, isyms_.get())) {
      return false;
    }
    if (!StringToLabels<Label>(ostring, &olabels_, otype_, osyms_.get())) {
      return false;
    }
    ptree_.Add(ilabels_, olabels_, weight);
    return true;
  }

  // Also parses a weight string.
  bool Add(const string &istring, const string &ostring,
           const string &weight) {
    std::istringstream strm(weight);
    Weight w;
    strm >> w;
    if (!strm) {
      LOG(ERROR) << "StringMapCompiler::Add: Bad weight: " << weight;
      return false;
    }
    return Add(istring, ostring, w);
  }

  void Compile(MutableFst<Arc> *fst,
               bool attach_input_symbols = true,
               bool attach_output_symbols = true) const {
    ptree_.ToFst(fst);
    // Optionally attaches symbol tables.
    if (attach_input_symbols) fst->SetInputSymbols(isyms_.get());
    if (attach_output_symbols) fst->SetOutputSymbols(osyms_.get());
  }

 private:
  const StringTokenType itype_;
  const StringTokenType otype_;
  const std::unique_ptr<SymbolTable> isyms_;
  const std::unique_ptr<SymbolTable> osyms_;
  PrefixTree<Arc> ptree_;

  // Transient data.
  std::vector<Label> ilabels_;
  std::vector<Label> olabels_;
};

}  // namespace internal

// Compiles deterministic FST representing the union of the cross-product of
// pairs of weighted string cross-products from a TSV file of string triples.
template <class Arc>
bool CompileStringFile(const string &fname, MutableFst<Arc> *fst,
                       StringTokenType itype = BYTE,
                       StringTokenType otype = BYTE,
                       const SymbolTable *isyms = nullptr,
                       const SymbolTable *osyms = nullptr,
                       bool attach_input_symbols = true,
                       bool attach_output_symbols = true) {
  internal::StringMapCompiler<Arc> compiler(itype, otype, isyms, osyms);
  internal::ColumnStringFile csf(fname);
  if (csf.Done()) return false;  // File opening failed.
  for (; !csf.Done(); csf.Next()) {
    const auto &line = csf.Row();
    switch (line.size()) {
      case 1: {
        const string iostring(line[0]);
        if (!compiler.Add(iostring, iostring)) return false;
        break;
      }
      case 2: {
        if (!compiler.Add(string(line[0]), string(line[1]))) return false;
        break;
      }
      case 3: {
        if (!compiler.Add(string(line[0]), string(line[1]),
                          string(line[2]))) {
          return false;
        }
        break;
      }
      default: {
        LOG(ERROR) << "CompileStringFile: Ill-formed line "
                   << csf.LineNumber() << " in file "
                   << csf.Filename();
        return false;
      }
    }
  }
  compiler.Compile(fst, attach_input_symbols, attach_output_symbols);
  return true;
}

// Compiles deterministic FST representing the union of the cross-product of
// pairs of weighted string cross-products from a vector of vector of strings.
template <class Arc>
bool CompileStringMap(const std::vector<std::vector<string>> &lines,
                      MutableFst<Arc> *fst, StringTokenType itype = BYTE,
                      StringTokenType otype = BYTE,
                      const SymbolTable *isyms = nullptr,
                      const SymbolTable *osyms = nullptr,
                      bool attach_input_symbols = true,
                      bool attach_output_symbols = true) {
  internal::StringMapCompiler<Arc> compiler(itype, otype, isyms, osyms);
  for (const auto &line : lines) {
    switch (line.size()) {
      case 1: {
        if (!compiler.Add(line[0], line[0])) return false;
        break;
      }
      case 2: {
        if (!compiler.Add(line[0], line[1])) return false;
        break;
      }
      case 3: {
        if (!compiler.Add(line[0], line[1], line[2])) return false;
        break;
      }
      default: {
        LOG(ERROR) << "CompileStringMap: Ill-formed line";
        return false;
      }
    }
  }
  compiler.Compile(fst, attach_input_symbols, attach_output_symbols);
  return true;
}

}  // namespace fst

#endif  // PYNINI_STRINGMAP_H_


text:
'use strict';

var _ = require('underscore');
var winston = require('winston');

module.exports = function(level) {
  level = 5 - level;
  var levels = {
    trace: 0,
    "debug": 1,
    "info": 2,
    "warn": 3,
    "error": 4,
    "silent": 5
  };

  if(level > 5) level = 5;
  if(level < 1) level = 0;

  var lookup = _.invert(levels);
  var logger = new winston.Logger({
    transports: [
      new winston.transports.Console({
        level: lookup[level],
        stderrLevels: Object.keys(levels)
      })
    ],
    level: lookup[level],
    levels: levels
  });

  return logger;
};


text:
BEGIN;

DROP MATERIALIZED VIEW cg.comic_strip_count;

COMMIT;


text:
/* @flow */
var config = require('config');
var dbConfig = config.get('Database');
var winston = require('winston');
var r = require('rethinkdb');

/* Timeout to wait for reconnection */
var timeOut = 1;

exports.connect = function() {
  if (!exports.conn) {
    r.connect(dbConfig, function(err, conn) {
      if (err) {
        timeOut = (++timeOut % 9);
        winston.error('[RethinkDB] ' + err.message);
        winston.info("[RethinkDB] next retry in " + timeOut + " seconds")
        setTimeout(exports.connect, timeOut * 1000);
      } else {
        exports.conn = conn;
        timeOut = 1;
      }
    });
  }
}

/**
 * Check db conenection
 */
exports.dbChecker = function(req, res, next) {
  if (exports.conn) {
    next();
  } else {
    winston.error('DB Connection not ready');
    res.status(200).send({
      ok: false
    });
  }
}

exports.connect();


text:
package cronapi;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashSet;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.ReflectionUtils;

import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;

import cronapi.rest.security.CronappSecurity;

public class SecurityBeanFilter extends SimpleBeanPropertyFilter {

  public static boolean includeProperty(Class clazzToCheck, String key, String method) {
    RestClient client = RestClient.getRestClient();
    if(client.getRequest() != null) {
      HttpServletRequest request = RestClient.getRestClient().getRequest();
      if(clazzToCheck != null) {
        if(request != null) {
          if(request.getAttribute("BeanPropertyFilter") != null) {
            HashSet<String> ignores = (HashSet<String>)request.getAttribute("BeanPropertyFilter");
            String name = clazzToCheck.getName() + "#" + key;
            if(ignores.contains(name))
              return false;
          }
        }

        Class clazz = clazzToCheck;
        if(clazz != null) {
          Field field = ReflectionUtils.findField(clazz, key);
          if(field != null) {
            Annotation security = field.getAnnotation(CronappSecurity.class);

            if(security instanceof CronappSecurity) {
              CronappSecurity cronappSecurity = (CronappSecurity)security;
              try {
                Method methodPermission = cronappSecurity.getClass().getMethod(method==null?client.getMethod().toLowerCase():method.toLowerCase());

                if(methodPermission != null) {
                  String value = (String)methodPermission.invoke(cronappSecurity);

                  if(value != null && !value.isEmpty()) {
                    boolean authorized = false;

                    String[] authorities = value.trim().split(";");

                    for(String role : authorities) {
                      if(role.equalsIgnoreCase("authenticated")) {
                        authorized = RestClient.getRestClient().getUser() != null;
                        if(authorized)
                          break;
                      }
                      if(role.equalsIgnoreCase("permitAll") || role.equalsIgnoreCase("public")) {
                        authorized = true;
                        break;
                      }
                      for(GrantedAuthority authority : RestClient.getRestClient().getAuthorities()) {
                        if(role.equalsIgnoreCase(authority.getAuthority())) {
                          authorized = true;
                          break;
                        }
                      }

                      if(authorized)
                        break;
                    }

                    if(!authorized) {
                      return false;
                    }
                  }
                }

              }
              catch(Exception e) {
                //
              }
            }
          }
        }

      }
    }
    return true;
  }

  @Override
  protected boolean include(BeanPropertyWriter writer) {
    return includeProperty(writer.getMember().getDeclaringClass(), writer.getName(), "GET");
  }

  @Override
  protected boolean include(PropertyWriter writer) {
    if(writer instanceof BeanPropertyWriter) {
      return includeProperty(((BeanPropertyWriter)writer).getMember().getDeclaringClass(), writer.getName(), "GET");
    }

    return true;
  }

}


text:
namespace GameEngine
{
   public class PlayerQuest
    {
            public Quest Details { get; set; }
            public bool IsCompleted { get; set; }

            public PlayerQuest(Quest details)
            {
                Details = details;
                IsCompleted = false;
            }
        }
}