text:
#include <sys/stat.h>

#include <sstream>

#include "java_generator.h"

#include "../hot.h"
#include "../string_helper.h"
#include "../os.h"
#include "../type_helper.h"

namespace org {
namespace labcrypto {
namespace hottentot {
namespace generator {
namespace java {
  void
  JavaGenerator::GenerateServiceProxy (
    ::org::labcrypto::hottentot::generator::Module *pModule
  ) {

    int serializableListCounter = 0;
    ::org::labcrypto::hottentot::generator::Service *pService;
    std::string basePackageName = pModule->package_;
    for (uint32_t i = 0; i < pModule->services_.size(); i++) {
      std::string replacableServiceProxyStrTmp = serviceProxyTmpStr_;
      pService = pModule->services_.at(i);
      pService = pModule->services_.at(i);
      ::org::labcrypto::hottentot::generator::StringHelper::Replace (
        replacableServiceProxyStrTmp,
        "[%INDENT%]",
        indent_,
        1
      );
      ::org::labcrypto::hottentot::generator::StringHelper::Replace (
        replacableServiceProxyStrTmp,
        "[%BASE_PACKAGE_NAME%]",
        basePackageName + (extendModule_.size() > 0 ? "." : "") + extendModule_,
        1
      );
      ::org::labcrypto::hottentot::generator::StringHelper::Replace (
        replacableServiceProxyStrTmp,
        "[%SERVICE_NAME%]",
        pService->name_,
        1
      );
      ::org::labcrypto::hottentot::generator::Method *pMethod;
      std::string methodsStr;
      for (uint32_t i = 0; i < pService->methods_.size(); i++) {
        pMethod = pService->methods_.at(i);
        std::string fetchedReturnTypeOfList;
        std::string lowerCaseFetchedReturnTypeOfList;
        std::string returnType = ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaType(pMethod->returnType_);
        std::string lowerCaseReturnType = pMethod->returnType_;
        std::string capitalizedReturnType =
        ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pMethod->returnType_);
        lowerCaseReturnType[0] += 32;
        if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pMethod->returnType_)) {
          fetchedReturnTypeOfList =
            ::org::labcrypto::hottentot::generator::TypeHelper::FetchTypeOfList(pMethod->returnType_);
          std::string returnTypeOfList =
            ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaClassType(fetchedReturnTypeOfList);
          returnType = "List<" + returnTypeOfList + ">";
        }
        methodsStr += indent_ + "public " + returnType + " " + pMethod->name_ + "(";
        ::org::labcrypto::hottentot::generator::Argument *pArg;
        std::string fetchedArgTypeOfList;
        std::string argType;
        for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) {
          pArg = pMethod->arguments_.at(i);
          if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pArg->type_)) {
            fetchedArgTypeOfList =
              ::org::labcrypto::hottentot::generator::TypeHelper::FetchTypeOfList(pArg->type_);
            std::string argTypeOfList =
              ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaClassType(fetchedArgTypeOfList);
            argType = "List<" + argTypeOfList + ">";
          } else {
            argType = ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaType(pArg->type_);
          }
          methodsStr += argType + " " + pArg->variable_;
          if (i < pMethod->arguments_.size() - 1) {
            methodsStr += ",";
          }
        }
        methodsStr += ") { \n";
        for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) {
          pArg = pMethod->arguments_.at(i);
          methodsStr += indent_ + indent_ + "//serialize " + pArg->variable_ + "\n";
          std::string capitalalizedArgVar =
          ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pArg->variable_);
          if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pArg->type_)) {
            std::string fetchedArgTypeOfList;
            serializableListCounter++;
            std::stringstream serializableListCounterStream;
            serializableListCounterStream << serializableListCounter;
            fetchedArgTypeOfList =
              ::org::labcrypto::hottentot::generator::TypeHelper::FetchTypeOfList(pArg->type_);
            std::string upperCaseArgTypeOfList =
              ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(fetchedArgTypeOfList);
            methodsStr += indent_ + indent_ +
                          "Serializable" + upperCaseArgTypeOfList + "List " +
                          "serializable" + upperCaseArgTypeOfList + "List_" +
                          serializableListCounterStream.str() +
                          " = new Serializable" + upperCaseArgTypeOfList + "List();\n";
            methodsStr += "serializable" + upperCaseArgTypeOfList + "List_" +
            serializableListCounterStream.str() +
            ".set" +
            upperCaseArgTypeOfList + "List(" + pArg->variable_ + ");\n";
            methodsStr += "byte[] serialized" +  capitalalizedArgVar +
                          " = serializable" + upperCaseArgTypeOfList + "List_" +
                          serializableListCounterStream.str() +
                          ".serialize();\n";
          } else if (::org::labcrypto::hottentot::generator::TypeHelper::IsUDT(pArg->type_)) {
            methodsStr += indent_ + indent_ +
                          "byte[] serialized" +
                          capitalalizedArgVar + " = " +
                          pArg->variable_ + ".serialize();\n";
          } else {
            std::string pdtWrapperClass =
              ::org::labcrypto::hottentot::generator::TypeHelper::GetPdtWrapperClassName(pArg->type_);
            methodsStr += indent_ + indent_ +
                          pdtWrapperClass + " " + pArg->variable_ + "Wrapper = new " +
                          pdtWrapperClass + "(" + pArg->variable_ + ");\n";
            methodsStr += indent_ + indent_ +
                          "byte[] serialized" +
                          capitalalizedArgVar + " = " +
                          pArg->variable_ + "Wrapper.serialize();\n";
          }
        }
        methodsStr += "\n";
        methodsStr += indent_ + indent_ + "//make request\n";
        methodsStr += indent_ + indent_ + "Request request = new Request();\n";
        std::stringstream serviceId;
        serviceId << pService->GetHash();
        methodsStr += indent_ + indent_ + "request.setServiceId(" + serviceId.str() + "L);\n";
        std::stringstream methodId;
        methodId << pMethod->GetHash();
        methodsStr += indent_ + indent_ + "request.setMethodId(" + methodId.str() + "L);\n";
        std::stringstream argSize;
        argSize << pMethod->arguments_.size();
        methodsStr +=
        indent_ + indent_ + "request.setArgumentCount((byte) " + argSize.str() + ");\n";
        methodsStr += indent_ + indent_ + "request.setType(Request.RequestType.";
        if (pService->serviceType_ == 0) {
          methodsStr += "InvokeStateless";
        } else if (pService->serviceType_ == 1) {
          methodsStr += "InvokeStatefull";
        }
        methodsStr += ");\n";
        for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) {
          std::stringstream ssI;
          pArg = pMethod->arguments_.at(i);
          ssI << i;
          std::string capitalizedArgVar =
            ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pArg->variable_);
          methodsStr += indent_ + indent_ + "Argument arg" + ssI.str() + " = new Argument();\n";
          methodsStr += indent_ + indent_ + "arg" + ssI.str() + ".setDataLength(" +
                        "serialized" + capitalizedArgVar + ".length);\n";
          methodsStr += indent_ + indent_ +
                        "arg" + ssI.str() + ".setData(serialized" + capitalizedArgVar + ");\n";
          methodsStr += indent_ + indent_ +
                       "request.addArgument(arg" + ssI.str() + ");\n";
        }
        methodsStr += indent_ + indent_ + "int dataLength = 0;\n";
        methodsStr += indent_ + indent_ + "//calculate data length for every argument\n";
        for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) {
          pArg = pMethod->arguments_.at(i);
          std::string argDataLengthVarName = pArg->variable_ + "DataLength";
          std::string capitalizedArgVar =
            ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pArg->variable_);
          std::string argDataLengthByteArrayLengthVarName =
          pArg->variable_ + "DataLengthByteArrayLength";
          methodsStr += indent_ + indent_ + "// calulate " + argDataLengthVarName + "\n";
          methodsStr += indent_ + indent_ + "int " + argDataLengthVarName + "= serialized" +
          capitalizedArgVar  + ".length;\n";
          methodsStr += indent_ + indent_ + "int " + argDataLengthByteArrayLengthVarName + " = 1;\n";
          methodsStr += indent_ + indent_ + "if (" + argDataLengthVarName + " >= 0x80) {\n";
          methodsStr += indent_ + indent_ + indent_ + "if (" + argDataLengthVarName + " <= 0xff) {\n";
          methodsStr += indent_ + indent_ + indent_ + indent_ + "//ex 0x81 0xff\n";
          methodsStr += indent_ + indent_ + indent_ + indent_ + "" +
          argDataLengthByteArrayLengthVarName + " = 2;\n";
          methodsStr += indent_ + indent_ + indent_ + "} else if (" + argDataLengthVarName + " <= 0xffff) {\n";
          methodsStr += indent_ + indent_ + indent_ + indent_ + "//ex 0x82 0xff 0xff\n";
          methodsStr += indent_ + indent_ + indent_ + indent_ + "" +
          argDataLengthByteArrayLengthVarName + " = 3;\n";
          methodsStr += indent_ + indent_ + indent_ + "} else if (" + argDataLengthVarName + " <= 0xffffff) {\n";
          methodsStr += indent_ + indent_ + indent_ + indent_ + "//ex 0x83 0xff 0xff 0xff\n";
          methodsStr += indent_ + indent_ + indent_ + indent_ + "" +
          argDataLengthByteArrayLengthVarName + " = 4;\n";
          methodsStr += indent_ + indent_ + indent_ + "}\n";
          methodsStr += indent_ + indent_ + "}\n";
          methodsStr += indent_ + indent_ + "dataLength += " + argDataLengthVarName + " + " +
          argDataLengthByteArrayLengthVarName + ";\n";
        }
        methodsStr += indent_ + indent_ + "// arg count(1) + request type(1) + method ID(4) + service ID(4) = 10;\n";
        methodsStr += indent_ + indent_ + "request.setLength(10 + dataLength);\n";
        methodsStr += indent_ + indent_ + "// connect to server\n";
        methodsStr += indent_ + indent_ + "TcpClient tcpClient = TcpClientFactory.create();\n";
        methodsStr += indent_ + indent_ + "try{\n";
        methodsStr += indent_ + indent_ + indent_ + "tcpClient.connect(host, port);\n";
        methodsStr += indent_ + indent_ + "} catch (TcpClientConnectException e) {\n";
        methodsStr += indent_ + indent_ + indent_ + "throw new HottentotRuntimeException(e);\n";
        methodsStr += indent_ + indent_ + "}\n";
        methodsStr += indent_ + indent_ + "// serialize request according to HTNP\n";
        methodsStr += indent_ + indent_ + "Protocol protocol = ProtocolFactory.create();\n";
        methodsStr += indent_ + indent_ +
        "byte[] serializedRequest = protocol.serializeRequest(request);\n";
        methodsStr += indent_ + indent_ + "// send request\n";
        methodsStr += indent_ + indent_ + "try {\n";
        methodsStr += indent_ + indent_ + indent_ + "tcpClient.write(serializedRequest);\n";
        methodsStr += indent_ + indent_ + "} catch (TcpClientWriteException e) {\n";
        methodsStr += indent_ + indent_ + indent_ + "throw new HottentotRuntimeException(e);\n";
        methodsStr += indent_ + indent_ + "}\n";
        if (!::org::labcrypto::hottentot::generator::TypeHelper::IsVoid(pMethod->returnType_)) {
          methodsStr += indent_ + indent_ + "// read response from server\n";
          methodsStr += indent_ + indent_ + "byte[] buffer = new byte[256];\n";
          methodsStr += indent_ + indent_ + "while (!protocol.isResponseComplete()) {\n";
          methodsStr += indent_ + indent_ + indent_ + "byte[] dataChunkRead;\n";
          methodsStr += indent_ + indent_ + indent_ + "try {\n";
          methodsStr += indent_ + indent_ + indent_ + indent_ + "dataChunkRead = tcpClient.read();\n";
          methodsStr += indent_ + indent_ + indent_ + "} catch (TcpClientReadException e) {\n";
          methodsStr +=
            indent_ + indent_ + indent_ + indent_ + "throw new HottentotRuntimeException(e);\n";
          methodsStr += indent_ + indent_ + indent_ + "}\n";
          methodsStr +=
            indent_ + indent_ + indent_ + "protocol.processDataForResponse(dataChunkRead);\n";
          methodsStr += indent_ + indent_ + "}\n";
          methodsStr += indent_ + indent_ + "Response response = protocol.getResponse();\n";
          methodsStr += indent_ + indent_ + "// close everything\n";
          methodsStr += indent_ + indent_ + " try { \n";
          methodsStr += indent_ + indent_ + indent_ + " tcpClient.close(); \n";
          methodsStr += indent_ + indent_ + "} catch (TcpClientCloseException e) { \n";
          methodsStr += indent_ + indent_ + indent_ + "e.printStackTrace(); \n";
          methodsStr += indent_ + indent_ + "} \n";
          methodsStr += indent_ + indent_ + "//deserialize " + pMethod->returnType_ + "part from response\n";
          if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pMethod->returnType_)) {
            std::string upperCaseReturnTypeOfList =
              ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(fetchedReturnTypeOfList);
            serializableListCounter++;
            std::stringstream serializableListCounterStream;
            serializableListCounterStream << serializableListCounter;
            methodsStr += indent_ + indent_ +
                          "Serializable" + upperCaseReturnTypeOfList + "List" +
                          " serializable" + upperCaseReturnTypeOfList + "List_" +
                          serializableListCounterStream.str() +
                          " = null;\n";
            methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n";
            methodsStr += indent_ + indent_ + indent_ +
                          "throw new MethodNotSupportRuntimeException();\n";
            methodsStr += indent_ + indent_ + "}\n";
            methodsStr += indent_ + indent_ +
                          "serializable" + upperCaseReturnTypeOfList + "List_" +
                          serializableListCounterStream.str() +
                          " = new Serializable" + upperCaseReturnTypeOfList + "List();\n";
            methodsStr += indent_ + indent_ +
                          "serializable" + upperCaseReturnTypeOfList + "List_" +
                          serializableListCounterStream.str() +
                          ".deserialize(response.getData());\n";
            methodsStr += indent_ + indent_ +
                          "return serializable" + upperCaseReturnTypeOfList +
                          "List_" +
                          serializableListCounterStream.str() +
                          ".get" + upperCaseReturnTypeOfList + "List();\n";
          } else if (::org::labcrypto::hottentot::generator::TypeHelper::IsEnum(pMethod->returnType_)) {
            methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n";
            methodsStr += indent_ + indent_ + indent_ +
                          "throw new MethodNotSupportRuntimeException();\n";
            methodsStr += indent_ + indent_ + "}\n";
            methodsStr += indent_ + indent_ +
                          "return " + pMethod->returnType_ + ".deserialize(response.getData());\n";
          } else if (::org::labcrypto::hottentot::generator::TypeHelper::IsUDT(pMethod->returnType_)) {
            methodsStr += indent_ + indent_ +
                          returnType + " " + lowerCaseReturnType + "= null;\n";
            methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n";
            methodsStr += indent_ + indent_ + indent_ +
                          "throw new MethodNotSupportRuntimeException();\n";            methodsStr += indent_ + indent_ + "}\n";
            methodsStr += indent_ + indent_ + "" + lowerCaseReturnType + "= new " +
                          pMethod->returnType_ + "();\n";
            methodsStr += indent_ + indent_ + "" + lowerCaseReturnType +
                          ".deserialize(response.getData());\n";
            methodsStr += indent_ + indent_ + "return " + lowerCaseReturnType + ";\n";
          } else {
            methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n";
            methodsStr += indent_ + indent_ + indent_ +
                          "throw new MethodNotSupportRuntimeException();\n";
            methodsStr += indent_ + indent_ + "}\n";
            std::string pdtWrapperClassName =
              ::org::labcrypto::hottentot::generator::TypeHelper::GetPdtWrapperClassName (pMethod->returnType_);
            methodsStr += indent_ + indent_ +
                          pdtWrapperClassName + " ret = new " +
                          pdtWrapperClassName + "();\n";
            methodsStr += indent_ + indent_ +
                          "ret.deserialize(response.getData());\n";
            methodsStr += indent_ + indent_ +
                          "return ret.getValue();\n";
          }
        }
        methodsStr += indent_ + "}\n";
      }
      replacableServiceProxyStrTmp.replace (
        replacableServiceProxyStrTmp.find("[%METHODS%]"),
        11,
        methodsStr
      );
      std::string packages =
        ::org::labcrypto::hottentot::generator::StringHelper::Concat (
          ::org::labcrypto::hottentot::generator::StringHelper::Split (
           pModule->GetPackage() + (extendModule_.size() > 0 ? "." : "") + extendModule_,
            '.'
          ),
          "/"
        );
      ::org::labcrypto::hottentot::generator::Os::MakeDir(outDir_ + "/" + packages);
      std::string path = outDir_ + "/" + packages + "/" +
        pService->name_.c_str() + "ServiceProxy.java";
      ::org::labcrypto::hottentot::generator::Os::WriteFile(path , replacableServiceProxyStrTmp);
    }
  }
} // END NAMESPACE java
} // END NAMESPACE generator
} // END NAMESPACE hottentot
} // END NAMESPACE labcrypto
} // END NAMESPACE org


