text:
package com.cyngn.exovert.generate.rest;

import com.cyngn.exovert.generate.entity.EntityGeneratorHelper;
import com.cyngn.exovert.generate.server.rest.TypeMap;
import com.cyngn.exovert.generate.storage.AccessorGenerator;
import com.cyngn.exovert.util.Disk;
import com.cyngn.exovert.util.GeneratorHelper;
import com.cyngn.exovert.util.MetaData;
import com.cyngn.exovert.util.Udt;
import com.cyngn.vertx.async.ResultContext;
import com.cyngn.vertx.web.HttpHelper;
import com.cyngn.vertx.web.JsonUtil;
import com.cyngn.vertx.web.RestApi;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.TableMetadata;
import com.google.common.base.CaseFormat;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
import org.apache.commons.lang.StringUtils;

import javax.lang.model.element.Modifier;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * Generates a REST interface for doing CRUD operations
 *
 * @author truelove@cyngn.com (Jeremy Truelove) 9/1/15
 */
public class RestGenerator {

    private static final String SUPPORTED_API_FIELD = "supportedApi";
    private static final String PRIMARY_KEY_FIELD = "primaryKey";

    public static void generate(Collection<TableMetadata> tables) throws IOException {
        String namespaceToUse = MetaData.instance.getRestNamespace();

        createUtilClass(namespaceToUse);

        for (TableMetadata table : tables) {
            String tableName = table.getName();
            String rawName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName);
            String name = rawName + "Api";
            String dalName = rawName + "Dal";

            TypeSpec.Builder restBuilder = TypeSpec.classBuilder(name).addModifiers(Modifier.PUBLIC);

            restBuilder.addField(GeneratorHelper.getLogger(namespaceToUse, name));

            restBuilder.addJavadoc(GeneratorHelper.getJavaDocHeader("REST Api for Cassandra entity - {@link " +
                    ClassName.get(MetaData.instance.getTableNamespace(), rawName) + "}", MetaData.instance.getUpdateTime()));

            restBuilder.addSuperinterface(RestApi.class);
            addMemberVars(tableName, dalName, restBuilder);

            restBuilder.addMethod(getConstructor(dalName, EntityGeneratorHelper.getPrimaryKey(table)));

            addSave(restBuilder, rawName);
            restBuilder.addMethod(getDelete(rawName));
            restBuilder.addMethod(getGet(rawName));
            getGetAll(rawName, restBuilder, table);
            restBuilder.addMethod(getSupportedApi());
            restBuilder.addMethod(getQueryConverter(table));

            JavaFile javaFile = JavaFile.builder(namespaceToUse, restBuilder.build()).build();
            Disk.outputFile(javaFile);
        }
    }

    private static void createUtilClass(String namespaceToUse) throws IOException {
        TypeSpec.Builder utilBuilder = TypeSpec.classBuilder("RestUtil").addModifiers(Modifier.PUBLIC)
            .addJavadoc(GeneratorHelper.getJavaDocHeader
                    ("Central place to put shared functions for REST call processing.", MetaData.instance.getUpdateTime()))
            .addMethod(getIsValidMethod());
        utilBuilder.addMethod(generateGetAllProcessingMethod());
        utilBuilder.addField(GeneratorHelper.getLogger(namespaceToUse, "RestUtil"));
        JavaFile javaFile = JavaFile.builder(namespaceToUse, utilBuilder.build()).build();
        Disk.outputFile(javaFile);
    }

    private static MethodSpec getConstructor(String dalName, List<String> primaryKey) {
        MethodSpec.Builder builder = MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ClassName.get(MetaData.instance.getDalNamespace(), dalName), "storage", Modifier.FINAL)
                .addStatement("this.storage = $L", "storage")
                .addCode("$L = new $T[]", PRIMARY_KEY_FIELD, String.class).beginControlFlow("");

        boolean first = true;
        for (String key : primaryKey) {
            if(first) {
                builder.addCode("$S", key);
                first = false;
            } else { builder.addCode(",\n$S", key); }
        }
        builder.addCode("\n");
        builder.endControlFlow("");

        return builder.build();
    }

    private static void addMemberVars(String rawClass, String dalName, TypeSpec.Builder builder) {
        String storageNamespace = MetaData.instance.getDalNamespace();
        String apiConstant = rawClass.toUpperCase() + "_API";
        String apiConstantAll = rawClass.toUpperCase() + "_ALL_API";

        builder.addField(FieldSpec.builder(String.class, apiConstant, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                .initializer("$S", MetaData.instance.getRestPrefix() + rawClass).build());

        builder.addField(FieldSpec.builder(String.class, apiConstantAll, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                .initializer("$S", MetaData.instance.getRestPrefix() + rawClass + "_all").build());

        builder.addField(ClassName.get(storageNamespace, dalName), "storage", Modifier.PRIVATE, Modifier.FINAL);

        CodeBlock block = CodeBlock.builder().beginControlFlow("")
                .add("new RestApi.RestApiDescriptor($T.POST, $L, this::save),\n", HttpMethod.class, apiConstant)
                .add("new RestApi.RestApiDescriptor($T.GET, $L, this::get),\n", HttpMethod.class, apiConstant)
                .add("new RestApi.RestApiDescriptor($T.DELETE, $L, this::delete),\n", HttpMethod.class, apiConstant)
                .add("new RestApi.RestApiDescriptor($T.GET, $L, this::getAll)\n", HttpMethod.class, apiConstantAll)
                .unindent().add("}")
                .build();

        builder.addField(FieldSpec.builder(RestApi.RestApiDescriptor[].class, SUPPORTED_API_FIELD, Modifier.PRIVATE,
                Modifier.FINAL)
                .initializer(block)
                .build());

        builder.addField(String[].class, "primaryKey", Modifier.FINAL);
    }

    private static void addSave(TypeSpec.Builder builder, String entityName) {
        builder.addMethod(getSave(entityName));
        builder.addMethod(getInternalSave(entityName));
    }

    private static MethodSpec getSave(String entityName) {
        return MethodSpec.methodBuilder("save")
                .addJavadoc(getJavaDoc("Save"), ClassName.get(MetaData.instance.getTableNamespace(), entityName))
                .addParameter(RoutingContext.class, "context", Modifier.FINAL)
                .addStatement("$T request = context.request()", HttpServerRequest.class)
                .addModifiers(Modifier.PUBLIC)
                .beginControlFlow("if(request.isEnded())")
                .addStatement("save(context, context.getBody())")
                .nextControlFlow("else")
                .addStatement("request.bodyHandler(buffer -> save(context, buffer))")
                .endControlFlow()
                .build();
    }

    private static MethodSpec getInternalSave(String entityName) {
        ClassName clazz = ClassName.get(MetaData.instance.getTableNamespace(), entityName);

        return MethodSpec.methodBuilder("save")
                .addJavadoc(getJavaDoc("Save") +
                                "\nNOTE: this method is left intentionally package protected to allow you to call it in a different way\n",
                        clazz)
                .addParameter(RoutingContext.class, "context", Modifier.FINAL)
                .addParameter(Buffer.class, "body", Modifier.FINAL)
                .addStatement("$T entity = $T.parseJsonToObject(body.toString(), $L.class)", clazz, JsonUtil.class, entityName)
                .beginControlFlow("if(entity == null)")
                .addStatement("$T.processErrorResponse($S + body, context.response(), $T.BAD_REQUEST.code())",
                        HttpHelper.class, "Failed to parse body: ", HttpResponseStatus.class)
                .addStatement("return")
                .endControlFlow()
                .addCode("\nstorage.save(entity, result -> ", Consumer.class)
                .beginControlFlow("")
                .beginControlFlow("if(result.succeeded)")
                .addStatement("$T.processResponse(context.response())", HttpHelper.class)
                .nextControlFlow("else if(result.error != null)")
                .addStatement("String error = $S + entity.toString() + $S + result.error.getMessage()",
                        "Could not persist ", ", error: ")
                .addStatement("logger.error($S,  error)", "save - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.INTERNAL_SERVER_ERROR.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .nextControlFlow("else")
                .addStatement("String error = $S + entity.toString() + $S + result.errorMessage", "Could not persist ",
                        ", error: ")
                .addStatement("logger.error($S,  error)", "save - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.BAD_REQUEST.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .endControlFlow()
                .endControlFlow(")")
                .build();

    }

    private static MethodSpec getDelete(String entityName) {
        ClassName clazz = ClassName.get(MetaData.instance.getTableNamespace(), entityName);

        return MethodSpec.methodBuilder("delete")
                .addJavadoc(getJavaDoc("Delete"), clazz)
                .addParameter(RoutingContext.class, "context", Modifier.FINAL)
                .addModifiers(Modifier.PUBLIC)
                .addCode("// if query params aren't valid a HttpResponseStatus.BAD_REQUEST will be sent with the missing field\n")
                .addStatement("$T queryKey = null", Object[].class)
                .beginControlFlow("if($T.isValid(context.request(), primaryKey))",
                        ClassName.get(MetaData.instance.getRestNamespace(), "RestUtil"))
                .addStatement("queryKey = convertQueryString($L)", "context")
                .endControlFlow()
                .beginControlFlow("\nif(queryKey != null)")
                .addCode("storage.delete(result -> ", Consumer.class)
                .beginControlFlow("")
                .beginControlFlow("if(result.succeeded)")
                .addStatement("$T.processResponse(context.response())", HttpHelper.class)
                .nextControlFlow("else if (result.error != null)")
                .addStatement("String error = $S + context.request().uri() + $S + result.error.getMessage()",
                        "Could not DELETE with query: ", " error: ")
                .addStatement("logger.error($S,  error)", "delete - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.INTERNAL_SERVER_ERROR.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .nextControlFlow("else")
                .addStatement("String error = $S + context.request().uri() + $S + result.error.getMessage()",
                        "Could not DELETE with query: ", " error: ")
                .addStatement("logger.error($S, error)", "delete - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.BAD_REQUEST.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .endControlFlow()
                .endControlFlow(", queryKey)")
                .endControlFlow()
                .build();
    }

    private static MethodSpec getGet(String entityName) {
        ClassName clazz = ClassName.get(MetaData.instance.getTableNamespace(), entityName);

        return MethodSpec.methodBuilder("get")
                .addJavadoc(getJavaDoc("Get"), clazz)
                .addParameter(RoutingContext.class, "context", Modifier.FINAL)
                .addModifiers(Modifier.PUBLIC)
                .addCode("// if query params aren't valid a HttpResponseStatus.BAD_REQUEST will be sent with the missing field\n")
                .addStatement("$T queryKey = null", Object[].class)
                .beginControlFlow("if($T.isValid(context.request(), primaryKey))",
                        ClassName.get(MetaData.instance.getRestNamespace(), "RestUtil"))
                .addStatement("queryKey = convertQueryString($L)", "context")
                .endControlFlow()
                .beginControlFlow("\nif(queryKey != null)")
                .addCode("storage.get(result -> ", Consumer.class)
                .beginControlFlow("")
                .beginControlFlow("if(result.succeeded)")
                .beginControlFlow("if(result.value != null)")
                .addStatement("$T.processResponse(result.value, context.response())", HttpHelper.class)
                .nextControlFlow("else")
                .addStatement("$T.processResponse(context.response(), $T.NOT_FOUND.code())", HttpHelper.class,
                        HttpResponseStatus.class)
                .endControlFlow()
                .nextControlFlow("else if(result.error != null)")
                .addStatement("String error = $S + context.request().uri() + $S + result.error.getMessage()", "Could not GET with query: ", " error: ")
                .addStatement("logger.error($S,  error)", "get - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.INTERNAL_SERVER_ERROR.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .nextControlFlow("else")
                .addStatement("String error = $S + context.request().uri() + $S + result.error.getMessage()", "Could not GET with query: ", " error: ")
                .addStatement("logger.error($S, error)", "get - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.BAD_REQUEST.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .endControlFlow()
                .endControlFlow(", queryKey)")
                .endControlFlow()
                .build();
    }

    private static void getGetAll(String entityName, TypeSpec.Builder restBuilder, TableMetadata table) {
        ClassName clazz = ClassName.get(MetaData.instance.getTableNamespace(), entityName);

        MethodSpec.Builder builder = MethodSpec.methodBuilder("getAll")
                .addJavadoc(getJavaDoc("GetAll - gets a list of"), clazz)
                .addParameter(RoutingContext.class, "context", Modifier.FINAL)
                .addModifiers(Modifier.PUBLIC);

        if(AccessorGenerator.isSingleValueKeyedTable(table)) {
            builder.addCode("// there's only 1 key so we do a get all\n")
                .addStatement("storage.getAll(result -> $T.processGetAllResult(context, result))",
                        ClassName.get(MetaData.instance.getRestNamespace(), "RestUtil"));
        } else {
            List<List<ParameterSpec>> permutations = AccessorGenerator.getParametersForAccessors(table);

            builder.addStatement("HttpServerRequest request = context.request()")
                .addStatement("int paramCount = request.params().size()")
                .beginControlFlow("\ntry")
                .addCode("//the query must start at the partition key\n")
                .beginControlFlow("switch(paramCount)");
            TypeMap typeToConverters = TypeMap.create();
            for (List<ParameterSpec> params : permutations) {
                builder.addCode("//partial key: " + getKeyCommentString(params) + "\n")
                    .addCode("case $L:\n", params.size());

                builder.addCode("\tstorage.getAll(");
                for(ParameterSpec param : params) {
                    String columnName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, param.name);

                    ColumnMetadata column = table.getColumn(columnName);

                    if(column.getType().equals(DataType.text())) {
                        builder.addCode("request.getParam($S), ", columnName);
                    } else {
                        String type = EntityGeneratorHelper.getRawType(column.getType()).simpleName();
                        builder.addCode(typeToConverters.getTypeConverter(type,
                                CodeBlock.builder().add("request.getParam($S)", columnName).build())).addCode(", ");
                    }
                }
                builder.addStatement("result -> $T.processGetAllResult(context, result))",
                        ClassName.get(MetaData.instance.getRestNamespace(), "RestUtil"));
                builder.addStatement("\tbreak");
            }

            builder.addCode("default:\n")
                .addStatement("\tString error = $S + context.request().uri()", "Invalid get all query: ")
                .addStatement("\tlogger.error($S,  error)", "get_all - {}")
                .addStatement("\t$T.processErrorResponse(error, context.response(), $T.BAD_REQUEST.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .addStatement("\tbreak")
                .endControlFlow().nextControlFlow("catch (Exception ex)")
                .addStatement("\tString error = $S + context.request().uri() + $S + ex.getMessage()", "error with query: ", " error: ")
                .addStatement("\tlogger.error($S,  error, ex)", "get_all - {}")
                .addStatement("\t$T.processErrorResponse(error, context.response(), $T.INTERNAL_SERVER_ERROR.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .endControlFlow();
        }

        restBuilder.addMethod(builder.build());
    }

    private static String getKeyCommentString(List<ParameterSpec> params) {
        List<String> columns = params.stream().map(param -> param.name).collect(Collectors.toList());

        return StringUtils.join(columns, ", ");
    }

    private static MethodSpec generateGetAllProcessingMethod() {
        return MethodSpec.methodBuilder("processGetAllResult")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .addTypeVariable(TypeVariableName.get("T"))
                .addJavadoc("Handles processing a get all result\n")
                .addParameter(RoutingContext.class, "context", Modifier.FINAL)
                .addParameter(ParameterizedTypeName.get(ClassName.get(ResultContext.class), ParameterizedTypeName.get(ClassName.get(List.class), TypeVariableName.get("T"))), "result", Modifier.FINAL)
                .beginControlFlow("if(result.succeeded)")
                .beginControlFlow("if(result.value != null)")
                .addStatement("$T.processResponse(result.value, context.response())", HttpHelper.class)
                .nextControlFlow("else")
                .addStatement("$T.processResponse(context.response(), $T.NOT_FOUND.code())", HttpHelper.class,
                        HttpResponseStatus.class)
                .endControlFlow()
                .nextControlFlow("else if(result.error != null)")
                .addStatement("String error = $S + context.request().uri() + $S + result.error.getMessage()", "Could not GET with query: ", " error: ")
                .addStatement("logger.error($S,  error)", "get_all - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.INTERNAL_SERVER_ERROR.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .nextControlFlow("else")
                .addStatement("String error = $S + context.request().uri() + $S + result.error.getMessage()", "Could not GET with query: ", " error: ")
                .addStatement("logger.error($S, error)", "get_all - {}")
                .addStatement("$T.processErrorResponse(error, context.response(), $T.BAD_REQUEST.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .endControlFlow()
                .build();
    }

    private static String getJavaDoc(String action) {
        return action + " a {@link $L} object.\n";
    }

    private static MethodSpec getSupportedApi() {
        return MethodSpec.methodBuilder("supportedApi")
                .addAnnotation(Override.class)
                .addStatement("$L", "return " + SUPPORTED_API_FIELD)
                .returns(TypeName.get(RestApi.RestApiDescriptor[].class))
                .addModifiers(Modifier.PUBLIC)
                .build();
    }

    private static MethodSpec getIsValidMethod() {
        return MethodSpec.methodBuilder("isValid").addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .returns(Boolean.class)
                .addJavadoc("Does the query string of this request contain the full primary key?\n")
                .addParameter(HttpServerRequest.class, "request", Modifier.FINAL)
                .addParameter(String[].class, PRIMARY_KEY_FIELD, Modifier.FINAL)
                .addStatement("$T error = null", String.class)
                .beginControlFlow("for(int i = 0; i < $L.length; i++)", PRIMARY_KEY_FIELD)
                .addStatement("$T key = primaryKey[i]", String.class)
                .addStatement("$T value = request.getParam(key)", String.class)
                .beginControlFlow("if($T.isEmpty(value))", StringUtils.class)
                .addStatement("error = $S + key", "You must supply parameter: ")
                .addStatement("$T.processErrorResponse(error, request.response(), $T.BAD_REQUEST.code())",
                        HttpHelper.class, HttpResponseStatus.class)
                .addStatement("break")
                .endControlFlow()
                .endControlFlow()
                .addStatement("return $T.isEmpty(error)", StringUtils.class)
                .build();
    }

    private static MethodSpec getQueryConverter(TableMetadata table) {

        List<ColumnMetadata> keys = table.getPrimaryKey();
        int numKeys = keys.size();
        TypeMap typeToConverters = TypeMap.create();

        MethodSpec.Builder builder = MethodSpec.methodBuilder("convertQueryString")
            .addJavadoc("Convert query params to their Cassandra type.\n")
            .addParameter(RoutingContext.class, "context", Modifier.FINAL)
            .addModifiers(Modifier.PUBLIC)
            .returns(Object[].class)
            .addStatement("$T request = context.request()", HttpServerRequest.class)
            .addCode("// if query params aren't valid a HttpResponseStatus.BAD_REQUEST will be sent with the missing field\n")
            .addStatement("$T values = new Object[$L]", Object[].class, keys.size());

        builder.beginControlFlow("try");
        for(int i = 0; i < numKeys; i++) {
            ColumnMetadata column = keys.get(i);
            if(column.getType().equals(DataType.text())) {
                builder.addStatement("values[$L] = request.getParam($S)", i, column.getName());
            } else if (Udt.instance.isUdt(column.getType())) {
                throw new IllegalArgumentException("We don't currently support UDT primary keys in the query string, field: "
                        + column.getName());
            } else {
                String type = EntityGeneratorHelper.getRawType(column.getType()).simpleName();
                builder.addCode("values[$L] = ", i)
                       .addCode(typeToConverters.getTypeConverter(type,
                                CodeBlock.builder().add("request.getParam($S)", column.getName()).build()))
                       .addStatement("");
            }
        }

        return builder.nextControlFlow("catch (Exception ex)")
               .addStatement("$T.processErrorResponse(ex.getMessage(), context.response(), $T.BAD_REQUEST.code())",
                       HttpHelper.class, HttpResponseStatus.class)
               .addStatement("return null")
               .endControlFlow()
               .addStatement("return values").build();
    }
}


text:
@class FLAuxiliaryViewController;

@protocol FLAuxiliaryViewControllerBehavior <NSObject>
- (UIViewController*) parentControllerForAuxiliaryViewController:(FLAuxiliaryViewController*) viewController;
- (void) addContainerViewToParentViewController:(FLAuxiliaryViewController*) viewController;
- (void) showViewControllerAnimated:(BOOL) animated viewController:(FLAuxiliaryViewController*) viewController;
- (void) hideViewController:(BOOL) animated viewController:(FLAuxiliaryViewController*) viewController;
- (void) didFinishDraggingWithResults:(FLViewDraggerResults) results viewController:(FLAuxiliaryViewController*) viewController;
- (CGRect) initialFrameForContainerView:(FLAuxiliaryViewController*) viewController;
- (BOOL) handleInternalTouches:(NSSet*) touches event:(UIEvent*) event viewController:(FLAuxiliaryViewController*) viewController;
- (void) didAddTouchableView:(FLAuxiliaryViewController*) viewController;
@end

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: hal-hal yang mengusik hati saat migrasi FOSS
date: 2010-12-10 21:56:17.000000000 +07:00
type: post
published: true
status: publish
categories:
- linux-opensource
tags: []
meta:
  _edit_last: '7761285'
  geo_latitude: '-8.588990'
  geo_longitude: '116.130400'
  geo_accuracy: '206'
  geo_address: mataram
  geo_public: '1'
author:
  login: pdft
  email: padfoot.tgz@gmail.com
  display_name: piko
  first_name: herpiko
  last_name: dwi aguno
---

1. memigrasikan pemikiran pengguna. orang yang tidak tertarik dan tidak punya gambaran tentang legalitas software. jenis ini yang paling banyak saya temui. ketika saya tawarkan, "gnu/linux itu begini, begitu".  dan yang bersangkutan mengangguk-ngagguk, "oh, yeah. let install it!". jadi saya menghabiskan barang sejamlah buat install dualboot dan akhirnya berkatalah ia, "duh, ndak ngerti, ko". jika saya berusaha menekankan mengapa ini penting, ndak bakalan nyambung karena sudah pasang muka 'i don't care', bajakan atau tidak , apa bedanya?

kesalahannya dimana? mungkin seharusnya saya tekankan ngomongin masalah FOSS sebelum koar-koar kelebihan. jadi pengguna sudah punya landasan bertahan kalau ketemu masalah.

2. aplikasi-aplikasi tertentu. sedia payung sebelum hujan, saya selalu punya iso repositori. tapi...

a : saya butuh transtool

b : (mikir)

a : saya butuh coreldraw

b : oh, ada inkscape!

a : pasangmukanorespeklihatinkscape

b : oh. :-|

yah, tidak selamanya wine berjalan sempurna. apalagi kalau orangnya prekengan. sampai-sampai di sela-sela sebuah pelatihan migrasi FOSS, saking putus asanya, saya berbisik, "sudahlah pak, pakai windos saja".

3. tentang repositori. mengingat internet di indonesia belum .... (belum apa yah? pokoknya masih kurang), repositori adalah hal yang agak sulit, baik koneksi langsung maupun mengunduh iso repo.

a : mas, kalau saya mau install potosop gimana?

b : o, ada alternatifnya di linux pak, namanya gimp.

a : gini. gini. gini. bapak harus konek sama repo. pakai internet.

b : (ngeluarin modem usb level edge)

a : (doh! membayangkan betapa lambatnya nanti apt-get. menawarkan install via iso repo yang sudah ada)

jika saya tawarkan menyalin iso repositori, ruang spasi hardis yang cukup adalah wajib. tapi tidaklah efektif menyimpan sedemikian besar file iso yang mana mungkin hanya 10 persen yang dibutuhkan (mengingat dependensi kesana kemari antar iso, semua harus utuh). kalau untuk kesenangan berlinux-ria, file iso bejubel tidak masalah, tapi untuk low-end user, perlu dipikir2. hmm. :(

kenapa masalah hardware tidak menjadi yang ke 4.? karena sejauh ini, saya lancar2 saja memigrasikan hardware. :)

kesimpulan : kalau boleh jujur, sebenarnya GNU/Linux itu tidak sesempurna yang orang-orang katakan. terus kenapa saya ngotot? karena ada alasan yang lebih kuat di balik itu.

btw kemarin, sempat baca surel dari milis linux-aktivis tentang aktivis linux itu sendiri. jika menilik ke sana, saya merasa saya bukan aktivis linux. saya tidak punya titel, sertifikasi, pengetahuan yang cukup, skill public-speaking buat ngomong2 di seminar atau pelatihan. wah, gimana dong? saya apa dong? apakah kegiatan aktivis linux itu harus dalam bentuk seminar2 dan pelatihan dan pengembangan perangkat lunak?  wah.


text:
cask 'font-cabin' do
  # version '1.006'
  version :latest
  sha256 :no_check

  url 'https://github.com/google/fonts/trunk/ofl/cabin',
      using:      :svn,
      revision:   '50',
      trust_cert: true
  homepage 'http://www.google.com/fonts/specimen/Cabin'
  license :ofl

  font 'Cabin-Bold.ttf'
  font 'Cabin-BoldItalic.ttf'
  font 'Cabin-Italic.ttf'
  font 'Cabin-Medium.ttf'
  font 'Cabin-MediumItalic.ttf'
  font 'Cabin-Regular.ttf'
  font 'Cabin-SemiBold.ttf'
  font 'Cabin-SemiBoldItalic.ttf'
end


text:
package migrations

import (
	"context"
	"net/http"
	"os"
	"testing"
	"time"

	"code.gitea.io/gitea/modules/migrations/base"

	"github.com/stretchr/testify/assert"
)

func TestGogsDownloadRepo(t *testing.T) {
	// Skip tests if Gogs token is not found
	gogsPersonalAccessToken := os.Getenv("GOGS_READ_TOKEN")
	if len(gogsPersonalAccessToken) == 0 {
		t.Skip("skipped test because GOGS_READ_TOKEN was not in the environment")
	}

	resp, err := http.Get("https://try.gogs.io/lunnytest/TESTREPO")
	if err != nil || resp.StatusCode/100 != 2 {
		// skip and don't run test
		t.Skipf("visit test repo failed, ignored")
		return
	}

	downloader := NewGogsDownloader(context.Background(), "https://try.gogs.io", "", "", gogsPersonalAccessToken, "lunnytest", "TESTREPO")
	repo, err := downloader.GetRepoInfo()
	assert.NoError(t, err)

	assert.EqualValues(t, &base.Repository{
		Name:        "TESTREPO",
		Owner:       "lunnytest",
		Description: "",
		CloneURL:    "https://try.gogs.io/lunnytest/TESTREPO.git",
	}, repo)

	milestones, err := downloader.GetMilestones()
	assert.NoError(t, err)
	assert.True(t, len(milestones) == 1)

	for _, milestone := range milestones {
		switch milestone.Title {
		case "1.0":
			assert.EqualValues(t, "open", milestone.State)
		}
	}

	labels, err := downloader.GetLabels()
	assert.NoError(t, err)
	assert.Len(t, labels, 7)
	for _, l := range labels {
		switch l.Name {
		case "bug":
			assertLabelEqual(t, "bug", "ee0701", "", l)
		case "duplicated":
			assertLabelEqual(t, "duplicated", "cccccc", "", l)
		case "enhancement":
			assertLabelEqual(t, "enhancement", "84b6eb", "", l)
		case "help wanted":
			assertLabelEqual(t, "help wanted", "128a0c", "", l)
		case "invalid":
			assertLabelEqual(t, "invalid", "e6e6e6", "", l)
		case "question":
			assertLabelEqual(t, "question", "cc317c", "", l)
		case "wontfix":
			assertLabelEqual(t, "wontfix", "ffffff", "", l)
		}
	}

	_, err = downloader.GetReleases()
	assert.Error(t, err)

	// downloader.GetIssues()
	issues, isEnd, err := downloader.GetIssues(1, 8)
	assert.NoError(t, err)
	assert.EqualValues(t, 1, len(issues))
	assert.False(t, isEnd)

	assert.EqualValues(t, []*base.Issue{
		{
			Number:      1,
			Title:       "test",
			Content:     "test",
			Milestone:   "",
			PosterName:  "lunny",
			PosterEmail: "xiaolunwen@gmail.com",
			State:       "open",
			Created:     time.Date(2019, 06, 11, 8, 16, 44, 0, time.UTC),
			Labels: []*base.Label{
				{
					Name:  "bug",
					Color: "ee0701",
				},
			},
		},
	}, issues)

	// downloader.GetComments()
	comments, err := downloader.GetComments(1)
	assert.NoError(t, err)
	assert.EqualValues(t, 1, len(comments))
	assert.EqualValues(t, []*base.Comment{
		{
			PosterName:  "lunny",
			PosterEmail: "xiaolunwen@gmail.com",
			Created:     time.Date(2019, 06, 11, 8, 19, 50, 0, time.UTC),
			Updated:     time.Date(2019, 06, 11, 8, 19, 50, 0, time.UTC),
			Content:     `1111`,
		},
	}, comments)

	// downloader.GetPullRequests()
	_, _, err = downloader.GetPullRequests(1, 3)
	assert.Error(t, err)
}


text:
importScripts("../../js/tests/canvas-tests-utils.js");
self.onmessage = function(e) {
    if (!setupTest())
        self.postMessage("Test failed");

    canvas.addEventListener("webglcontextlost", function(e) {
        if (!testLostContext(e))
            self.postMessage("Test failed");
        // restore the context after this event has exited.
        setTimeout(function() {
            // we didn't call prevent default so we should not be able to restore the context
            if (!compareGLError(gl.INVALID_OPERATION, "WEBGL_lose_context.restoreContext()"))
                self.postMessage("Test failed");
            testLosingAndRestoringContext().then(function() {
                self.postMessage("Test passed");
            }, function() {
                self.postMessage("Test failed");
            });
        }, 0);
    });
    canvas.addEventListener("webglcontextrestored", function() {
        self.postMessage("Test failed");
    });
    allowRestore = false;
    contextLostEventFired = false;
    contextRestoredEventFired = false;

    if (!testOriginalContext())
        self.postMessage("Test failed");
    WEBGL_lose_context.loseContext();
    // The context should be lost immediately.
    if (!gl.isContextLost())
        self.postMessage("Test failed");
    if (gl.getError() != gl.CONTEXT_LOST_WEBGL)
        self.postMessage("Test failed");
    if (gl.getError() != gl.NO_ERROR)
        self.postMessage("Test failed");
    // gl methods should be no-ops
    if (!compareGLError(gl.NO_ERROR, "gl.blendFunc(gl.TEXTURE_2D, gl.TEXTURE_CUBE_MAP)"))
        self.postMessage("Test failed");
    // but the event should not have been fired.
    if (contextLostEventFired)
        self.postMessage("Test failed");
}


text:
/*!
 * Start Bootstrap - Shop Homepage HTML Template (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

body {
    padding-top: 70px; /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
}

.slide-image {
    width: 100%;
}

.carousel-holder {
    margin-bottom: 30px;
}

.carousel-control,
.item {
    border-radius: 4px;
}

.caption {
    height: 130px;
    overflow: hidden;
}

.caption h4 {
    white-space: nowrap;
}

.thumbnail img {
    width: 100%;
}

.ratings {
    padding-right: 10px;
    padding-left: 10px;
    color: #d17581;
}

.thumbnail {
    padding: 0;
}

.thumbnail img {
	width: 320px;
	height: 150px;
}

.thumbnail .caption-full {
    padding: 9px;
    color: #333;
}

footer {
    margin: 50px 0;
}


text:
cd ..
cd ..
cd bin
./classification ../models/vgg_face/deploy.prototxt ../weights/vgg_face/CK/vgg_face_train_iter_10000.caffemodel "../datasets/face/CK/4 - LMDB/train/mean.binaryproto" ../datasets/face/CK/emotion_labels.txt "../datasets/face/CK/3 - CROPPED_RESIZED/validate/anger/2.jpg"


text:
var mongoose = require('mongoose');
var PersonSchema = mongoose.Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  }
},
	{collection: 'people' }
);

module.exports = mongoose.model('',PersonSchema);


text:
/**
* Add Two Numbers.
* https://oj.leetcode.com/problems/add-two-numbers/
* You are given two linked lists representing two non-negative numbers. The dig-
* its are stored in reverse order and each of their nodes contain a single digit
* . Add the two numbers and return it as a linked list.
*/

#ifndef SOLUTIONS_ADD_TWO_NUMBERS_H_
#define SOLUTIONS_ADD_TWO_NUMBERS_H_

#include <vector>

#include "../util/util_common.h"

class AddTwoNumbers {
public:
  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
};

#endif  // SOLUTIONS_ADD_TWO_NUMBERS_H_


text:
package io.opentelemetry.sdk.extension.trace.jaeger.sampler;

import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import io.opentelemetry.exporter.internal.retry.RetryPolicy;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;

class DefaultGrpcServiceBuilderTest {

  private static DefaultGrpcServiceBuilder<
          SamplingStrategyParametersMarshaler, SamplingStrategyResponseUnMarshaler>
      exporterBuilder() {
    return new DefaultGrpcServiceBuilder<>(
        "some", null, 10, URI.create("htt://localhost:8080"), "some");
  }

  @Test
  @SuppressWarnings("PreferJavaTimeOverload")
  void validConfig() {
    assertThatCode(() -> exporterBuilder().setTimeout(0, TimeUnit.MILLISECONDS))
        .doesNotThrowAnyException();
    assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(0)))
        .doesNotThrowAnyException();
    assertThatCode(() -> exporterBuilder().setTimeout(10, TimeUnit.MILLISECONDS))
        .doesNotThrowAnyException();
    assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(10)))
        .doesNotThrowAnyException();

    assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost:4317"))
        .doesNotThrowAnyException();
    assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost"))
        .doesNotThrowAnyException();
    assertThatCode(() -> exporterBuilder().setEndpoint("https://localhost"))
        .doesNotThrowAnyException();
    assertThatCode(() -> exporterBuilder().setEndpoint("http://foo:bar@localhost"))
        .doesNotThrowAnyException();

    assertThatCode(() -> exporterBuilder().setCompression("gzip")).doesNotThrowAnyException();
    assertThatCode(() -> exporterBuilder().setCompression("none")).doesNotThrowAnyException();

    assertThatCode(() -> exporterBuilder().addHeader("foo", "bar").addHeader("baz", "qux"))
        .doesNotThrowAnyException();

    assertThatCode(
            () ->
                exporterBuilder().setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8)))
        .doesNotThrowAnyException();

    assertThatCode(() -> exporterBuilder().addRetryPolicy(RetryPolicy.getDefault()))
        .doesNotThrowAnyException();
  }

  @Test
  @SuppressWarnings({"PreferJavaTimeOverload", "NullAway"})
  public void invalidConfig() {
    assertThatThrownBy(() -> exporterBuilder().setTimeout(-1, TimeUnit.MILLISECONDS))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("timeout must be non-negative");
    assertThatThrownBy(() -> exporterBuilder().setTimeout(1, null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("unit");
    assertThatThrownBy(() -> exporterBuilder().setTimeout(null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("timeout");

    assertThatThrownBy(() -> exporterBuilder().addRetryPolicy(null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("retryPolicy");

    assertThatThrownBy(() -> exporterBuilder().addHeader(null, "val"))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("key");
    assertThatThrownBy(() -> exporterBuilder().addHeader("key", null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("value");

    assertThatThrownBy(() -> exporterBuilder().setTrustedCertificates(null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("trustedCertificatesPem");

    assertThatThrownBy(() -> exporterBuilder().setEndpoint(null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("endpoint");
    assertThatThrownBy(() -> exporterBuilder().setEndpoint("😺://localhost"))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("Invalid endpoint, must be a URL: 😺://localhost");
    assertThatThrownBy(() -> exporterBuilder().setEndpoint("localhost"))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("Invalid endpoint, must start with http:// or https://: localhost");
    assertThatThrownBy(() -> exporterBuilder().setEndpoint("gopher://localhost"))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost");

    assertThatThrownBy(() -> exporterBuilder().setCompression(null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("compressionMethod");
    assertThatThrownBy(() -> exporterBuilder().setCompression("foo"))
        .isInstanceOf(IllegalArgumentException.class)
        .hasMessage(
            "Unsupported compression method. Supported compression methods include: gzip, none.");

    assertThatThrownBy(() -> exporterBuilder().setChannel(null))
        .isInstanceOf(NullPointerException.class)
        .hasMessage("channel");
  }
}


text:
<!DOCTYPE html>

	<title>Colors by function</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/fonts/font_roboto/roboto.css"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>


text:
package com.microsoft.bingads.v12.campaignmanagement;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for CampaignCriterion complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="CampaignCriterion">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="CampaignId" type="{http://www.w3.org/2001/XMLSchema}long"/>
 *         <element name="Criterion" type="{https://bingads.microsoft.com/CampaignManagement/v12}Criterion" minOccurs="0"/>
 *         <element name="ForwardCompatibilityMap" type="{http://schemas.datacontract.org/2004/07/System.Collections.Generic}ArrayOfKeyValuePairOfstringstring" minOccurs="0"/>
 *         <element name="Id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
 *         <element name="Status" type="{https://bingads.microsoft.com/CampaignManagement/v12}CampaignCriterionStatus" minOccurs="0"/>
 *         <element name="Type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CampaignCriterion", propOrder = {
    "campaignId",
    "criterion",
    "forwardCompatibilityMap",
    "id",
    "status",
    "type"
})
@XmlSeeAlso({
    BiddableCampaignCriterion.class,
    NegativeCampaignCriterion.class
})
public class CampaignCriterion {

    @XmlElement(name = "CampaignId")
    protected long campaignId;
    @XmlElement(name = "Criterion", nillable = true)
    protected Criterion criterion;
    @XmlElement(name = "ForwardCompatibilityMap", nillable = true)
    protected ArrayOfKeyValuePairOfstringstring forwardCompatibilityMap;
    @XmlElement(name = "Id", nillable = true)
    protected Long id;
    @XmlElement(name = "Status", nillable = true)
    @XmlSchemaType(name = "string")
    protected CampaignCriterionStatus status;
    @XmlElement(name = "Type", nillable = true)
    protected String type;

    /**
     * Gets the value of the campaignId property.
     *
     */
    public long getCampaignId() {
        return campaignId;
    }

    /**
     * Sets the value of the campaignId property.
     *
     */
    public void setCampaignId(long value) {
        this.campaignId = value;
    }

    /**
     * Gets the value of the criterion property.
     *
     * @return
     *     possible object is
     *     {@link Criterion }
     *
     */
    public Criterion getCriterion() {
        return criterion;
    }

    /**
     * Sets the value of the criterion property.
     *
     * @param value
     *     allowed object is
     *     {@link Criterion }
     *
     */
    public void setCriterion(Criterion value) {
        this.criterion = value;
    }

    /**
     * Gets the value of the forwardCompatibilityMap property.
     *
     * @return
     *     possible object is
     *     {@link ArrayOfKeyValuePairOfstringstring }
     *
     */
    public ArrayOfKeyValuePairOfstringstring getForwardCompatibilityMap() {
        return forwardCompatibilityMap;
    }

    /**
     * Sets the value of the forwardCompatibilityMap property.
     *
     * @param value
     *     allowed object is
     *     {@link ArrayOfKeyValuePairOfstringstring }
     *
     */
    public void setForwardCompatibilityMap(ArrayOfKeyValuePairOfstringstring value) {
        this.forwardCompatibilityMap = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link Long }
     *
     */
    public Long getId() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link Long }
     *
     */
    public void setId(Long value) {
        this.id = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link CampaignCriterionStatus }
     *
     */
    public CampaignCriterionStatus getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link CampaignCriterionStatus }
     *
     */
    public void setStatus(CampaignCriterionStatus value) {
        this.status = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListInstance FeatureId="{f9ce21f8-f437-4f7e-8bc6-946378c850f0}"
              TemplateType="171"
              Title="WorkflowTaskList"
              Description="This list instance is used for workflow Task items."
              Url="Lists/WorkflowTaskList"
              RootWebOnly="FALSE" />

  <ContentTypeBinding ListUrl="Lists/WorkflowTaskList"
                      RootWebOnly="FALSE"
                      ContentTypeId="0x0108003365C4474CAE8C42BCE396314E88E51F"/>

  <!-- This element binds the content type "CustomApprovalTask" to the task list of the workflow -->
  <ContentTypeBinding ListUrl="Lists/WorkflowTaskList"
                      RootWebOnly="FALSE"
                      ContentTypeId="0x0108003365C4474CAE8C42BCE396314E88E51F00032992A620484EF69483D9D2295556C2"/>

</Elements>


text:
#ifndef COPY_H
#define COPY_H

#include "nodes/execnodes.h"
#include "nodes/parsenodes.h"
#include "tcop/dest.h"

/* CopyStateData is private in commands/copy.c */
typedef struct CopyStateData *CopyState;

extern uint64 DoCopy(const CopyStmt *stmt, const char *queryString);

extern void ProcessCopyOptions(CopyState cstate, bool is_from, List *options);
extern CopyState BeginCopyFrom(Relation rel, const char *filename,
			  List *attnamelist, List *options);
extern void EndCopyFrom(CopyState cstate);
extern bool NextCopyFrom(CopyState cstate, ExprContext *econtext,
			 Datum *values, bool *nulls, Oid *tupleOid);
extern bool NextCopyFromRawFields(CopyState cstate,
					  char ***fields, int *nfields);
extern void CopyFromErrorCallback(void *arg);

extern DestReceiver *CreateCopyDestReceiver(void);

#endif   /* COPY_H */


text:
package org.apache.flink.table.data.columnar.vector;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.data.ArrayData;

/** Array column vector. */
@Internal
public interface ArrayColumnVector extends ColumnVector {
    ArrayData getArray(int i);
}


text:
/*
 * Now that we have the LEDs blinking, we try to vary the frequency of blinking
 * This code varies the frequency of blinking of the LED connected to P1.0 using FOR loops
 *
 * The variable i is the delay loop variable. i runs from j to 0.
 * Hence the value of j decides how long the delay will be.
 * We vary j from 0 to 10000 and back to 0 in steps of 250 to achieve the desired effect
 */

#include <msp430.h>

int main(void) {
    volatile int i,j; //Force the compiler to not optimize the variables i and j
    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    P1DIR|=BIT0; //Set P1.0 as output

    while(1)
    {

        for(j=0;j<10000;j+=250) //j goes from 0 to 10000 in steps of 250
            {
            P1OUT^=BIT0; //Toggle the LED
            for(i=j;i>0;i--); //Wait for j number of cycles

        }
        for(j=10000;j>0;j-=250) //j goes from 10000 to 0 in steps of 250
        {
            P1OUT^=BIT0; //Toggle the LED
            for(i=j;i>0;i--); //Wait for j number of cycles

        }
    }

    return 0;
}


text:
package Client;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name = "CalculeAproxPiService", targetNamespace = "http://Services/", wsdlLocation = "http://localhost:8088/caculpi?wsdl")
public class CalculeAproxPiService
    extends Service
{

    private final static URL CALCULEAPROXPISERVICE_WSDL_LOCATION;
    private final static WebServiceException CALCULEAPROXPISERVICE_EXCEPTION;
    private final static QName CALCULEAPROXPISERVICE_QNAME = new QName("http://Services/", "CalculeAproxPiService");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("http://localhost:8088/caculpi?wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        CALCULEAPROXPISERVICE_WSDL_LOCATION = url;
        CALCULEAPROXPISERVICE_EXCEPTION = e;
    }

    public CalculeAproxPiService() {
        super(__getWsdlLocation(), CALCULEAPROXPISERVICE_QNAME);
    }

    public CalculeAproxPiService(WebServiceFeature... features) {
        super(__getWsdlLocation(), CALCULEAPROXPISERVICE_QNAME, features);
    }

    public CalculeAproxPiService(URL wsdlLocation) {
        super(wsdlLocation, CALCULEAPROXPISERVICE_QNAME);
    }

    public CalculeAproxPiService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, CALCULEAPROXPISERVICE_QNAME, features);
    }

    public CalculeAproxPiService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public CalculeAproxPiService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     *
     * @return
     *     returns CalculeAproxPi
     */
    @WebEndpoint(name = "CalculeAproxPiPort")
    public CalculeAproxPi getCalculeAproxPiPort() {
        return super.getPort(new QName("http://Services/", "CalculeAproxPiPort"), CalculeAproxPi.class);
    }

    /**
     *
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the features parameter will have their default values.
     * @return
     *     returns CalculeAproxPi
     */
    @WebEndpoint(name = "CalculeAproxPiPort")
    public CalculeAproxPi getCalculeAproxPiPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://Services/", "CalculeAproxPiPort"), CalculeAproxPi.class, features);
    }

    private static URL __getWsdlLocation() {
        if (CALCULEAPROXPISERVICE_EXCEPTION!= null) {
            throw CALCULEAPROXPISERVICE_EXCEPTION;
        }
        return CALCULEAPROXPISERVICE_WSDL_LOCATION;
    }

}


text:
<?php

namespace Tests\AppBundle\Controller\Index;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class IndexTest extends WebTestCase
{

    public function testIndex()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains('Welcome to Symfony', $crawler->filter('#container h1')->text());

    }

}


text:
/*******************************************************************************
* @file     main.c
* @author   imoware
* @version  V3.1.0
* @date     04/11/12
********************************************************************************
* @version history    Description
* ----------------    -----------
* v2.5.0              LSI Clock Enable for RTC (deprecated with 2.7 release)
* v2.6.0              LSI Clock Calibration (deprecated with 2.7 release)
* v2.7.0              LSE Clock Enable for RTC
* v2.8.0              (1) Tag Version, (2) Last Packet Reserved
* v3.0.0              Tamper Switch Debounce Handler
* v3.1.0              Tamper Switch Debounce Handler WITHOUT Timer2
*******************************************************************************/
#include "blocker_services.h"
#include "i2c_ee.h"

#include "stm8l15x.h"
#include "stm8l15x_clk.h"
#include "stm8l15x_gpio.h"
#include "stm8l15x_i2c.h"
#include "stm8l15x_itc.h"
#include "stm8l15x_rtc.h"
#include "stdio.h"
#include "stdlib.h"

extern __IO bool rtcConfigured;
extern __IO bool lowVoltBatteryDetected;
extern __IO bool testTamperSwitch;

void main(void)
{
    rtcConfigured = FALSE;
    testTamperSwitch = FALSE;
    lowVoltBatteryDetected = FALSE;

    // initialize Tag i/o's
    initializeTagPins();

    // run Tag Diagnostics
    tagDiagnostics();

    // initialize Tag EEPROM
    initializeTagEE();

    // tag is ready for host operations...
    while (TRUE)
    {
        halt();
        delay((uint16_t)8000);
    }
}
/*************************** END OF FILE **************************************/


text:
/*
 * Created on 21/11/2006
 */
package japa.parser.ast.expr;

import japa.parser.ast.visitor.GenericVisitor;
import japa.parser.ast.visitor.VoidVisitor;

import java.util.List;

/**
 * @author Julio Vilmar Gesser
 */
public final class NormalAnnotationExpr extends AnnotationExpr {

    private List<MemberValuePair> pairs;

    public NormalAnnotationExpr() {
    }

    public NormalAnnotationExpr(NameExpr name, List<MemberValuePair> pairs) {
        this.name = name;
        this.pairs = pairs;
    }

    public NormalAnnotationExpr(int beginLine, int beginColumn, int endLine, int endColumn, NameExpr name, List<MemberValuePair> pairs) {
        super(beginLine, beginColumn, endLine, endColumn);
        this.name = name;
        this.pairs = pairs;
    }

    @Override
    public <R, A> R accept(GenericVisitor<R, A> v, A arg) {
        return v.visit(this, arg);
    }

    @Override
    public <A> void accept(VoidVisitor<A> v, A arg) {
        v.visit(this, arg);
    }

    public List<MemberValuePair> getPairs() {
        return pairs;
    }

    public void setPairs(List<MemberValuePair> pairs) {
        this.pairs = pairs;
    }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>Basic Form</title>

	<link rel="stylesheet" href="assets/demo.css">
	<link rel="stylesheet" href="assets/form-basic.css">

JNJ Prints | Add Order

        View Orders
        Home

        <form class="form-basic" method="post" action="#">

Add Order :: Product Selection

                    Products:
                    <select name="dropdown" onchange = "redirect(this.value)">

                        <option value = "">Products</option>
                        <option value = "order_bagtag.php">Bag Tag</option>
                        <option value = "order_keychain.php">Key Chain</option>
                        <option value = "order_tarpaulin.php">Tarpaulin</option>
                        <option value = "order_shirt.php">Shirts</option>
                        <option value = "order_tumbler.php">Tumbler</option>
                    </select>

        </form>


text:
/******************************************************************************
 *
 * Module Name: uteval - Object evaluation
 *
 *****************************************************************************/

/*
 * Copyright (C) 2000 - 2013, Intel Corp.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */

#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"

#define _COMPONENT          ACPI_UTILITIES
ACPI_MODULE_NAME("uteval")

/*******************************************************************************
 *
 * FUNCTION:    acpi_ut_evaluate_object
 *
 * PARAMETERS:  prefix_node         - Starting node
 *              path                - Path to object from starting node
 *              expected_return_types - Bitmap of allowed return types
 *              return_desc         - Where a return value is stored
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Evaluates a namespace object and verifies the type of the
 *              return object. Common code that simplifies accessing objects
 *              that have required return objects of fixed types.
 *
 *              NOTE: Internal function, no parameter validation
 *
 ******************************************************************************/

acpi_status
acpi_ut_evaluate_object(struct acpi_namespace_node * prefix_node,
			char *path,
			u32 expected_return_btypes,
			union acpi_operand_object **return_desc)
{
	struct acpi_evaluate_info *info;
	acpi_status status;
	u32 return_btype;

	ACPI_FUNCTION_TRACE(ut_evaluate_object);

	/* Allocate the evaluation information block */

	info = ACPI_ALLOCATE_ZEROED(sizeof(struct acpi_evaluate_info));
	if (!info) {
		return_ACPI_STATUS(AE_NO_MEMORY);
	}

	info->prefix_node = prefix_node;
	info->pathname = path;

	/* Evaluate the object/method */

	status = acpi_ns_evaluate(info);
	if (ACPI_FAILURE(status)) {
		if (status == AE_NOT_FOUND) {
			ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
					  "[%4.4s.%s] was not found\n",
					  acpi_ut_get_node_name(prefix_node),
					  path));
		} else {
			ACPI_ERROR_METHOD("Method execution failed",
					  prefix_node, path, status);
		}

		goto cleanup;
	}

	/* Did we get a return object? */

	if (!info->return_object) {
		if (expected_return_btypes) {
			ACPI_ERROR_METHOD("No object was returned from",
					  prefix_node, path, AE_NOT_EXIST);

			status = AE_NOT_EXIST;
		}

		goto cleanup;
	}

	/* Map the return object type to the bitmapped type */

	switch ((info->return_object)->common.type) {
	case ACPI_TYPE_INTEGER:
		return_btype = ACPI_BTYPE_INTEGER;
		break;

	case ACPI_TYPE_BUFFER:
		return_btype = ACPI_BTYPE_BUFFER;
		break;

	case ACPI_TYPE_STRING:
		return_btype = ACPI_BTYPE_STRING;
		break;

	case ACPI_TYPE_PACKAGE:
		return_btype = ACPI_BTYPE_PACKAGE;
		break;

	default:
		return_btype = 0;
		break;
	}

	if ((acpi_gbl_enable_interpreter_slack) && (!expected_return_btypes)) {
		/*
		 * We received a return object, but one was not expected. This can
		 * happen frequently if the "implicit return" feature is enabled.
		 * Just delete the return object and return AE_OK.
		 */
		acpi_ut_remove_reference(info->return_object);
		goto cleanup;
	}

	/* Is the return object one of the expected types? */

	if (!(expected_return_btypes & return_btype)) {
		ACPI_ERROR_METHOD("Return object type is incorrect",
				  prefix_node, path, AE_TYPE);

		ACPI_ERROR((AE_INFO,
			    "Type returned from %s was incorrect: %s, expected Btypes: 0x%X",
			    path,
			    acpi_ut_get_object_type_name(info->return_object),
			    expected_return_btypes));

		/* On error exit, we must delete the return object */

		acpi_ut_remove_reference(info->return_object);
		status = AE_TYPE;
		goto cleanup;
	}

	/* Object type is OK, return it */

	*return_desc = info->return_object;

      cleanup:
	ACPI_FREE(info);
	return_ACPI_STATUS(status);
}

/*******************************************************************************
 *
 * FUNCTION:    acpi_ut_evaluate_numeric_object
 *
 * PARAMETERS:  object_name         - Object name to be evaluated
 *              device_node         - Node for the device
 *              value               - Where the value is returned
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Evaluates a numeric namespace object for a selected device
 *              and stores result in *Value.
 *
 *              NOTE: Internal function, no parameter validation
 *
 ******************************************************************************/

acpi_status
acpi_ut_evaluate_numeric_object(char *object_name,
				struct acpi_namespace_node *device_node,
				u64 *value)
{
	union acpi_operand_object *obj_desc;
	acpi_status status;

	ACPI_FUNCTION_TRACE(ut_evaluate_numeric_object);

	status = acpi_ut_evaluate_object(device_node, object_name,
					 ACPI_BTYPE_INTEGER, &obj_desc);
	if (ACPI_FAILURE(status)) {
		return_ACPI_STATUS(status);
	}

	/* Get the returned Integer */

	*value = obj_desc->integer.value;

	/* On exit, we must delete the return object */

	acpi_ut_remove_reference(obj_desc);
	return_ACPI_STATUS(status);
}

/*******************************************************************************
 *
 * FUNCTION:    acpi_ut_execute_STA
 *
 * PARAMETERS:  device_node         - Node for the device
 *              flags               - Where the status flags are returned
 *
 * RETURN:      Status
 *
 * DESCRIPTION: Executes _STA for selected device and stores results in
 *              *Flags.
 *
 *              NOTE: Internal function, no parameter validation
 *
 ******************************************************************************/

acpi_status
acpi_ut_execute_STA(struct acpi_namespace_node *device_node, u32 * flags)
{
	union acpi_operand_object *obj_desc;
	acpi_status status;

	ACPI_FUNCTION_TRACE(ut_execute_STA);

	status = acpi_ut_evaluate_object(device_node, METHOD_NAME__STA,
					 ACPI_BTYPE_INTEGER, &obj_desc);
	if (ACPI_FAILURE(status)) {
		if (AE_NOT_FOUND == status) {
			ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
					  "_STA on %4.4s was not found, assuming device is present\n",
					  acpi_ut_get_node_name(device_node)));

			*flags = ACPI_UINT32_MAX;
			status = AE_OK;
		}

		return_ACPI_STATUS(status);
	}

	/* Extract the status flags */

	*flags = (u32) obj_desc->integer.value;

	/* On exit, we must delete the return object */

	acpi_ut_remove_reference(obj_desc);
	return_ACPI_STATUS(status);
}

/*******************************************************************************
 *
 * FUNCTION:    acpi_ut_execute_power_methods
 *
 * PARAMETERS:  device_node         - Node for the device
 *              method_names        - Array of power method names
 *              method_count        - Number of methods to execute
 *              out_values          - Where the power method values are returned
 *
 * RETURN:      Status, out_values
 *
 * DESCRIPTION: Executes the specified power methods for the device and returns
 *              the result(s).
 *
 *              NOTE: Internal function, no parameter validation
 *
******************************************************************************/

acpi_status
acpi_ut_execute_power_methods(struct acpi_namespace_node *device_node,
			      const char **method_names,
			      u8 method_count, u8 *out_values)
{
	union acpi_operand_object *obj_desc;
	acpi_status status;
	acpi_status final_status = AE_NOT_FOUND;
	u32 i;

	ACPI_FUNCTION_TRACE(ut_execute_power_methods);

	for (i = 0; i < method_count; i++) {
		/*
		 * Execute the power method (_sx_d or _sx_w). The only allowable
		 * return type is an Integer.
		 */
		status = acpi_ut_evaluate_object(device_node,
						 ACPI_CAST_PTR(char,
							       method_names[i]),
						 ACPI_BTYPE_INTEGER, &obj_desc);
		if (ACPI_SUCCESS(status)) {
			out_values[i] = (u8)obj_desc->integer.value;

			/* Delete the return object */

			acpi_ut_remove_reference(obj_desc);
			final_status = AE_OK;	/* At least one value is valid */
			continue;
		}

		out_values[i] = ACPI_UINT8_MAX;
		if (status == AE_NOT_FOUND) {
			continue;	/* Ignore if not found */
		}

		ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
				  "Failed %s on Device %4.4s, %s\n",
				  ACPI_CAST_PTR(char, method_names[i]),
				  acpi_ut_get_node_name(device_node),
				  acpi_format_exception(status)));
	}

	return_ACPI_STATUS(final_status);
}


text:
"""
    Dummy conftest.py for mlrampup.

    If you don't know what this is for, just leave it empty.
    Read more about conftest.py under:
    https://pytest.org/latest/plugins.html
"""
from __future__ import print_function, absolute_import, division

import pytest


text:
<?php

use yii\db\Migration;

class m170627_081144_roadTable extends Migration
{
    public function safeUp()
    {
        $this->createTable('Trips', [
            'id' => $this->primaryKey(),
            'fn' => $this->string(),
            'tn' => $this->string(),
            'fn_country_id' => $this->integer(),
            'tn_country_id' => $this->integer(),
            'min_price' => $this->integer(),
            'average_price' => $this->integer(),
            'max_price' => $this->integer(),
        ]);
    }

    public function safeDown()
    {
        $this->dropTable('Trips');
    }

    /*
    // Use up()/down() to run migration code without a transaction.
    public function up()
    {

    }

    public function down()
    {
        echo "m170627_081144_roadTable cannot be reverted.\n";

        return false;
    }
    */
}


text:
package io.github.mattshen.dbkit.core.models;

public class Query {
}


text:
// Copyright (c) 2014 Augie R. Maddox, Guavaman Enterprises. All rights reserved.
#pragma warning disable 0219
#pragma warning disable 0618
#pragma warning disable 0649
#pragma warning disable 0414

namespace Rewired.Editor {

    using UnityEngine;
    using UnityEditor;
    using System.IO;
    using Rewired;
    using Rewired.Platforms;
    using Rewired.Utils;

    [InitializeOnLoad]
    [System.ComponentModel.Browsable(false)]
    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    public static class UnityEditorBridge {

        private static EditorPlatform editorPlatform;
        private static Platform platform;
        private static WebplayerPlatform webplayerPlatform;
        private static bool isEditor;

        private static void Initialize() {
            DeterminePlatform();
        }

        private static void DeterminePlatform() {
            editorPlatform = EditorPlatform.None;
            platform = Platform.Unknown;
            webplayerPlatform = WebplayerPlatform.None;
            isEditor = false;

            // Find out the platform
#if UNITY_EDITOR
            isEditor = true;
            editorPlatform = EditorPlatform.Unknown;
#endif

#if UNITY_EDITOR_WIN
            editorPlatform = EditorPlatform.Windows;
#endif

#if UNITY_EDITOR_OSX
            editorPlatform = EditorPlatform.OSX;
#endif

#if UNITY_STANDALONE_OSX
            platform = Platform.OSX;

#endif

#if UNITY_DASHBOARD_WIDGET

#endif

#if UNITY_STANDALONE_WIN
            platform = Platform.Windows;
#endif

#if UNITY_STANDALONE_LINUX
            platform = Platform.Linux;
#endif

#if UNITY_STANDALONE

#endif

#if UNITY_ANDROID
            platform = Platform.Android;
#endif

#if UNITY_BLACKBERRY
            platform = Platform.Blackberry;
#endif

#if UNITY_WP8
            platform = Platform.WindowsPhone8;
#endif

#if UNITY_IPHONE
            platform = Platform.iOS;
#endif

#if UNITY_IOS
            platform = Platform.iOS;
#endif

#if UNITY_PS3
            platform = Platform.PS3;
#endif

#if UNITY_PS4
            platform = Platform.PS4;
#endif

#if UNITY_PSP2
            platform = Platform.PSVita;
#endif

#if UNITY_PSM
            platform = Platform.PSMobile;
#endif

#if UNITY_XBOX360
            platform = Platform.Xbox360;
#endif

#if UNITY_XBOXONE
            platform = Platform.XboxOne;
#endif

#if UNITY_WII
            platform = Platform.Wii;
#endif

#if UNITY_WIIU
            platform = Platform.WiiU;
#endif

#if UNITY_FLASH
            platform = Platform.Flash;
#endif

#if UNITY_METRO
            platform = Platform.WindowsAppStore;
#endif

#if UNITY_WINRT

#endif

#if UNITY_WEBGL
            platform = Platform.WebGL;
#endif

            // Check if Webplayer
#if UNITY_WEBPLAYER

            webplayerPlatform = UnityTools.DetermineWebplayerPlatformType(platform, editorPlatform); // call this BEFORE you change the platform so we still know what base system this is
            platform = Platform.Webplayer;

#endif

        }
    }
}


text:
def reverse(coconuts, sailors):
    curnuts = coconuts
    print "We start with %d coconuts, and %d sailors. And a monkey." % (coconuts, sailors)
    for i in range(sailors):
        sailor_takes = curnuts / 5
        print "The sailor takes %d for himself." % sailor_takes
        remainder = curnuts % 5
        print "The amount left over after the split is %d." % remainder
        #remainder-=1
        print "The monkey gets one."
        curnuts = (curnuts - sailor_takes) - remainder # for the monkey
        print "The amount left over for the other sailors is %d." % curnuts
    if curnuts % sailors == 0:
        curnuts /= sailors
        print "The end amount splits evenly. %d each." % curnuts
    else:
        print "It doesn't split %d ways: %d / %d = %d with remainder %d" % (sailors, curnuts, sailors, curnuts / sailors, curnuts % sailors)

reverse(11, 2)
reverse(25, 3)
reverse(253, 4)
reverse(3121, 5)
reverse(46651, 6)
reverse(823537, 7)


text:
function facebook_setup(appid) {
        window.fbAsyncInit = function() {
          FB.init({
            appId      : appid,
            status     : true,
            cookie     : true,
            xfbml      : true,
            oauth      : true,
          });
          FB.Event.subscribe('auth.login', function(r) {
              if ( r.status === 'connected' )
              {
                  console.log(r)
              }
          });
        };

        (function(d){
           var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           d.getElementsByTagName('head')[0].appendChild(js);
         }(document));
       }


text:
package dat076.group4.model.persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

/**
 * A container for entities that supports
 * common CRUD operations.
 *
 * @param <T> Type of items in container
 * @param <K> Primary key for items
 */
public abstract class AbstractDAO<T, K> implements IDAO<T, K> {

    private final Class<T> type;

    public AbstractDAO(Class<T> type) {
        this.type = type;
    }

    protected abstract EntityManager getEntityManager();

    @Override
    public void create(T t) {
        getEntityManager().persist(t);
    }

    @Override
    public void delete(K id) {
        T t = getEntityManager().getReference(type, id);
        getEntityManager().remove(t);
    }

    @Override
    public void update(T t) {
        getEntityManager().merge(t);
    }

    @Override
    public T find(K id) {
        return getEntityManager().find(type, id);
    }

    @Override
    public List<T> findAll() {
        return getEntityManager().createQuery(
               "select t from " + type.getSimpleName() + " t", type)
               .getResultList();
    }

    @Override
    public List<T> findRange(int first, int n) {
        TypedQuery<T> q = getEntityManager().createQuery(
                "select t from " + type.getSimpleName() + " t", type);
        q.setFirstResult(first);
        q.setMaxResults(n);
        return q.getResultList();
    }

    @Override
    public int count() {
        return getEntityManager().createQuery(
               "select count(t) from " + type.getSimpleName() + " t", Long.class)
               .getSingleResult().intValue();
    }
}


text:
import {
    addClass,
    getCaretPosition,
    getComputedStyle,
    getCssTransform,
    getScrollableElement,
    getScrollbarWidth,
    innerWidth,
    offset,
    resetCssTransform,
    setCaretPosition,
    hasVerticalScrollbar,
    hasHorizontalScrollbar
} from './../helpers/dom/element';
import autoResize from 'autoResize';
import {BaseEditor} from './_baseEditor';
import {eventManager as eventManagerObject} from './../eventManager';
import {getEditor, registerEditor} from './../editors';
import {KEY_CODES} from './../helpers/unicode';
import {stopPropagation, stopImmediatePropagation, isImmediatePropagationStopped} from './../helpers/dom/event';

var TextEditor = BaseEditor.prototype.extend();

/**
 * @private
 * @editor TextEditor
 * @class TextEditor
 * @dependencies autoResize
 */
TextEditor.prototype.init = function() {
  var that = this;
  this.createElements();
  this.eventManager = eventManagerObject(this);
  this.bindEvents();
  this.autoResize = autoResize();

  this.instance.addHook('afterDestroy', function() {
    that.destroy();
  });
};

TextEditor.prototype.getValue = function() {
  return this.TEXTAREA.value;
};

TextEditor.prototype.setValue = function(newValue) {
  this.TEXTAREA.value = newValue;
};

var onBeforeKeyDown = function onBeforeKeyDown(event) {
  var instance = this,
      that = instance.getActiveEditor(),
      ctrlDown;

  // catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
  ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;

  // Process only events that have been fired in the editor
  if (event.target !== that.TEXTAREA || isImmediatePropagationStopped(event)) {
    return;
  }

  if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
    // when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
    stopImmediatePropagation(event);
    return;
  }

  switch (event.keyCode) {
    case KEY_CODES.ARROW_RIGHT:
      if (that.isInFullEditMode()) {
        if ((!that.isWaiting() && !that.allowKeyEventPropagation) ||
            (!that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode))) {
          stopImmediatePropagation(event);
        }
      }
      break;
    case KEY_CODES.ARROW_LEFT:
      if (that.isInFullEditMode()) {
        if ((!that.isWaiting() && !that.allowKeyEventPropagation) ||
            (!that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode))) {
          stopImmediatePropagation(event);
        }
      }
      break;
    case KEY_CODES.ARROW_UP:
    case KEY_CODES.ARROW_DOWN:
      if (that.isInFullEditMode()) {
        if ((!that.isWaiting() && !that.allowKeyEventPropagation) ||
            (!that.isWaiting() && that.allowKeyEventPropagation && !that.allowKeyEventPropagation(event.keyCode))) {
          stopImmediatePropagation(event);
        }
      }
      break;

    case KEY_CODES.ENTER:
      var selected = that.instance.getSelected();
      var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
      if ((ctrlDown && !isMultipleSelection) || event.altKey) { // if ctrl+enter or alt+enter, add new line
        if (that.isOpened()) {
          var caretPosition = getCaretPosition(that.TEXTAREA),
              value = that.getValue();

          var newValue = value.slice(0, caretPosition) + '\n' + value.slice(caretPosition);

          that.setValue(newValue);

          setCaretPosition(that.TEXTAREA, caretPosition + 1);

        } else {
          that.beginEditing(that.originalValue + '\n');
        }
        stopImmediatePropagation(event);
      }
      event.preventDefault(); // don't add newline to field
      break;

    case KEY_CODES.A:
    case KEY_CODES.X:
    case KEY_CODES.C:
    case KEY_CODES.V:
      if (ctrlDown) {
        stopImmediatePropagation(event); // CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
      }
      break;

    case KEY_CODES.BACKSPACE:
    case KEY_CODES.DELETE:
    case KEY_CODES.HOME:
    case KEY_CODES.END:
      stopImmediatePropagation(event); // backspace, delete, home, end should only work locally when cell is edited (not in table context)
      break;
  }

  if ([KEY_CODES.ARROW_UP, KEY_CODES.ARROW_RIGHT, KEY_CODES.ARROW_DOWN, KEY_CODES.ARROW_LEFT].indexOf(event.keyCode) === -1) {
    that.autoResize.resize(String.fromCharCode(event.keyCode));
  }
};

TextEditor.prototype.open = function() {
  this.refreshDimensions(); // need it instantly, to prevent https://github.com/handsontable/handsontable/issues/348

  this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};

TextEditor.prototype.close = function(tdOutside) {
  this.textareaParentStyle.display = 'none';

  this.autoResize.unObserve();

  if (document.activeElement === this.TEXTAREA) {
    this.instance.listen(); // don't refocus the table if user focused some cell outside of HT on purpose
  }
  this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};

TextEditor.prototype.focus = function() {
  this.TEXTAREA.focus();
  setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length);
};

TextEditor.prototype.createElements = function() {
  //    this.$body = $(document.body);

  this.TEXTAREA = document.createElement('TEXTAREA');

  addClass(this.TEXTAREA, 'handsontableInput');

  this.textareaStyle = this.TEXTAREA.style;
  this.textareaStyle.width = 0;
  this.textareaStyle.height = 0;

  this.TEXTAREA_PARENT = document.createElement('DIV');
  addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder');

  this.textareaParentStyle = this.TEXTAREA_PARENT.style;
  this.textareaParentStyle.top = 0;
  this.textareaParentStyle.left = 0;
  this.textareaParentStyle.display = 'none';

  this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);

  this.instance.rootElement.appendChild(this.TEXTAREA_PARENT);

  var that = this;
  this.instance._registerTimeout(setTimeout(function() {
    that.refreshDimensions();
  }, 0));
};

TextEditor.prototype.getEditedCell = function() {
  var editorSection = this.checkEditorSection(),
      editedCell;

  switch (editorSection) {
    case 'top':
      editedCell = this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 101;
      break;
    case 'top-left-corner':
      editedCell = this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 103;
      break;
    case 'bottom-left-corner':
      editedCell = this.instance.view.wt.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 103;
      break;
    case 'left':
      editedCell = this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 102;
      break;
    case 'bottom':
      editedCell = this.instance.view.wt.wtOverlays.bottomOverlay.clone.wtTable.getCell({
        row: this.row,
        col: this.col
      });
      this.textareaParentStyle.zIndex = 102;
      break;
    default:
      editedCell = this.instance.getCell(this.row, this.col);
      this.textareaParentStyle.zIndex = '';
      break;
  }

  return editedCell != -1 && editedCell != -2 ? editedCell : void 0;
};

TextEditor.prototype.refreshDimensions = function() {
  if (this.state !== Handsontable.EditorState.EDITING) {
    return;
  }
  this.TD = this.getEditedCell();

  // TD is outside of the viewport.
  if (!this.TD) {
    this.close(true);

    return;
  }
  var currentOffset = offset(this.TD),
      containerOffset = offset(this.instance.rootElement),
      scrollableContainer = getScrollableElement(this.TD),
      totalRowsCount = this.instance.countRows(),
      editTop = currentOffset.top - containerOffset.top - 1 - (scrollableContainer.scrollTop || 0),
      editLeft = currentOffset.left - containerOffset.left - 1 - (scrollableContainer.scrollLeft || 0),

      settings = this.instance.getSettings(),
      rowHeadersCount = this.instance.hasRowHeaders(),
      colHeadersCount = this.instance.hasColHeaders(),
      editorSection = this.checkEditorSection(),
      backgroundColor = this.TD.style.backgroundColor,
      cssTransformOffset;

  // TODO: Refactor this to the new instance.getCell method (from #ply-59), after 0.12.1 is released
  switch (editorSection) {
    case 'top':
      cssTransformOffset = getCssTransform(this.instance.view.wt.wtOverlays.topOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'left':
      cssTransformOffset = getCssTransform(this.instance.view.wt.wtOverlays.leftOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'top-left-corner':
      cssTransformOffset = getCssTransform(this.instance.view.wt.wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'bottom-left-corner':
      cssTransformOffset = getCssTransform(this.instance.view.wt.wtOverlays.bottomLeftCornerOverlay.clone.wtTable.holder.parentNode);
      break;
    case 'bottom':
      cssTransformOffset = getCssTransform(this.instance.view.wt.wtOverlays.bottomOverlay.clone.wtTable.holder.parentNode);
      break;
  }

  if (colHeadersCount && this.instance.getSelected()[0] === 0 ||
      (settings.fixedRowsBottom && this.instance.getSelected()[0] === totalRowsCount - settings.fixedRowsBottom)) {
    editTop += 1;
  }

  if (this.instance.getSelected()[1] === 0) {
    editLeft += 1;
  }

  if (cssTransformOffset && cssTransformOffset != -1) {
    this.textareaParentStyle[cssTransformOffset[0]] = cssTransformOffset[1];
  } else {
    resetCssTransform(this.TEXTAREA_PARENT);
  }

  this.textareaParentStyle.top = editTop + 'px';
  this.textareaParentStyle.left = editLeft + 'px';

  let firstRowOffset = this.instance.view.wt.wtViewport.rowsRenderCalculator.startPosition;
  let firstColumnOffset = this.instance.view.wt.wtViewport.columnsRenderCalculator.startPosition;
  let horizontalScrollPosition = this.instance.view.wt.wtOverlays.leftOverlay.getScrollPosition();
  let verticalScrollPosition = this.instance.view.wt.wtOverlays.topOverlay.getScrollPosition();
  let scrollbarWidth = getScrollbarWidth();

  let cellTopOffset = this.TD.offsetTop + firstRowOffset - verticalScrollPosition;
  let cellLeftOffset = this.TD.offsetLeft + firstColumnOffset - horizontalScrollPosition;

  let width = innerWidth(this.TD) - 8;
  let actualVerticalScrollbarWidth = hasVerticalScrollbar(scrollableContainer) ? scrollbarWidth : 0;
  let actualHorizontalScrollbarWidth = hasHorizontalScrollbar(scrollableContainer) ? scrollbarWidth : 0;
  let maxWidth = this.instance.view.maximumVisibleElementWidth(cellLeftOffset) - 9 - actualVerticalScrollbarWidth;
  let height = this.TD.scrollHeight + 1;
  let maxHeight = Math.max(this.instance.view.maximumVisibleElementHeight(cellTopOffset) - actualHorizontalScrollbarWidth, 23);

  const cellComputedStyle = getComputedStyle(this.TD);

  this.TEXTAREA.style.fontSize = cellComputedStyle.fontSize;
  this.TEXTAREA.style.fontFamily = cellComputedStyle.fontFamily;
  this.TEXTAREA.style.backgroundColor = ''; // RESET STYLE
  this.TEXTAREA.style.backgroundColor = backgroundColor ? backgroundColor : getComputedStyle(this.TEXTAREA).backgroundColor;

  this.autoResize.init(this.TEXTAREA, {
    minHeight: Math.min(height, maxHeight),
    maxHeight: maxHeight, // TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
    minWidth: Math.min(width, maxWidth),
    maxWidth: maxWidth // TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
  }, true);

  this.textareaParentStyle.display = 'block';
};

TextEditor.prototype.bindEvents = function() {
  var editor = this;

  this.eventManager.addEventListener(this.TEXTAREA, 'cut', function(event) {
    stopPropagation(event);
  });

  this.eventManager.addEventListener(this.TEXTAREA, 'paste', function(event) {
    stopPropagation(event);
  });

  this.instance.addHook('afterScrollHorizontally', function() {
    editor.refreshDimensions();
  });

  this.instance.addHook('afterScrollVertically', function() {
    editor.refreshDimensions();
  });

  this.instance.addHook('afterColumnResize', function() {
    editor.refreshDimensions();
    editor.focus();
  });

  this.instance.addHook('afterRowResize', function() {
    editor.refreshDimensions();
    editor.focus();
  });

  this.instance.addHook('afterDestroy', function() {
    editor.eventManager.destroy();
  });
};

TextEditor.prototype.destroy = function() {
  this.eventManager.destroy();
};

export {TextEditor};

registerEditor('text', TextEditor);


text:
<!DOCTYPE html>

	<title></title>

Who We Belongs......

Top Solver......

Developer......

Creative Person.......

 Jubair Azam

 Foyaz Rahman Akondo

 Nazmul Islam

 Yusuf

 Nayeem Hasan Apu

							  Previous

							  Next


text:
Doodie
======

An pagerduty dashboard.

![Screenshot](https://raw.github.com/ohlol/doodie/master/doodie.png)

Setup
=====

    $ pip install -r requirements.txt
    $ cat > local_settings.py <<EOF
    PAGERDUTY_APIKEY="<apikey here>"
    PAGERDUTY_SUBDOMAIN="<subdomain here>"
    EOF

    $ env FLASK_DEBUG=true ./manage.py runserver &
    $ open http://localhost:7777/incidents