text:
@import url(https://fonts.googleapis.com/css?family=News+Cycle:400,700);
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic);
/*********************************************
 * GLOBAL STYLES
 *********************************************/
body {
  background: white;
  background-color: white; }

.reveal {
  font-family: "Lato", sans-serif;
  font-size: 36px;
  font-weight: normal;
  letter-spacing: -0.02em;
  color: black; }

::-moz-selection {
  color: white;
  background: rgba(0, 0, 0, 0.99);
  text-shadow: none; }

::selection {
  color: white;
  background: rgba(0, 0, 0, 0.99);
  text-shadow: none; }

/*********************************************
 * HEADERS
 *********************************************/
.reveal h1,
.reveal h2,
.reveal h3,
.reveal h4,
.reveal h5,
.reveal h6 {
  margin: 0 0 20px 0;
  color: black;
  font-family: "News Cycle", Impact, sans-serif;
  line-height: 0.9em;
  letter-spacing: 0.02em;
  text-transform: none;
  text-shadow: none;
  -webkit-transition: color .15s ease;
  transition: color .15s ease; }

.reveal h1 {
  text-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2); }

/*********************************************
 * LINKS
 *********************************************/
.reveal a:not(.image) {
  color: darkblue;
  text-decoration: none;
  -webkit-transition: color .15s ease;
  transition: color .15s ease; }

.reveal a:not(.image):hover {
  color: #0000f1;
  text-shadow: none;
  border: none; }

.reveal .roll span:after {
  color: #fff;
  background: #00003f; }

/*********************************************
 * IMAGES
 *********************************************/
.reveal section img {
  margin: 15px 0px;
  -webkit-transition: all .2s linear;
  transition: all .2s linear; }

/*********************************************
 * NAVIGATION CONTROLS
 *********************************************/
.reveal .controls div.navigate-left,
.reveal .controls div.navigate-left.enabled {
  border-right-color: darkblue; }

.reveal .controls div.navigate-right,
.reveal .controls div.navigate-right.enabled {
  border-left-color: darkblue; }

.reveal .controls div.navigate-up,
.reveal .controls div.navigate-up.enabled {
  border-bottom-color: darkblue; }

.reveal .controls div.navigate-down,
.reveal .controls div.navigate-down.enabled {
  border-top-color: darkblue; }

.reveal .controls div.navigate-left.enabled:hover {
  border-right-color: #0000f1; }

.reveal .controls div.navigate-right.enabled:hover {
  border-left-color: #0000f1; }

.reveal .controls div.navigate-up.enabled:hover {
  border-bottom-color: #0000f1; }

.reveal .controls div.navigate-down.enabled:hover {
  border-top-color: #0000f1; }

/*********************************************
 * PROGRESS BAR
 *********************************************/
.reveal .progress {
  background: rgba(0, 0, 0, 0.2); }

.reveal .progress span {
  background: darkblue;
  -webkit-transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985);
  transition: width 800ms cubic-bezier(0.26, 0.86, 0.44, 0.985); }

/*********************************************
 * SLIDE NUMBER
 *********************************************/
.reveal .slide-number {
  color: darkblue; }

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

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


text:
class Lokata extends KontoInwestycyjne
{
    double oprocentowanie;

    Lokata(double p)
    {
        super();
        oprocentowanie=p;
    }

    public void aktualizuj()
    {
        stan *= (oprocentowanie + 1);
    }
}


text:
package com.blnz.xsl.sax2;

/**
 * receives comment events from a parse
*/
public interface CommentHandler
{
    /**
     * recieve notification that a comment has been encountered
     * in the parse
     */
    void comment(String contents) throws org.xml.sax.SAXException;
}


text:
import { RaphaelAttributes, RaphaelBaseElement, RaphaelPaper, RaphaelPath, RaphaelSet } from "raphael";

declare module "raphael" {
    // Raphael.fn
    interface RaphaelPaper {
        arrow(x1: number, y1: number, x2: number, y2: number, size: number): RaphaelPath;
        myStuff: {
            arrow(flag: boolean): number;
            star(): void;
        };
        firstLevel: {
            secondLevel: {
                method(): boolean;
            }
        };
    }

    // Raphael.el
    interface RaphaelElement {
        red(): void;
        colored(r: number, g: number, b: number): this;
    }

    // RaphaelPaper.customAttributes
    interface RaphaelAttributes {
        hue: number;
        hsb: string;
    }

    // Raphael.st
    interface RaphaelSet {
        green(): void;
        colorized(r: number, g: number, b: number): this;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">

    <item android:drawable="@drawable/nw0" android:duration="500"/>
    <item android:drawable="@drawable/nw1" android:duration="500"/>
    <item android:drawable="@drawable/nw2" android:duration="500"/>
    <item android:drawable="@drawable/nw3" android:duration="500"/>
    <item android:drawable="@drawable/nw4" android:duration="500"/>
    <item android:drawable="@drawable/nw5" android:duration="500"/>
    <item android:drawable="@drawable/nw6" android:duration="500"/>
    <item android:drawable="@drawable/nw7" android:duration="500"/>
    <item android:drawable="@drawable/nw8" android:duration="500"/>
    <item android:drawable="@drawable/nw9" android:duration="500"/>

</animation-list>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycopath. Mycol. appl. 34: 271 (1968)

#### Original name
Cercospora magnoliae Ellis & Harkn., 1881

### Remarks
null


text:
@implementation UIBarButtonItem (ProjectButtons)

+ (UIBarButtonItem *)backArrowButtonWithTarget:(id)target action:(SEL)action
{
    UIImage *buttonImage = [UIImage imageNamed:@"backButton.png"];

    //create the button and assign the image
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:buttonImage forState:UIControlStateNormal];

    //set the frame of the button to the size of the image (see note below)
    button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    //create a UIBarButtonItem with the button as a custom view
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    return customBarItem;
}
@end


text:
layout: page
title: About Us
date: 2016-11-26
comments: false
---

While one was on a lookout for an idea, the other wanted a book subscription box that catered to her bookish whims without costing a bomb — that is precisely how The BiblioBox happened! We are a Bangalore-based book subscription box, fulfilling your monthly bookish needs with thoughtfully-curated monthly and customized boxes, bringing to you all things books! While the trend of subscription boxes is taking the world by a storm, it is slowly, yet surely, making its way to the Indian Subcontinent.

While most boxes around the world cater to a specific genre or an age group, we, at The BiblioBox, aim to satisfy every palette. Whether you dig classics, or crime, or fantasy, or young adult fiction, we have something for each of you.

Apart from just sending two books, instead of the usual practice of one book per box, we also have a huge array of bookish merchandise that is either specifically designed by an artist, or done in-house. Bringing book-nerd delights to bibliophiles in the land of diversity with diverse themes each month, apart from customized boxes tailored as per your needs, we are here to satiate all your bookish cravings!

Go, indulge!


text:
title: "2017 Updates"
layout: article
categories: Announcements
---

There have been a number of changes in 2017. New IDPA rules, the match fees are being increased and new incentives for helping to setup the match.

## Club related news

The general **club meeting will take place Feb 25th before the match.** Alan and Michael Scott will propose the new and retiring officers. It shouldn't take very long. If you are not an IDPA shooter this gives you a good reason to come and give it a try. IDPA has new rules that let you shoot 3 matches for free to try it out.

We are looking for an Equipment Manager. They would work closly with all the match directors in making sure they have everything they need for their match.  Also in charge of keeping the Conex's organized.  PLEASE reach out to Jim Smith if you are at all interested. Would be great to have 2 people working together on this.

The Liabilty Insurance went up by 3000 dollars due to increased participation. With this added cost we are raising our match fees. The membership is still the same $12 for a calender year and members continue to get a discount on matches. All other match fees are going up $5 across the board. That means the new match fee schedule is:

| **Match Type**  |**UDPL Member**|**Non Member**|
|Regular UDPL/IDPA Match | $20.00 | $30.00 |
|3 Gun Match| $25.00 | $35.00 |
|Female Shooters| $10.00 | $10.00 |
|Junior Shooters (17 and under)| $10.00 | $10.00 |
|Match Safety Officers | $5.00 | $5.00 |

Note that Match Safety Officers must be approved by the Match Director and the discount is only available if you are the SO at that match.

These new rates will be in effect with the 25th Febuary Match. **ALL FEES NEED TO BE PAID EITHER BY CASH OR CHECK**

Now with the new fees we are starting a "set up day bonus" for all those that come the day before a match and help with set up. Those that come and do the work not only get to shoot the MATCH AT NO COST but their name will be put in for a drawing for a gun at the end of the calender year.

Each time you come out and work with the match director they will turn over your name to be added for the drawing. The drawing will take place at NEXT years general member meeting (in 2018). Setup is a thankless job and we're hoping to encourage more people to help with these changes.

## Schedule for 2017

The schedule has been finalized and is available [here](https://www.udpl.net/schedule/). You can filter to see just the UDPL matches at the FARM by entering FARM in the box on the right side.

## February 25th IDPA match

This match will be using the new IDPA 2017 rules which you can find [here](http://www.idpa.com/compete/rules).

[Register on Practiscore](https://practiscore.com/udpl-2017-february-idpa-match/register)

A short summary of the rules can be found [here](http://www.actionpistolgroup.com/2017%20IDPA%20RULE%20CHANGE%20SYNOPSIS.pdf). My even shorter summary is:

* 1 second per point down
* No more Failure to Neutralize (FTN) penalty
* Head area of target has a new 4" circle that is the down 0. Outside of this circle but still on the head is now a down 1 zone.
* No more cover calls. Now we have fault lines. Inside the line and you're safe
* Shoot pretty much any gun in the NFC (Not for Competition) divison. This includes Pistol Caliber Carbines and handguns with optics.
* Maximum target distance for scenerio stages is 20 yards, 50 yards for standards stages
* Penalties for not helping to tape/reset or coaching a shooter

You can also now shoot 3 IDPA matches without being a member to try it out.


text:
package leap.lang.serialize;

public interface Serializer {

	String serialize(Object value);

	Object deserialize(String string);

	Object tryDeserialize(String string);

}


text:
from os.path import join, dirname
with open(join(dirname(__file__), "VERSION")) as _f:
    __version__ = _f.read().strip()
del _f, join, dirname


text:
package org.springframework.roo.addon.requestfactory.entity;

import static org.springframework.roo.model.RooJavaType.ROO_MONGO_ENTITY;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.component.ComponentContext;
import org.springframework.roo.addon.layers.repository.jpa.RepositoryJpaLocator;
import org.springframework.roo.addon.layers.repository.mongo.RepositoryMongoLocator;
import org.springframework.roo.addon.layers.service.ServiceAnnotationValues;
import org.springframework.roo.addon.layers.service.ServiceClassMetadata;
import org.springframework.roo.addon.plural.PluralMetadata;
import org.springframework.roo.addon.requestfactory.RequestFactoryTypeService;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.ItdTypeDetails;
import org.springframework.roo.classpath.details.MemberHoldingTypeDetails;
import org.springframework.roo.classpath.itd.AbstractMemberDiscoveringItdMetadataProvider;
import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.scanner.MemberDetails;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.project.LogicalPath;

/**
 * Provides {@link ServiceClassMetadata} for building the ITD for the
 * implementation class of a user project's service.
 *
 * @author Stefan Schmidt
 * @author Andrew Swan
 * @since 1.2.0
 */
@Component(immediate = true)
@Service
public class ServiceImplMetadataProvider extends
        AbstractMemberDiscoveringItdMetadataProvider {

    @Reference RepositoryJpaLocator repositoryJpaLocator;
    @Reference RepositoryMongoLocator repositoryMongoLocator;
    @Reference RequestFactoryTypeService requestFactoryTypeService;

    private final Map<JavaType, String> managedEntityTypes =
            new HashMap<JavaType, String>();

    protected void activate(final ComponentContext context) {
        metadataDependencyRegistry.addNotificationListener(this);
        metadataDependencyRegistry.registerDependency(
                PhysicalTypeIdentifier.getMetadataIdentiferType(),
                getProvidesType());
        setIgnoreTriggerAnnotations(true);
    }

    @Override
    protected String createLocalIdentifier(final JavaType javaType,
            final LogicalPath path) {
        return ServiceImplMetadata.createIdentifier(javaType, path);
    }

    protected void deactivate(final ComponentContext context) {
        metadataDependencyRegistry.removeNotificationListener(this);
        metadataDependencyRegistry.deregisterDependency(
                PhysicalTypeIdentifier.getMetadataIdentiferType(),
                getProvidesType());
    }

    @Override
    protected String getGovernorPhysicalTypeIdentifier(
            final String metadataIdentificationString) {
        final JavaType javaType = ServiceImplMetadata
                .getJavaType(metadataIdentificationString);
        final LogicalPath path = ServiceImplMetadata
                .getPath(metadataIdentificationString);
        return PhysicalTypeIdentifier.createIdentifier(javaType, path);
    }

    public String getItdUniquenessFilenameSuffix() {
        return "RequestFactory_Service";
    }

    @Override
    protected String getLocalMidToRequest(final ItdTypeDetails itdTypeDetails) {
        // Determine the governor for this ITD, and whether any metadata is even
        // hoping to hear about changes to that JavaType and its ITDs
        final JavaType governor = itdTypeDetails.getName();
        final String localMid = managedEntityTypes.get(governor);
        if (localMid != null) {
            return localMid;
        }

        final MemberHoldingTypeDetails memberHoldingTypeDetails =
                typeLocationService.getTypeDetails(governor);
        if (memberHoldingTypeDetails != null) {
            for (final JavaType type : memberHoldingTypeDetails
                    .getLayerEntities()) {
                final String localMidType = managedEntityTypes.get(type);
                if (localMidType != null) {
                    return localMidType;
                }
            }
        }
        return null;
    }

    @Override
    protected ItdTypeDetailsProvidingMetadataItem getMetadata(
            final String metadataIdentificationString,
            final JavaType aspectName,
            final PhysicalTypeMetadata governorPhysicalTypeMetadata,
            final String itdFilename) {
        final ClassOrInterfaceTypeDetails serviceClass =
                governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
        if (serviceClass == null) {
            return null;
        }
        ServiceMetadata serviceInterfaceMetadata = null;
        for (final JavaType implementedType : serviceClass.getImplementsTypes()) {
            final ClassOrInterfaceTypeDetails potentialServiceInterfaceTypeDetails =
                    typeLocationService.getTypeDetails(implementedType);
            if (potentialServiceInterfaceTypeDetails != null) {
                final LogicalPath path = PhysicalTypeIdentifier.getPath(
                        potentialServiceInterfaceTypeDetails.getDeclaredByMetadataId());
                final String implementedTypeId = ServiceMetadata
                        .createIdentifier(implementedType, path);
                if ((serviceInterfaceMetadata = (ServiceMetadata) metadataService
                        .get(implementedTypeId)) != null) {
                    // Found the metadata for the service interface
                    break;
                }
            }
        }
        if (serviceInterfaceMetadata == null || !serviceInterfaceMetadata.isValid()) {
            return null;
        }

        // Register this provider for changes to the service interface // TODO
        // move this down in case we return null early below?
        metadataDependencyRegistry.registerDependency(serviceInterfaceMetadata
                .getId(), metadataIdentificationString);

        final ServiceAnnotationValues serviceAnnotationValues =
                serviceInterfaceMetadata.getServiceAnnotationValues();
        final JavaType[] domainTypes = serviceAnnotationValues
                .getDomainTypes();

        /*
         * For each domain type, collect (1) the plural and (2) the parent
         * property field.
         */
        final Map<JavaType, String> domainTypePlurals = new HashMap<JavaType, String>();
        final Map<JavaType, FieldMetadata> domainTypeParentFields = new HashMap<JavaType, FieldMetadata>();
        final Map<JavaType, JavaType> domainTypeParentRepos = new HashMap<JavaType, JavaType>();
        final Map<JavaType, FieldMetadata> domainTypeToIdTypeMap = new HashMap<JavaType, FieldMetadata>();
        for (final JavaType domainType : domainTypes) {
            final List<FieldMetadata> idFields = persistenceMemberLocator
                    .getIdentifierFields(domainType);
            if (idFields.size() != 1) {
                // The ID field metadata is either unavailable or not stable yet
                return null;
            }
            final FieldMetadata idField = idFields.get(0);
            domainTypeToIdTypeMap.put(domainType, idField);

            // Collect the plural for this domain type
            final ClassOrInterfaceTypeDetails domainTypeDetails =
                    typeLocationService.getTypeDetails(domainType);
            if (domainTypeDetails == null) {
                return null;
            }
            final LogicalPath path = PhysicalTypeIdentifier.getPath(
                    domainTypeDetails.getDeclaredByMetadataId());
            final String pluralId = PluralMetadata.createIdentifier(
                    domainType, path);
            final PluralMetadata pluralMetadata =
                    (PluralMetadata) metadataService.get(pluralId);
            if (pluralMetadata == null) {
                return null;
            }
            domainTypePlurals.put(domainType, pluralMetadata.getPlural());

            final FieldMetadata parentField = requestFactoryTypeService
                    .getParentField(domainTypeDetails);
            domainTypeParentFields.put(domainType, parentField);

            if (parentField != null) {
                final ClassOrInterfaceTypeDetails parentRepoDetails;
                if (domainTypeDetails.getAnnotation(ROO_MONGO_ENTITY) != null) {
                    parentRepoDetails = repositoryMongoLocator.getRepositories(parentField.getFieldType()).iterator().next();
                } else {
                    parentRepoDetails = repositoryJpaLocator.getRepositories(parentField.getFieldType()).iterator().next();
                }
                domainTypeParentRepos.put(domainType, parentRepoDetails.getType());
            }

            // Maintain a list of entities that are being handled by this layer
            managedEntityTypes.put(domainType, metadataIdentificationString);

            // Register this provider for changes to the domain type or its
            // plural
            metadataDependencyRegistry.registerDependency(domainTypeDetails
                    .getDeclaredByMetadataId(), metadataIdentificationString);
            metadataDependencyRegistry.registerDependency(pluralId,
                    metadataIdentificationString);
        }
        final MemberDetails serviceClassDetails = memberDetailsScanner
                .getMemberDetails(getClass().getName(), serviceClass);
        return new ServiceImplMetadata(metadataIdentificationString,
                aspectName, governorPhysicalTypeMetadata, serviceClassDetails,
                serviceAnnotationValues, domainTypeToIdTypeMap, domainTypeParentFields,
                domainTypeParentRepos, domainTypePlurals);
    }

    public String getProvidesType() {
        return ServiceImplMetadata.getMetadataIdentiferType();
    }
}


text:
YUI.add('pagedflickr-binder-index', function (Y, NAME) {
    "use strict";

/**
 * The pagedflickr-binder-index module.
 *
 * @module pagedflickr-binder-index
 */

    /**
     * Constructor for the Binder class.
     *
     * @param mojitProxy {Object} The proxy to allow the binder to interact
     *        with its owning mojit.
     *
     * @class Binder
     * @constructor
     */
    Y.namespace('mojito.binders')[NAME] = {

        /**
         * Binder initialization method, invoked after all binders on the page
         * have been constructed.
         */
        init: function (mojitProxy) {
            this.mojitProxy = mojitProxy;
        },

        /**
         * The binder method, invoked to allow the mojit to attach DOM event
         * handlers.
         *
         * @param node {Node} The DOM node to which this mojit is attached.
         */
        bind: function (node) {
            node.all('.pic a').on('click', function (evt) {
                var url = evt.currentTarget.get('href'),
                    matches = url.match(/image\/(\d+)/),
                    imageID = matches[1];
                Y.log('on click ' + url, 'debug', NAME);
                if (imageID) {
                    evt.halt();

                    // Update our pagination links so when we round-trip back
                    // to the server, we persist the image choice.
                    node.all('#paginate a').each(function (pageLink) {
                        var pageUrl = pageLink.get('href');
                        pageLink.set('href', pageUrl.replace(/\/image\/\d+/, '/image/' + imageID));
                    });

                    Y.log('broadcast flickr-image-chosen ' + imageID, 'debug', NAME);
                    this.mojitProxy.broadcast('flickr-image-chosen', { id: imageID });
                }
            }, this);
        }

    };

}, '0.0.1', {requires: ['node', 'mojito-client']});


text:
<?php namespace Kurenai\Contracts;

interface Document
{
    /**
     * Set the document content in Markdown format.
     *
     * @param  string $content
     *
     * @return \Kurenai\Document
     */
    public function setContent($content);

    /**
     * Get the document content in Markdown format.
     *
     * @return string
     */
    public function getContent();

    /**
     * Get the document content in HTML format.
     *
     * @return string
     */
    public function getHtmlContent();

    /**
     * Set the document metadata using an array.
     *
     * @param  array $metadata
     *
     * @return \Kurenai\Document
     */
    public function set(array $metadata);

    /**
     * Add a piece of metadata to the document.
     *
     * @param  string $key
     * @param  mixed $value
     *
     * @return \Kurenai\Document
     */
    public function add($key, $value);

    /**
     * Get metadata from the document.
     *
     * @param  string $key
     *
     * @return mixed
     */
    public function get($key = null);
}


text:
MerelCoin Core version 0.13.3 is now available from:

  <https://download.merelcoin.org/merelcoin-0.13.3/>

This is a new minor version release, including new features, various bugfixes and performance improvements.
It is recommended to upgrade to this version.

Please report bugs using the issue tracker at github:

  <https://github.com/merelcoin-project/merelcoin/issues>

Compatibility
==============

Microsoft ended support for Windows XP on [April 8th, 2014](https://www.microsoft.com/en-us/WindowsForBusiness/end-of-xp-support),
an OS initially released in 2001. This means that not even critical security
updates will be released anymore. Without security updates, using a merelcoin
wallet on a XP machine is irresponsible at least.

In addition to that, with 0.12.x there have been varied reports of Bitcoin Core
randomly crashing on Windows XP. It is [not clear](https://github.com/bitcoin/bitcoin/issues/7681#issuecomment-217439891)
what the source of these crashes is, but it is likely that upstream
libraries such as Qt are no longer being tested on XP.

We do not have time nor resources to provide support for an OS that is
end-of-life. From 0.13.0 on, Windows XP is no longer supported. Users are
suggested to upgrade to a newer version of Windows, or install an alternative OS
that is supported.

No attempt is made to prevent installing or running the software on Windows XP,
you can still do so at your own risk, but do not expect it to work: do not
report issues about Windows XP to the issue tracker.

From 0.13.1 onwards OS X 10.7 is no longer supported. 0.13.0 was intended to work on 10.7+,
but severe issues with the libc++ version on 10.7.x keep it from running reliably.
0.13.1 now requires 10.8+, and will communicate that to 10.7 users, rather than crashing unexpectedly.

Notable changes
===============

New Multisig Address Prefix
---------------------------

MerelCoin Core now supports P2SH addresses beginning with M on mainnet and Q on testnet.
P2SH addresses beginning with 3 on mainnet and m or n on testnet will continue to be valid.
Old and new addresses can be used interchangeably.

miniupnp CVE-2017-8798
----------------------

Bundled miniupnpc was updated to 2.0.20170509. This fixes an integer signedness error (present in MiniUPnPc v1.4.20101221 through v2.0) that allows remote attackers (within the LAN) to cause a denial of service or possibly have unspecified other impact.

This only affects users that have explicitly enabled UPnP through the GUI setting or through the -upnp option, as since the last UPnP vulnerability (in MerelCoin Core 0.10.4) it has been disabled by default.

If you use this option, it is recommended to upgrade to this version as soon as possible.

Reset Testnet
-------------

Testnet3 has been deprecated and replaced with Testnet4. The server port has been changed to 19335 however the RPC port remains
the same (19332).

Testnet faucets can be located at:
- http://testnet.merelcointools.com
- http://testnet.thrasher.io

Developers who require the new testnet blockchain paramaters can find them [here](https://github.com/merelcoin-project/merelcoin/blob/0.13/src/chainparams.cpp#L214).

Credits
=======

Thanks to everyone who directly contributed to this release:

- [The Bitcoin Core Developers](/doc/release-notes)
- Adrian Gallagher
- Shaolin Fry
- Xinxi Wang
- Out0fmemory
- Erasmospunk
- Romanornr


text:
# 02 - Crear Versión Estática

> Este paso requiere que hayas completado los siguientes fundamentos:
> 1. [Render y Create Element](../fundamentos/01-render-y-create-element.md)
> 2. [Componentes](../fundamentos/02-componentes.md)
> 3. [JSX](../fundamentos/03-jsx.md)
> 6. [Listas](../fundamentos/06-listas.md)

Una vez que ya tenemos la división en componentes, podemos pasar a crear una implementación estática de nuestra aplicación. La idea es convertir el HTML que representa un estado estático de nuestra aplicación, en un árbol de componentes de React que se dibujan en base a `props`.

En esta etapa, vas a estar tipeando mucho, moviendo código y no tanto pensando, ya que es más bien mecánico el proceso. Una vez que descubras el mecanismo en los primeros 2 o 3 casos, los demás salen de igual forma y más rápido.

En el repo vas a encontrar el archivo `/src/inicio/index.js`. Este es el código que vas a estar modificando al hacer la aplicación.

En este archivo tenemos un gran componente `App` que encierra toda la UI de nuestra aplicación, escrita en JSX. Podemos ver también que hay un flag `showEmpty` para poder cambiar entre la versión estática del listado de artistas y el estado de "no se encontraron resultados". También hay una función disponible importada que se llama `getArtists` que permite obtener la misma información que se ve en el browser en forma de array, como si viniera de la API. Esto será util para dividir la aplicación en componentes e ir parametrizando el contenido en base al valor de un objeto de ese array.

Vamos a realizar algunos ejemplos, y luego deberás completar el resto por tu cuenta.

En primer lugar, como en el paso anterior dividimos en dos paneles la primera vez, vamos a hacer esa división en el código.

Creamos dos componentes, `ArtistsPanel` y `CollectionPanel`, donde el primero es el panel de la izquierda y el otro el de la derecha. Identificamos los `div`s con `className="leftPanel"` y con `className="rightFixedPanel"`, y esos los dejamos en `App` como los "placeholders" de los paneles. Todo el contenido interno de cada uno de esos divs, lo movemos a los componentes:

```jsx
function ArtistsPanel() {
  return (
    <div>
      <form className="searchForm">
        {/* ... */}
      </form>
      <div className="artistsList">
        {/* ... */}
      </div>
      {/* ... */}
    </div>
  )
}

function CollectionsPanel() {
  return (
    <div>
      <h2 className="myArtistsTitle">
        Mis Artistas (2)
      </h2>
      <ul className="myArtistsList">
        {/* ... */}
      </ul>
      {/* ... */}
    </div>
  )
}
```

Y ahora modificamos el componente `App` para que use a esos componentes que creamos:

```jsx
class App extends Component {
  if (showEmpty) {
    // ...esta parte la ignoramos por ahora.
  }

  return (
    <div>
      <div className="leftPanel">
        <ArtistsPanel />
      </div>
      <div className="rightFixedPanel">
        <CollectionsPanel />
      </div>
    </div>
  )
}
```

Ya nuestro componente `App` dejo de ser ese componente gigante que teníamos al principio, lo dividimos en dos componentes.

Ahora seguimos dividiendo como lo hicimos en el paso 1, nos enfocamos en el `ArtistsPanel`, y vamos a dividir en otros dos componentes, el formulario de búsqueda, y el listado de artistas. En este caso, como vamos a utilizar la información de los artistas, es útil empezar a parametrizar los componentes y obtener el listado de artistas con `getArtists` y pasar el listado al componente como `props`. Luego parametrizaremos los items:

```jsx
function SearchInput() {
  return (
    <form className="searchForm">
      <input type="text" className="searchInput" value="beatles" />
      <button type="submit" className="searchButtonLayout searchButton">
        <svg viewBox="0 0 27 28" xmlns="http://www.w3.org/2000/svg">
          <title>Buscar</title>
          <path
            d="M18.387 16.623C19.995 15.076 21 12.907 21 10.5 21 5.806 17.195 2 12.5 2 7.806 2 4 5.806 4 10.5S7.806 19 12.5 19c1.927 0 3.7-.65 5.125-1.73l4.4 5.153.76-.65-4.398-5.15zM12.5 18C8.364 18 5 14.636 5 10.5S8.364 3 12.5 3 20 6.364 20 10.5 16.636 18 12.5 18z"
            fill="currentColor"
            fillRule="evenodd"
          />
        </svg>
      </button>
    </form>
  )
}

function ArtistsList(props) {
  const artists = props.artists; // Por ahora los dejamos aquí, luego parametrizaremos.
  return (
    <div className="artistsList">
        <div className="artistsListItem">
          {/* ... */}
        </div>
        <div className="artistsListItem">
          {/* ... */}
        </div>
        {/* ... */}
    </div>
  )
}
```

Reemplazamos el contenido en `ArtistsPanel`, obteniendo los artistas con `getArtists` y pasandoselos a `ArtistsList` como `prop`:

```jsx
function ArtistsPanel() {
  const artists = getArtists();

  return (
    <div>
      <SearchInput />
      <ArtistsList artists={artists} />
    </div>

  )
}
```

Seguimos partiendo en componentes, y nos enfocamos en el componente `ArtistsList`. Ya recibimos la prop `artists`, en anticipación a que este componente dibujará todos los artistas de la lista. También identificamos en el JSX de `ArtistsList` que se repite el fragmento de UI que representa a un artista, con distintos valores para cada artista. Podemos parametrizar esto moviendo esa estructura a su propio componente, `Artist`, y le pasamos cada uno de los artistas de la lista como prop.

```jsx
function Artist(props) {
  return (
    <div className="artist">
      <div
        className="artistImage"
        style={{
          width: 200,
          height: 200,
          borderRadius: 200,
          backgroundImage:
            `url('${props.artist.images[0].url}')`
        }}
      />
      <span className="artistName">{props.artist.name}</span>
      {/* ... */}
    </div>
  )
}

function ArtistsList(props) {
  return (
    <div className="artistsList">
      {props.artists.map((artist) => (
        <div className="artistsListItem">
          <Artist artist={artist} />
        </div>
      ))}
    </div>
  )
}
```

Podemos ver como vamos reduciendo el código final y vamos reusando estructuras con componentes.

Si te aparece un error en la consola del navegador indicando que te falta agregar la `key` en un componente, probablemente necesites asignarlo en este paso, donde iteramos por la lista de artistas y creamos elementos `div` para cada uno. Esos `div` necesitan una `key`, [como vimos en los fundamentos](../fundamentos/06-listas.md).

También no olvides guardar una lista de artistas seleccionados, de forma que puedas asignar la clase `isSelected` al `div` de `className="artist"` dependiendo si el artista está seleccionado o no. Por ahora no tenemos el mecanismo de seleccionar artistas, pero podemos recibir una `prop` en el componente `Artist` que indique si el artista esta seleccionado o no, y en base a eso poner o no esa clase. Luego en `ArtistsPanel`, donde obtuvimos la lista de artistas a partir de `getArtists`, podemos crear una lista de artistas seleccionados y propagarla por los componentes via `props` hasta el componente `Artist`:

```jsx
function ArtistsPanel() {
  const artists = getArtists();
  // Seleccionamos algunos artistas
  const selectedArtists = [artists[0], artists[2]];
  return (
    <div>
      <SearchInput />
      <ArtistsList
        artists={artists}
        selectedArtists={selectedArtists}
      />
    </div>

  )
}
function ArtistsList(props) {
  return (
    <div className="artistsList">
      {props.artists.map((artist) => (
        <div className="artistsListItem">
          <Artist
            artist={artist}
            selected={props.selectedArtists.some(a => a.id === artist.id)}
          />
        </div>
      ))}
    </div>
  )
}

function Artist(props) {
  return (
    <div
      className={`artist ${props.selected ? 'isSelected' : ''}`}
    >
      {/* ... */}
    </div>
  )
}
```

Bueno, hasta aquí con los ejemplos, ahora es tu turno de seguir! Recordá también componentizar el caso de "no hay resultados".

Cuando termines, [vamos a identificar el estado de nuestra aplicación](./03-identificar-estado-minimo.md).


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

title: Handbuch für die OS-Plattform von Amazon-Feuer
---

# Handbuch für die OS-Plattform von Amazon-Feuer

Diese Anleitung zeigt Ihre Entwicklungsumgebung SDK einrichten, Cordova apps für Amazon-Feuer-OS-Geräte wie der Kindle Fire HDX bereitstellen.

Finden Sie im folgenden detaillierte Plattform-spezifischen Informationen:

*   [Amazon Fire OS Konfiguration](config.html)
*   [Amazon Fire OS Webansichten für](webview.html)
*   [Amazon Fire OS Plugins](plugin.html)

## Anforderungen und Unterstützung

Die Entwicklung von Cordova apps für Amazon Fire OS erfordert das Android SDK und das Amazon-WebView-SDK. Überprüfen Sie die Anforderungen für diese SDKs an den Verbindungen unten:

*   [Android SDK-System][1]

*   [Amazon WebView SDK][2]

 [1]: http://developer.android.com/sdk/
 [2]: https://developer.amazon.com/sdk/fire/IntegratingAWV.html#installawv

## Installation

### Android SDK

Installieren Sie das Android SDK von [developer.android.com/sdk][1]. Sie können mit einer Wahl, wo das SDK installieren vorgelegt werden sonst die heruntergeladenen verschieben `adt-bundle` Baum, wo Sie Entwicklungstools zu speichern.

Für Cordova Kommandozeilen-Tools arbeiten, müssen Sie das SDK enthalten `tools` und `platform-tools` Verzeichnisse in Ihrer PATH-Umgebung.

Auf Mac, Linux oder andere Unix-ähnliche Plattformen, können Sie einen Text-Editor zum Erstellen oder ändern die `~/.bash_profile` -Datei eine Zeile wie die folgende, je nachdem, wo das SDK installiert:

    Export PATH = ${PATH}: / Entwicklung/Adt-Bundle/Sdk/Plattform-Tools: / Entwicklung/Adt-Bundle/Sdk/Tools

Dies macht die SDK-Tools im neu eröffneten terminal-Fenster verfügbar. Sonst laufen Sie hier, um sie in der aktuellen Sitzung zur Verfügung stellen:

    $ Quelle ~/.bash_profile

Die PATH-Umgebung unter Windows 7 zu ändern:

*   Im Menü " **Start** " in der unteren linken Ecke des Desktops mit der rechten Maustaste auf **Computer**, klicken, **Eigenschaften**.

*   Klicken Sie in der Spalte auf der linken Seite auf **Erweiterte Systemeinstellungen** .

*   Drücken Sie im daraufhin angezeigten Dialogfeld **Umgebungsvariablen**.

*   Wählen Sie die **PATH** -Variable und klicken Sie **Bearbeiten**.

*   Fügen Sie Folgendes in den Pfad basierend auf dem Sie das SDK, zum Beispiel installiert:

        ;C:\Development\adt-bundle\sdk\platform-Tools;C:\Development\adt-bundle\sdk\tools

*   Speichern Sie den Wert und schließen Sie beide Dialogfelder zu.

Sie müssen möglicherweise auch Java und Ant öffnen eine Eingabeaufforderung und geben aktivieren `java` , und geben Sie auch `ant` . Hängen Sie an den Pfad, welcher nicht ausgeführt:

    ;%JAVA_HOME%\bin;%ANT_HOME%\bin

### Amazon WebView SDK

Laden Sie das Amazon WebView SDK aus dem [Amazon-Entwicklerportal][2].

*   Erstellen einer `libs/` Ordner im `~/.cordova/lib/amazon-fireos/cordova/3.1.0/` Ordner.
*   Fügen Sie die `awv_interface.jar` aus dem heruntergeladenen SDK zu`~/.cordova/lib/amazon-fireos/cordova/3.1.0/libs/`

## Öffnen Sie ein Projekt im SDK

Verwendung der `cordova` Utility für ein neues Projekt, wie in der Cordova The Command-Line Interface beschrieben einrichten. Zum Beispiel in einem Quellcode-Verzeichnis:

    $ cordova create hello com.example.hello "HelloWorld"
    $ cd hello
    $ cordova platform add amazon-fireos
    $ cordova build

Einmal erstellt, wird hier das SDK zu verwenden, um es zu ändern:

*   Starten Sie die **Eclipse** -Anwendung.

*   Wählen Sie **Neues Projekt** .

*   Wählen Sie **Android Projekt aus vorhandenem Code** aus dem daraufhin angezeigten Dialogfeld, und klicken Sie auf **weiter**: ![][3]

*   Navigieren Sie zu `hello` , oder welches Verzeichnis Sie für das Projekt erstellt, dann auf die `platforms/amazon-fireos` Unterverzeichnis.

*   Drücken Sie **Fertig stellen**.

 [3]: {{ site.baseurl }}/static/img/guide/platforms//eclipse_new_project.png

Sobald das Eclipse-Fenster wird geöffnet, erscheint ein rotes **X** auf ungelöste Probleme hinweisen. Wenn ja, gehen Sie zusätzlichen folgendermaßen:

*   Rechtsklick auf das Projektverzeichnis.

*   Wählen Sie in den daraus resultierenden **Eigenschaften** im Navigationsbereich des **Android** .

*   Erstellen Sie Ziel für das Projekt zu, wählen Sie die höchste Android API-Ebene, die Sie installiert haben.

*   Klicken Sie auf **OK**.

*   Wählen Sie im Menü **Projekt** **Clean** . Dies sollten alle Fehler im Projekt korrigieren.

## Bereitstellung auf Gerät

Um eine app direkt auf das Gerät zu drücken, stellen Sie sicher, dass USB debugging auf dem Gerät wie beschrieben auf der [Android Developer-Website][4]aktiviert ist, und verwenden Sie einen Mini-USB-Kabel zu, um es an Ihr System anschließen.

 [4]: http://developer.android.com/tools/device.html

Drücken Sie die app auf das Gerät von der Befehlszeile aus:

    $ cordova run amazon-fireos

Abwechselnd innerhalb von Eclipse, Maustaste auf das Projekt, und wählen Sie **Ausführen als → Android-Anwendung**.

**Hinweis**: derzeit über einen Emulator testen wird nicht unterstützt für Amazon WebView-apps basierte.


text:
module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-import'),
    require('tailwindcss'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    })
  ]
}


text:
from jawaf.server import get_jawaf
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def _address_string(addr):
    """Convenience method to treat a given address field as a string or tuple/list
    :param addr: String or List/Tuple. Single address or addresses."""
    if isinstance(addr, str):
        return addr
    return ','.join(addr)

async def send_mail(
    subject, message, from_address, to, cc=None, bcc=None, html_message=None
):
    """Send mail using async smtp lib.
    :param subject: String. Subject.
    :param message: String. Message.
    :param from_address: String. From address.
    :param to: String or List/Tuple. To address.
    :param cc: String or List/Tuple. Email CC.
    :param bcc: String or List/Tuple. Email BCC.
    :param html_message: String. HTML Message (will send multipart message).
    """
    if html_message:
        msg = MIMEMultipart('alternative')
        msg.attach(MIMEText(message, 'plain'))
        msg.attach(MIMEText(html_message, 'html'))
    else:
        msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = from_address
    msg['To'] = _address_string(to)
    if cc:
        msg['Cc'] = _address_string(cc)
    recipients = []
    for address in [to, cc, bcc]:
        if isinstance(address, str):
            address = [address]
        if address:
            recipients.extend(address)
    await get_jawaf().get_smtp().sendmail(from_address, recipients, msg.as_string())


text:
package org.ms2ms.mzjava;

import com.google.common.collect.Multimap;
import org.expasy.mzjava.proteomics.io.ms.ident.MaxQuantPsmReader;
import org.expasy.mzjava.proteomics.mol.modification.ModificationResolver;
import org.expasy.mzjava.proteomics.ms.ident.PeptideMatch;
import org.expasy.mzjava.proteomics.ms.ident.SpectrumIdentifier;
import org.ms2ms.data.ms.MaxQuant;
import org.ms2ms.data.ms.PSM;
import org.ms2ms.math.Stats;
import org.ms2ms.r.Dataframe;
import org.ms2ms.r.Var;
import org.ms2ms.utils.IOs;
import org.ms2ms.utils.Strs;
import org.ms2ms.utils.TabFile;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by yuw on 10/28/2015.
 */
public class MaxQuantReader extends MaxQuantPsmReader
{
  public MaxQuantReader()                                 { super(); }
  public MaxQuantReader(ModificationResolver modResolver) { super(modResolver); }

  @Override
  protected SpectrumIdentifier getSpectrumId(ResultSet results) throws SQLException
  {
    SpectrumIdentifier identifier = super.getSpectrumId(results);

    try
    {
      identifier.setPrecursorIntensity(Stats.toDouble(Strs.split(results.getString("Intensities"), ';')[0]));
      String[] scans = Strs.split(identifier.getSpectrum(), '.');
      identifier.setName(scans[0]+"#"+scans[1]);
      identifier.setSpectrumFile(scans[0]);
    }
    catch (Exception e) {}

    return identifier;
  }
  @Override
  protected void setValues(PeptideMatch peptideMatch, ResultSet results) throws SQLException
  {
    // set the attributes
    try { peptideMatch.setMassDiff(results.getDouble("Mass Error [ppm]") * results.getDouble("Mass")*1E-6); } catch (Exception e) {}
    try { peptideMatch.setTotalNumIons(         results.getInt("Number of Matches"));     } catch (Exception e) {}
    try { peptideMatch.addScore("Score",        results.getDouble("Score"));              } catch (Exception e) {}
    try { peptideMatch.addScore("dScore",       results.getDouble("Delta score"));        } catch (Exception e) {}
    try { peptideMatch.addScore("PEP",          results.getDouble("PEP"));                } catch (Exception e) {}
    try { peptideMatch.addScore("IntCoverage",  results.getDouble("Intensity coverage")); } catch (Exception e) {}
    try { peptideMatch.addScore("PeakCoverage", results.getDouble("Peak coverage"));      } catch (Exception e) {}
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fieldiana, Bot. 21: 13 (1989)

#### Original name
Omphalina infumata Singer

### Remarks
null


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	Address*: <input type="text" id="InServerAddress" name="server[address]" />
	Port*: <input type="text" id="InServerPort" name="server[port]" />
    Name: <input type="text" id="InMasterName" name="master[name]" />

	<button id="ButtonCreateMaster">Create master</button>

* required

Name

Client port

Url

Clients

Status

Weinre

    <button id="ButtonReconnectMaster">Reconnect master</button>
    <button id="ButtonDisconnectMaster">Disconnect master</button>
    <button id="ButtonCloseMaster">Close Master</button>


text:
package org.chaplib;

import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.util.EntityUtils;

public class HttpResource {

    private URI uri;
    private HttpClient httpClient;

    public HttpResource(URI uri, HttpClient httpClient) {
        this.uri = uri;
        this.httpClient = httpClient;
    }

    public <T> T value(ContentParser<T> parser) {
        HttpResponse resp = execute(new HttpGet(uri));
        HttpEntity entity = resp.getEntity();
        if (entity == null) return null;
        try {
            return parser.parse(entity);
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private HttpResponse execute(HttpUriRequest req) {
        try {
            req.setHeader("User-Agent", "chaplib/0.1.0 Apache-HttpClient/4.1.3");
            return httpClient.execute(req);
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void delete() {
        consumeBodyOf(execute(new HttpDelete(uri)));
    }

    private void consumeBodyOf(HttpResponse resp) {
        HttpEntity entity = resp.getEntity();
        if (entity == null) return;
        try {
            EntityUtils.consume(entity);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void replaceOrCreate(HttpEntity entity) {
        HttpPut req = new HttpPut(uri);
        req.setEntity(entity);
        consumeBodyOf(execute(req));
    }

    public void post(HttpEntity entity) {
        HttpPost req = new HttpPost(uri);
        req.setEntity(entity);
        consumeBodyOf(execute(req));
    }

}


text:
<?php

namespace Cerad\Bundle\UserBundle\Event;

use Cerad\Bundle\UserBundle\Model\UserInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpFoundation\Request;

class UserEvent extends Event
{
    private $user;
    private $request;

    public function __construct(UserInterface $user, Request $request)
    {
        $this->user    = $user;
        $this->request = $request;
    }

    /**
     * @return UserInterface
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }
}


text:
#pragma once

#include <queue>
#include "const_define.h"

using namespace std;

const uint32_t MAX_QUEUE_COUNT = 1000000;

template<typename T>
class SafeQueue {
private:
    queue<T> mQueue;
    bgcc::Mutex mLocker;

    bgcc::Semaphore mFullSemaphore;
    bgcc::Semaphore mEmptySemaphore;

    pthread_mutex_t     _mutex;
    pthread_cond_t      _cond;
    uint32_t            _waitings;
public:
    SafeQueue();
    ~SafeQueue();
    bool Empty();
    typename queue<T>::size_type Size();
    void BlockFront(T& value);
    bool Pop(T& value);
    void BlockPop();
    void BlockPop(T& value);
    void HarfBlockPop(T& value);
    bool UnBlockPop(T& value, int32_t timeout);
    void Push(const T& value);
    void BlockPush(const T& value);
    void HarfBlockPush(const T& value);
};

template<class T>
SafeQueue<T>::SafeQueue()
    : mFullSemaphore(0)
    , mEmptySemaphore(MAX_QUEUE_COUNT)
    , _waitings(0)
{
    pthread_mutex_init(&this->_mutex, NULL);
    pthread_cond_init(&this->_cond, NULL);
}

template<class T>
SafeQueue<T>::~SafeQueue()
{
    pthread_mutex_destroy(&_mutex);
    pthread_cond_destroy(&_cond);
}

template<class T>
bool SafeQueue<T>::Empty() {
    SingleLocker s(&mLocker);
    return mQueue.empty();
}

template<class T>
typename queue<T>::size_type SafeQueue<T>::Size() {
    SingleLocker s(&mLocker);
    return mQueue.size();
}

template<class T>
void SafeQueue<T>::BlockFront(T& value) {
    mFullSemaphore.wait();
    mLocker.lock();
    value = mQueue.front();
    mLocker.unlock();
    mFullSemaphore.signal();
}

template<class T>
bool SafeQueue<T>::Pop(T& value) {
    SingleLocker s(&mLocker);

    if (mQueue.empty()) {
        return false;
    }

    value = mQueue.front();
    mQueue.pop();
    return true;
}

template<class T>
void SafeQueue<T>::BlockPop() {
    mFullSemaphore.wait();
    mLocker.lock();
    mQueue.pop();
    mLocker.unlock();
    mEmptySemaphore.signal();
}

template<class T>
void SafeQueue<T>::BlockPop(T& value) {
    mFullSemaphore.wait();
    mLocker.lock();
    value = mQueue.front();
    mQueue.pop();
    mLocker.unlock();
    mEmptySemaphore.signal();
}

template<class T>
void SafeQueue<T>::HarfBlockPop(T& value) {
    mFullSemaphore.wait();
    mLocker.lock();
    value = mQueue.front();
    mQueue.pop();
    mLocker.unlock();
}

template<class T>
bool SafeQueue<T>::UnBlockPop(T& value, int32_t timeout) {
    pthread_mutex_lock(&_mutex);
    mLocker.lock();
    ++_waitings;

        if (mQueue.empty()) {
            if (timeout > 0) {
                struct timespec abstime;
                clock_gettime(CLOCK_REALTIME, &abstime);
                abstime.tv_sec += timeout / 1000;
                abstime.tv_nsec += (timeout % 1000) * 1000000;
                mLocker.unlock();
                pthread_cond_timedwait(&_cond, &_mutex, &abstime);
                mLocker.lock();
            }
        }

        if (mQueue.empty()) {
            --_waitings;
            pthread_mutex_unlock(&_mutex);
            mLocker.unlock();
            return false;
        }

    value = mQueue.front();
    mQueue.pop();
    --_waitings;
    mLocker.unlock();
    pthread_mutex_unlock(&_mutex);
    return true;
}

template<class T>
void SafeQueue<T>::Push(const T& value) {
    SingleLocker s(&mLocker);

    if (mQueue.size() >= MAX_QUEUE_COUNT) { //maybe overflow, need log out
        mQueue.pop();
    }

    mQueue.push(value);

    if (_waitings > 0) {
        pthread_cond_signal(&_cond);
    }
}

template<class T>
void SafeQueue<T>::BlockPush(const T& value) {
    mEmptySemaphore.wait();
    mLocker.lock();
    mQueue.push(value);
    mLocker.unlock();
    mFullSemaphore.signal();
    if (_waitings > 0) {
        pthread_cond_signal(&_cond);
    }
}

template<class T>
void SafeQueue<T>::HarfBlockPush(const T& value) {
    bool isFull = false;
    mLocker.lock();

    if (mQueue.size() >= MAX_QUEUE_COUNT) { //maybe overflow, need log out
        isFull = true;
        mQueue.pop();
    }

    mQueue.push(value);
    mLocker.unlock();

    if (!isFull) {
        mFullSemaphore.signal();
    }

    if (_waitings > 0) {
        pthread_cond_signal(&_cond);
    }
}


text:
var app = angular.module("userFactoryModule", []);

app.factory('User', ['$http', function($http) {

    var urlBase = '/api/users';
    var User = {};

    User.checkEmail = function(email) {
        return $http.get(urlBase + '/email/check/' + email);
    }

    User.saveUser = function(user) {
        // default post header
        $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        // send user data
        return $http({
            method: 'POST',
            url: urlBase + '/save',
            data: $.param({
                firstName: user.firstName,
                lastName: user.lastName,
                email: user.email,
                password: user.password,
                role: user.role
            }),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        });
    }

    User.getUser = function() {
        $http.defaults.headers.common['access-token'] = sessionStorage.getItem('token');
        return $http.get('/api/user');
    }

    return User;
}]);


text:
#include <packml_msgs/Status.h>

namespace packml_msgs
{

bool isStandardState(int state)
{

  switch (state)  {
  case State::ABORTED:
  case State::ABORTING:
  case State::CLEARING:
  case State::COMPLETE:
  case State::COMPLETING:
  case State::EXECUTE:
  case State::HELD:
  case State::HOLDING:
  case State::IDLE:
  case State::OFF:
  case State::RESETTING:
  case State::STARTING:
  case State::STOPPED:
  case State::STOPPING:
  case State::SUSPENDED:
  case State::SUSPENDING:
  case State::UNHOLDING:
  case State::UNSUSPENDING:
    return true;
    break;
  default:
    return false;
    break;
  }
}

Status initStatus(std::string node_name)
{
  Status status;
  status.header.frame_id = node_name;
  status.state.val = packml_msgs::State::UNDEFINED;
  status.sub_state = packml_msgs::State::UNDEFINED;
  status.mode.val = packml_msgs::Mode::UNDEFINED;
  //TODO: need better definition on errors
  status.error = 0;
  status.sub_error = 0;
  return status;
}

} //namespace packml_msgs

#ifndef UTILS_H
#define UTILS_H

#endif // UTILS_H


text:
package lt.baraksoft.summersystem.dao.generic;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.SynchronizationType;

import lt.baraksoft.summersystem.model.IEntity;

/**
 * Created by Zygimantas on 2016.03.18.
 */

// Butu neblogai kazkoki equalsAndHashProvideri extendint

@Stateless
public class GenericDao<T extends IEntity<K>, K extends Serializable> implements IGenericDao<T, K> {

	@PersistenceContext(unitName = "summerhousePU")
	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	private final Class<T> entityClass;

	@SuppressWarnings("unchecked")
	public GenericDao() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
		this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
	}

	@Override
	public void save(T entity) {
		if (entity == null) {
			throw new IllegalArgumentException("Parameter entity is required");
		}
		entityManager.persist(entity);
	}

	@Override
	public void remove(T entity) {
		entityManager.remove(entityManager.merge(entity));
	}

	// TODO transactional readonly true
	@Override
	public T get(K id) {
		if (id == null) {
			throw new IllegalArgumentException("Parameter id is required");
		}
		return entityManager.find(entityClass, id);
	}

	@Override
	public T update(T entity) {
		if (entity == null) {
			throw new IllegalArgumentException("Parameter entity is required");
		} else if (entity.getId() == null) {
			save(entity);
			return entity;
		}
		return entityManager.merge(entity);
	}
}


text:
/*************/
/*  GLOBALS  */
/*************/
// Override the default timeout interval for Jasmine
jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000;

// Get a reference to a random demo Firebase
var demoFirebaseUrl = 'https://' + generateRandomString() + '.firebaseio-demo.com';

// Define examples of valid and invalid parameters
var invalidFirebaseRefs = [null, undefined, NaN, true, false, [], 0, 5, "", "a", ["hi", 1]];
var validKeys = ["a", "loc1", "(e@Xi:4t>*E2)hc<5oa:1s6{B0d?u", Array(743).join("a")];
var invalidKeys = ["", true, false, null, undefined, {a: 1}, "loc.1", "loc$1", "[loc1", "loc1]", "loc#1", "loc/1", "a#i]$da[s", "te/nst", "te/rst", "te/u0000st", "te/u0015st", "te/007Fst", Array(800).join("a")];
var validLocations = [[0, 0], [-90, 180], [90, -180], [23, 74], [47.235124363, 127.2379654226]];
var invalidLocations = [[-91, 0], [91, 0], [0, 181], [0, -181], [[0, 0], 0], ["a", 0], [0, "a"], ["a", "a"], [NaN, 0], [0, NaN], [undefined, NaN], [null, 0], [null, null], [0, undefined], [undefined, undefined], "", "a", true, false, [], [1], {}, {a:1}, null, undefined, NaN];
var validGeohashes = ["4", "d62dtu", "000000000000"];
var invalidGeohashes = ["", "aaa", 1, true, false, [], [1], {}, {a:1}, null, undefined, NaN];
var validQueryCriterias = [{center: [0,0], radius: 1000}, {center: [1,-180], radius: 1.78}, {center: [22.22,-107.77], radius: 0}, {center: [0,0]}, {center: [1,-180]}, {center: [22.22,-107.77]}, {radius: 1000}, {radius: 1.78}, {radius: 0}];
var invalidQueryCriterias = [{}, {random: 100}, {center: [91,2], radius: 1000, random: "a"}, {center: [91,2], radius: 1000}, {center: [1,-181], radius: 1000}, {center: ["a",2], radius: 1000}, {center: [1,[1,2]], radius: 1000}, {center: [0,0], radius: -1}, {center: [null,2], radius: 1000}, {center: [1,undefined], radius: 1000}, {center: [NaN,0], radius: 1000}, {center: [1,2], radius: -10}, {center: [1,2], radius: "text"}, {center: [1,2], radius: [1,2]}, {center: [1,2], radius: null}, true, false, undefined, NaN, [], "a", 1];

// Create global variables to hold the Firebase and GeoFire variables
var firebaseRef, geoFire, geoQueries;

/**********************/
/*  HELPER FUNCTIONS  */
/**********************/
/* Helper function which runs before each Jasmine test has started */
function beforeEachHelper(done) {
  // Create a new firebase ref with a new context
  firebaseRef = new Firebase(demoFirebaseUrl, Firebase.Context());

  // Reset the Firebase
  firebaseRef.remove(function() {
    // Create a new firebase ref at a random node
    firebaseRef = firebaseRef.child(generateRandomString());

    // Create a new GeoFire
    geoFire = new GeoFire(firebaseRef);

    // Reset the GeoQueries
    geoQueries = [];

    done();
  });
}

/* Helper function which runs after each Jasmine test has completed */
function afterEachHelper(done) {
  // Cancel each outstanding GeoQuery
  geoQueries.forEach(function(geoQuery) {
    geoQuery.cancel();
  })

  // Wait for 50 milliseconds after each test to give enough time for old query events to expire
  wait(50).then(function() {
    done();
  });
}

/* Returns a random alphabetic string of variable length */
function generateRandomString() {
  var possibleCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  var numPossibleCharacters = possibleCharacters.length;

  var text = "";
  for (var i = 0; i < 10; i++) {
    text += possibleCharacters.charAt(Math.floor(Math.random() * numPossibleCharacters));
  }

  return text;
}

/* Returns the current data in the Firebase */
function getFirebaseData() {
  return new RSVP.Promise(function(resolve, reject) {
    firebaseRef.once("value", function(dataSnapshot) {
      resolve(dataSnapshot.exportVal());
    });
  });
};

/* Returns a promise which is fulfilled after the inputted number of milliseconds pass */
function wait(milliseconds) {
  return new RSVP.Promise(function(resolve, reject) {
    var timeout = window.setTimeout(function() {
      window.clearTimeout(timeout);
      resolve();
    }, milliseconds);
  });
};

/* Keeps track of all the current asynchronous tasks being run */
function Checklist(items, expect, done) {
  var eventsToComplete = items;

  /* Removes a task from the events list */
  this.x = function(item) {
    var index = eventsToComplete.indexOf(item);
    if (index === -1) {
      expect("Attempting to delete unexpected item '" + item + "' from Checklist").toBeFalsy();
    }
    else {
      eventsToComplete.splice(index, 1);
      if (this.isEmpty()) {
        done();
      }
    }
  };

  /* Returns the length of the events list */
  this.length = function() {
    return eventsToComplete.length;
  };

  /* Returns true if the events list is empty */
  this.isEmpty = function() {
    return (this.length() === 0);
  };
};

/* Common error handler for use in .catch() statements of promises. This will
 * cause the test to fail, outputting the details of the exception. Otherwise, tests
 * tend to fail due to the Jasmine ASYNC timeout and provide no details of what actually
 * went wrong.
 **/
function failTestOnCaughtError(error) {
  expect(error).toBeNull();
}


text:
<Record>
<Term>Language Development Disorders</Term>
<SemanticType>Mental or Behavioral Dysfunction</SemanticType>
<ParentTerm>Language Disorders</ParentTerm>
<ClassificationPath>Nervous System Diseases/Neurologic Manifestations/Neurobehavioral Manifestations/Communication Disorders/Language Disorders/Language Development Disorders</ClassificationPath>
<ClassificationPath>Pathological Conditions, Signs and Symptoms/Signs and Symptoms/Neurologic Manifestations/Neurobehavioral Manifestations/Communication Disorders/Language Disorders/Language Development Disorders</ClassificationPath>
<BroaderTerm>Neurobehavioral Manifestations</BroaderTerm>
<BroaderTerm>Neurologic Manifestations</BroaderTerm>
<BroaderTerm>Signs and Symptoms</BroaderTerm>
<BroaderTerm>Pathological Conditions, Signs and Symptoms</BroaderTerm>
<BroaderTerm>Language Disorders</BroaderTerm>
<BroaderTerm>Language Development Disorders</BroaderTerm>
<BroaderTerm>Nervous System Diseases</BroaderTerm>
<BroaderTerm>Communication Disorders</BroaderTerm>
<Synonym>Speech Delay</Synonym>
<Synonym>Developmental Language Disorder</Synonym>
<Synonym>Language Development Disorder</Synonym>
<Synonym>Language Delays</Synonym>
<Synonym>Semantic-Pragmatic Disorder</Synonym>
<Synonym>Developmental Language Disorders</Synonym>
<Synonym>Language Delay</Synonym>
<Synonym>Central Auditory Processing Disorder</Synonym>
<Synonym>Language Development Disorders</Synonym>
<Synonym>Semantic-Pragmatic Disorders</Synonym>
<Synonym>Speech Delays</Synonym>
<Synonym>Semantic Pragmatic Disorder</Synonym>
<Description>Conditions characterized by language abilities (comprehension and expression of speech and writing) that are below the expected level for a given age, generally in the absence of an intellectual impairment. These conditions may be associated with DEAFNESS; BRAIN DISEASES; MENTAL DISORDERS; or environmental factors.</Description>
<Source>MeSH</Source>
</Record>


text:
var imgurLimit = 0;

function KCScreenshot(){
	this.scale = ((ConfigManager.api_gameScale || 100) / 100);
	this.gamebox = {};
	this.canvas = {};
	this.context = {};
	this.domImg = {};
	this.base64img = "";
	this.playerIndex = "";
	this.screenshotFilename = "";
	this.format = (ConfigManager.ss_type=="JPG")
		?["jpeg", "jpg", "image/jpeg"]
		:["png", "png", "image/png"];
}

KCScreenshot.prototype.start = function(playerName, element){
	var self = this;
	this.playerName = playerName;
	this.gamebox = element;
	this.generateScreenshotFilename();

	// Initialize HTML5 Canvas
	this.canvas = document.createElement("canvas");
	this.canvas.width = 800 * this.scale;
	this.canvas.height = 480 * this.scale;
	this.context = this.canvas.getContext("2d");

	// Initialize Image Tag
	this.domImg = new Image();

	this.capture();
};

function chromeCapture(captureFormat, response){
	chrome.tabs.captureVisibleTab(null, {format: captureFormat, quality: 70}, response);
}

KCScreenshot.prototype.generateScreenshotFilename = function() {
  var d = new Date();
  curr_month = (d.getMonth()+1) + "";
  if (curr_month.length == 1) { curr_month = "0" + curr_month; }
  curr_date = d.getDate() + "";
  if (curr_date.length == 1) { curr_date = "0" + curr_date; }
  curr_hour = d.getHours() + "";
  if (curr_hour.length == 1) { curr_hour = "0" + curr_hour; }
  curr_min = d.getMinutes() + "";
  if (curr_min.length == 1) { curr_min = "0" + curr_min; }
  curr_second = d.getSeconds() + "";
  if (curr_second.length == 1) { curr_second = "0" + curr_second; }

  this.screenshotFilename = "["+this.playerName+"] "+d.getFullYear()+"-"+curr_month+"-"+curr_date+" "+curr_hour+"-"+curr_min+"-"+curr_second + " " + getRandomInt(10,99);
};

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

KCScreenshot.prototype.capture = function(){
	var self = this;

	// Start capturing
	chromeCapture(this.format[0], function(base64img){
		self.domImg.src = base64img;
		self.domImg.onload = self.crop();
	});
};

KCScreenshot.prototype.crop = function(){
	var self = this;

	// Get zoom factor
	chrome.tabs.getZoom(null, function(zoomFactor){
		// Get gamebox dimensions and position
		var params = {
			realWidth: 800 * zoomFactor * self.scale,
			realHeight: 480 * zoomFactor * self.scale,
			offTop: self.gamebox.offset().top * zoomFactor * self.scale,
			offLeft: self.gamebox.offset().left * zoomFactor * self.scale,
		};

		// Actual Cropping
		self.context.drawImage(
			self.domImg,
			params.offLeft,
			params.offTop,
			params.realWidth,
			params.realHeight,
			0,
			0,
			800 * self.scale,
			480 * self.scale
		);

		// Convert image to base64
		self.base64img = self.canvas.toDataURL(self.format[2]);

		// Call output function on what to do with the base64 image
		self.output();
	});
};

KCScreenshot.prototype.output = function(){
	switch(parseInt(ConfigManager.ss_mode, 10)){
		case 0: this.saveDownload(); break;
		case 1: this.saveImgur(); break;
		default: this.saveTab(); break;
	}
};

KCScreenshot.prototype.saveDownload = function(){
	chrome.downloads.setShelfEnabled(false);
	chrome.downloads.download({
		url: this.base64img,
		filename: ConfigManager.ss_directory+'/'+this.screenshotFilename+"."+this.format[1],
		conflictAction: "uniquify"
	}, function(downloadId){
		setTimeout(function(){
			chrome.downloads.setShelfEnabled(true);
		}, 1000);
	});

};

KCScreenshot.prototype.saveImgur = function(){
	var stampNow = Math.floor((new Date()).getTime()/1000);
	if(stampNow - imgurLimit > 10){
		imgurLimit = stampNow;
	}else{
		this.saveDownload();
		return false;
	}

	var self = this;
	$.ajax({
		url: 'https://api.imgur.com/3/credits',
		method: 'GET',
		headers: {
			Authorization: 'Client-ID 088cfe6034340b1',
			Accept: 'application/json'
		},
		success: function(response){
			if(response.data.UserRemaining>10 && response.data.ClientRemaining>100){
				$.ajax({
					url: 'https://api.imgur.com/3/image',
					method: 'POST',
					headers: {
						Authorization: 'Client-ID 088cfe6034340b1',
						Accept: 'application/json'
					},
					data: {
						image: self.base64img.substring(23),
						type: 'base64'
					},
					success: function(response){
						KC3Database.Screenshot(response.data.link);
					}
				});
			}else{
				self.saveDownload();
			}
		}
	});
};

KCScreenshot.prototype.saveTab = function(){
	window.open(this.base64img, "_blank");
};


text:
var gulp = require('gulp');

gulp.task('build', ['browserify', 'markup', 'scripts']);


text:
<?php

namespace Phpug\Exception;

class UnauthenticatedException extends \Exception
{
    protected $header = 'You have to be logged in';

    public function __construct($message = "", $code = 0, Exception $previous = null, $header = '')
    {
        parent::__construct($message, $code, $previous);
        if ($header) {
            $this->header = $header;
        }
    }
    public function getHttpStatusCode()
    {
        return 401;
    }

    public function getAdditionalHeaderFields()
    {
        return array('\Zend\Http\Header\WWWAuthenticate' => 'WWW-Authenticate: OAuth');
    }

    public function getHeader()
    {
        return $this->header;
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <title>Reviews - lawrencehlee.github.io</title>

  <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:300,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="/css/custom.css">
<link rel="stylesheet" href="/css/navbar.css">
<link rel="stylesheet" href="/css/footer.css">
<link rel="stylesheet" href="/css/responsive.css">

					lawrencehlee.github.io

					<s class="bar"></s>
					<s class="bar"></s>

						Home

						Blog

						Projects

						Reviews

Reviews

Coming soon!

      Powered by
      Hugo and
      Pure.
      © 2016 Lawrence H Lee. All rights reserved.


text:
set -exo pipefail

if [ $DB == 'postgres' ]
then
  sudo apt-get install postgresql-client -y
fi

crystal spec spec/integration/sam_test.cr &&
  # TODO: fix concurrency tests
  # crystal spec spec/integration/concurrency_test.cr -Dpreview_mt &&
  crystal spec spec/integration/micrate_test.cr


text:
package org.collectionspace.chain.csp.persistence.services.connection;

import org.apache.commons.httpclient.HttpMethod;

public interface Returned {
	public void setResponse(HttpMethod method,int status) throws Exception;
	public int getStatus();
}


text:
//
//  CLTStoryDetial.h
//
//  Created by CAI on 2015/4/24
//  Copyright (c) 2015年 CAI. All rights reserved.
//

/*
     故事详情
*/

#import "Mantle.h"

@interface CLTStoryDetial : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong)NSString *author;
@property (nonatomic, strong)NSString *content;
@property (nonatomic, strong)NSString *publishTime;
@property (nonatomic, strong)NSString *authorPhoto;
@property (nonatomic, strong)NSString *title;
@property (nonatomic, strong)NSString *cover;
@property (nonatomic, strong)NSString *storyId;

@end


text:
<?php

/**
 * @access protected
 * @author Judzhin Miles <info[woof-woof]msbios.com>
 */
namespace MSBios\ModelBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Class Comment
 * @package MSBios\ModelBundle\Entity
 * @ORM\Table(name="tut_t_comments")
 * @ORM\Entity
 */
class Comment extends Timestampable
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="author", type="string", length=100)
     * @Assert\NotBlank
     */
    private $authorName;

    /**
     * @var string
     *
     * @ORM\Column(name="message", type="text")
     * @Assert\NotBlank
     */
    private $message;

    /**
     * @var Post
     * @ORM\ManyToOne(targetEntity="MSBios\ModelBundle\Entity\Post", inversedBy="comments")
     * @ORM\JoinColumn(name="post_id", referencedColumnName="id", nullable=false)
     * @Assert\NotBlank
     */
    private $post;
    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set authorName
     *
     * @param string $authorName
     * @return Comment
     */
    public function setAuthorName($authorName)
    {
        $this->authorName = $authorName;

        return $this;
    }

    /**
     * Get authorName
     *
     * @return string
     */
    public function getAuthorName()
    {
        return $this->authorName;
    }

    /**
     * Set message
     *
     * @param string $message
     * @return Comment
     */
    public function setMessage($message)
    {
        $this->message = $message;

        return $this;
    }

    /**
     * Get message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Set Post
     *
     * @param Post $post
     * @return $this
     */
    public function setPost(Post $post)
    {
        $this->post = $post;

        return $this;
    }

    /**
     * Get Post
     *
     * @return Post
     */
    public function getPost()
    {
        return $this->post;
    }
}


text:
"""spatial lag of a variable
"""
__author__ = "Juan C. Duque, Alejandro Betancourt"
__credits__ = "Copyright (c) 2010-11 Juan C. Duque"
__license__ = "New BSD License"
__version__ = "1.0.0"
__maintainer__ = "RiSE Group"
__email__ = "contacto@rise-group.org"
__all__ = ['spatialLag']

import numpy

def spatialLag(data,w):
    """
    This method recives a dictionary of variables an
    return a copy of the dictionary with variables
    spatially lagged.

    :param data: data dictionary to be lagged
    :type data: dictionary
    :rtype: dictionary (Y dictionary with the lag of vars)
    """
    data = [data[x] for x in data]
    data = numpy.matrix(data)
    data = data.transpose()
    w = numpy.matrix(w)
    data = data*w
    data = data.transpose()
    y = {}
    for nd, d in enumerate(data):
        y[nd] = d.tolist()[0]
    return y