text:
from datetime import datetime
from functools import partial, lru_cache
from random import shuffle

from bs4 import BeautifulSoup
import bs4.element
from funcy import mapcat, merge

from parsedatetime import Calendar, Constants
import langid

from datextractor import TAGS_PATH
from datextractor.utils import prepare_date, check_reg_exp_datetime, SITE_CHECKERS, SITE_EXTRACTORS, \
    reg_exp_datetime, extract_time, loadyaml

__all__ = [
    'extract',
]

def _extract_date(tag: str, el: bs4.element.Tag, verbose: bool = False) -> list:
    result = []

    if len(el) > 300:
        return []

    # if verbose:
    #     print(el)

    if tag == 'meta' and el.has_attr('content'):
        result.append(el['content'])
    if tag == 'abbr' and all([el.has_attr('itemprop'), el.has_attr('title')]):
        result.append(el['title'])
    # if tag == 'time' and el.has_attr('datetime'):
    #     result.append(el['datetime'])

    _ = el.prettify()
    _ = BeautifulSoup(_, "lxml").getText()
    _ = _[:300]
    if _:
        result.append(_.lower().strip())
    #
    # if verbose:
    #     pprint.pprint(result)
    return result

def _check_sites(page: BeautifulSoup, verbose: bool = False):
    result = None
    for site, checker in SITE_CHECKERS.items():
        if verbose:
            print("Check of site '%s'..." % site)
        if checker(page):
            if verbose:
                print("Page is site - '%s'" % site)
            result = site
            break
    return result

def _extract_of_site(page: BeautifulSoup, site: str) -> datetime:
    assert site in SITE_EXTRACTORS, "Not found extractor for size '%s'" % site
    return SITE_EXTRACTORS[site](page)

def _extract_date_tags(page: BeautifulSoup, tags_file: str, verbose: bool = False):
    result = []
    _extract_func_date = partial(_extract_date, verbose=verbose)
    _tags = loadyaml(tags_file)
    for tag, tags_params in _tags.items():
        # if verbose:
        #     print("Processing tag - '%s'" % tag)
        result = merge(
            result,
            list(mapcat(
                partial(_extract_func_date, tag),
                mapcat(page.findAll,
                       [tag] * len(tags_params), tags_params))))
    return list(map(prepare_date, result))

def _create_datetime(day, time):
    if day is None:
        result = None
    else:
        result = datetime(
            day.year,
            day.month,
            day.day,
            time.hour if time is not None else 0,
            time.minute if time is not None else 0,
            time.second if time is not None else 0,
        )
    return result

def _extract_date_with_regex(elements):
    _date = None
    _day = None

    _dates = check_reg_exp_datetime(elements)
    if _dates:
        if '%Y %m %d %H %M' in _dates:
            _date = _dates['%Y %m %d %H %M']
        if '%Y %m %d' in _dates:
            _day = _dates['%Y %m %d']
    return _date, _day

@lru_cache(maxsize=10)
def get_parse_functions(language: str = 'en') -> list:
    if language == 'ru':
        language = 'ru_RU'
    _cal = Calendar(Constants(language))
    return [
        _cal.parseDateText,
        _cal.parse,
        _cal.parseDT,
    ]

def _get_date_info(key_minutes: str, date_line: str, verbose: bool = False) -> dict:
    funcs = get_parse_functions(langid.classify(date_line)[0])

    result = {}
    _ = extract_time(date_line)
    result[key_minutes] = _[0] if _ else None

    if verbose:
        print('')

    for fun in funcs:
        try:
            if verbose:
                print("Parse %s: %s" % (fun.__name__, fun(date_line)[0]))
            _ = fun(date_line)[0]
            _1 = datetime.now()

            if str(_) == _1.strftime("%Y-%m-%d %H:%M:%S"):
                continue
            if isinstance(_, datetime) and _.year > _1.year:
                continue

            result[fun.__name__] = _
        except AttributeError as e:
            # if verbose:
            #     print("Run '%s', error - %s" % (fun.__name__, e))
            pass
    return result

def _extract_day_time(data: list, key_minutes: str, funcs_names: list, verbose: bool = False):
    _time, _day = None, None
    for x in data:
        if all(func in x for func in funcs_names) and _day is None:

            if verbose:
                print("Day", x.get('parse'))

            _day = datetime(*x.get('parse')[:6])
        elif x.get(key_minutes, None) is not None and _time is None:
            if verbose:
                print("Time", x.get(key_minutes))
            _time = x.get(key_minutes)

    return _day, _time

def extract(text: str, verbose: bool = False) -> datetime:
    langid.set_languages(['en', 'ru'])
    page = BeautifulSoup(text, "lxml")

    if verbose:
        print("Run site checkers...")
    _ = _check_sites(page, verbose)
    _date = _extract_of_site(page, _) if _ is not None else None
    if _date is not None:
        return _date

    if verbose:
        print("Extract tags from page")
        print('=' * 20)
        print(' ' * 20)
        print(' ' * 20)

    _date_lines = _extract_date_tags(page, TAGS_PATH, verbose)
    shuffle(_date_lines)

    if verbose:
        print(_date_lines)

    _date, _day = _extract_date_with_regex(_date_lines)
    if _date is not None:
        return _date

    for x in _date_lines:
        _date = reg_exp_datetime(x)
        if _date is not None:
            return _date

    _cal = Calendar(Constants("en"))

    funcs = [
        _cal.parseDateText,
        _cal.parse,
        _cal.parseDT,
    ]

    key_minutes = 'minutes_hour'
    data = [_get_date_info(key_minutes, x, verbose) for x in _date_lines]
    result = _create_datetime(*_extract_day_time(data, key_minutes, [x.__name__ for x in funcs], verbose))

    if verbose:
        print(' ' * 20)
        print(' ' * 20)
        print('=' * 20)

    return result


text:
package org.openehealth.ipf.commons.ihe.fhir.iti67;

import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.IncludeParam;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.Read;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.annotation.Sort;
import ca.uhn.fhir.rest.api.SortSpec;
import ca.uhn.fhir.rest.api.server.IBundleProvider;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.DateRangeParam;
import ca.uhn.fhir.rest.param.ReferenceAndListParam;
import ca.uhn.fhir.rest.param.ReferenceOrListParam;
import ca.uhn.fhir.rest.param.ReferenceParam;
import ca.uhn.fhir.rest.param.TokenOrListParam;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.r4.model.DocumentReference;
import org.hl7.fhir.r4.model.IdType;
import org.hl7.fhir.r4.model.Patient;
import org.hl7.fhir.r4.model.Practitioner;
import org.hl7.fhir.r4.model.ResourceType;
import org.openehealth.ipf.commons.ihe.fhir.AbstractPlainProvider;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * Resource Provider for MHD (ITI-67).
 *
 * @author Christian Ohr
 * @since 4.1
 */
public class Iti67StrictResourceProvider extends AbstractPlainProvider {

    @SuppressWarnings("unused")
    @Search(type = DocumentReference.class)
    public IBundleProvider documentReferenceSearch(
            @RequiredParam(name = DocumentReference.SP_PATIENT, chainWhitelist = {"", Patient.SP_IDENTIFIER}) ReferenceParam patient,
            @RequiredParam(name = DocumentReference.SP_STATUS) TokenOrListParam status,
            @OptionalParam(name = DocumentReference.SP_IDENTIFIER) TokenParam identifier,
            @OptionalParam(name = DocumentReference.SP_DATE) DateRangeParam date,
            @OptionalParam(name = DocumentReference.SP_AUTHOR, chainWhitelist = { Practitioner.SP_FAMILY, Practitioner.SP_GIVEN }) ReferenceAndListParam author,
            @OptionalParam(name = DocumentReference.SP_CATEGORY) TokenOrListParam category,
            @OptionalParam(name = DocumentReference.SP_TYPE) TokenOrListParam type,
            @OptionalParam(name = DocumentReference.SP_SETTING) TokenOrListParam setting,
            @OptionalParam(name = DocumentReference.SP_PERIOD) DateRangeParam period,
            @OptionalParam(name = DocumentReference.SP_FACILITY) TokenOrListParam facility,
            @OptionalParam(name = DocumentReference.SP_EVENT) TokenOrListParam event,
            @OptionalParam(name = DocumentReference.SP_SECURITY_LABEL) TokenOrListParam securityLabel,
            @OptionalParam(name = DocumentReference.SP_FORMAT) TokenOrListParam format,
            @OptionalParam(name = DocumentReference.SP_RELATED, chainWhitelist = { "", DocumentReference.SP_IDENTIFIER }) ReferenceOrListParam related,
            // Extension to ITI-67
            @OptionalParam(name = IAnyResource.SP_RES_ID) TokenParam resourceId,
            @Sort SortSpec sortSpec,
            @IncludeParam Set<Include> includeSpec,
            RequestDetails requestDetails,
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) {

        var relatedTokenParam = new TokenOrListParam();
        if (related != null) {
            related.getValuesAsQueryTokens().stream()
                    .map(referenceParam -> referenceParam.toTokenParam(getFhirContext()))
                    .forEach(relatedTokenParam::addOr);
        }

        ReferenceOrListParam relatedParam = new ReferenceOrListParam();
        TokenOrListParam relatedIdParam = new TokenOrListParam();
        if (related != null) {
            related.getValuesAsQueryTokens().stream()
                    .filter(referenceParam -> !DocumentReference.SP_IDENTIFIER.equals(referenceParam.getChain()))
                    .forEach(relatedParam::addOr);
            related.getValuesAsQueryTokens().stream()
                    .filter(referenceParam -> DocumentReference.SP_IDENTIFIER.equals(referenceParam.getChain()))
                    .map(referenceParam -> referenceParam.toTokenParam(getFhirContext()))
                    .forEach(relatedIdParam::addOr);
        }

        var searchParameters = Iti67SearchParameters.builder()
                .status(status)
                .identifier(identifier)
                .date(date)
                .category(category)
                .type(type)
                .setting(setting)
                .period(period)
                .facility(facility)
                .event(event)
                .securityLabel(securityLabel)
                .format(format)
                .related(relatedParam)
                .relatedId(relatedIdParam)
                ._id(resourceId)
                .sortSpec(sortSpec)
                .includeSpec(includeSpec)
                .fhirContext(getFhirContext())
                .build();

        searchParameters.setAuthor(author);

        var patientChain = patient.getChain();
        if (Patient.SP_IDENTIFIER.equals(patientChain)) {
            searchParameters.setPatientIdentifier(patient.toTokenParam(getFhirContext()));
        } else if (patientChain == null || patientChain.isEmpty()) {
            searchParameters.setPatientReference(patient);
        }

        // Run down the route
        return requestBundleProvider(null, searchParameters, ResourceType.DocumentReference.name(),
                httpServletRequest, httpServletResponse, requestDetails);
    }

    /**
     * Handles DocumentReference Retrieve. This is not an actual part of the ITI-67 specification, but in the
     * context of restful FHIR IHE transaction it makes sense to be able to retrieve a DocumentReference by
     * its resource ID.
     *
     * @param id                  resource ID
     * @param httpServletRequest  servlet request
     * @param httpServletResponse servlet response
     * @param requestDetails      request details
     * @return {@link DocumentReference} resource
     */
    @SuppressWarnings("unused")
    @Read(version = true, type = DocumentReference.class)
    public DocumentReference documentReferenceRetrieve(
            @IdParam IdType id,
            RequestDetails requestDetails,
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) {
        if (id == null) throw new InvalidRequestException("Must provide ID with READ request");
        // Run down the route
        return requestResource(id, null, DocumentReference.class,
                httpServletRequest, httpServletResponse, requestDetails);
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: default
title: A collection of shapes made with SVG
---

	{% for post in paginator.posts %}

{{ post.title }}

	{% endfor %}

{% if paginator.page == paginator.total_pages %}

		Thanks for browsing—you've now reached the end.
		If you liked what you saw and want to get involved, head
		over to the Github repo to submit your own shapes.

{% endif %}

{% include home-page-pagination.html %}


text:
package kubelet

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"path"
	"strconv"
	"strings"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/capabilities"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client/record"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/clientauth"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/health"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/coreos/go-etcd/etcd"
	"github.com/fsouza/go-dockerclient"
	"github.com/golang/glog"
	cadvisor "github.com/google/cadvisor/client"
)

// TODO: move this into a pkg/util
func GetHostname(hostnameOverride string) string {
	hostname := []byte(hostnameOverride)
	if string(hostname) == "" {
		// Note: We use exec here instead of os.Hostname() because we
		// want the FQDN, and this is the easiest way to get it.
		fqdn, err := exec.Command("hostname", "-f").Output()
		if err != nil {
			glog.Fatalf("Couldn't determine hostname: %v", err)
		}
		hostname = fqdn
	}
	return strings.TrimSpace(string(hostname))
}

// TODO: move this into a pkg/util
func GetDockerEndpoint(dockerEndpoint string) string {
	var endpoint string
	if len(dockerEndpoint) > 0 {
		endpoint = dockerEndpoint
	} else if len(os.Getenv("DOCKER_HOST")) > 0 {
		endpoint = os.Getenv("DOCKER_HOST")
	} else {
		endpoint = "unix:///var/run/docker.sock"
	}
	glog.Infof("Connecting to docker on %s", endpoint)

	return endpoint
}

// TODO: move this into pkg/util
func ConnectToDockerOrDie(dockerEndpoint string) *docker.Client {
	client, err := docker.NewClient(GetDockerEndpoint(dockerEndpoint))
	if err != nil {
		glog.Fatal("Couldn't connect to docker.")
	}
	return client
}

// TODO: move this into the kubelet itself
func MonitorCAdvisor(k *Kubelet, cp uint) {
	defer util.HandleCrash()
	// TODO: Monitor this connection, reconnect if needed?
	glog.V(1).Infof("Trying to create cadvisor client.")
	cadvisorClient, err := cadvisor.NewClient("http://127.0.0.1:" + strconv.Itoa(int(cp)))
	if err != nil {
		glog.Errorf("Error on creating cadvisor client: %v", err)
		return
	}
	glog.V(1).Infof("Successfully created cadvisor client.")
	k.SetCadvisorClient(cadvisorClient)
}

// TODO: move this into the kubelet itself
func InitHealthChecking(k *Kubelet) {
	// TODO: These should probably become more plugin-ish: register a factory func
	// in each checker's init(), iterate those here.
	health.AddHealthChecker(health.NewExecHealthChecker(k))
	health.AddHealthChecker(health.NewHTTPHealthChecker(&http.Client{}))
	health.AddHealthChecker(&health.TCPHealthChecker{})
}

// TODO: move this into a pkg/tools/etcd_tools
func EtcdClientOrDie(etcdServerList util.StringList, etcdConfigFile string) *etcd.Client {
	if len(etcdServerList) > 0 {
		return etcd.NewClient(etcdServerList)
	} else if etcdConfigFile != "" {
		etcdClient, err := etcd.NewClientFromFile(etcdConfigFile)
		if err != nil {
			glog.Fatalf("Error with etcd config file: %v", err)
		}
		return etcdClient
	}
	return nil
}

// TODO: move this into pkg/util
func SetupRootDirectoryOrDie(rootDirectory string) {
	if rootDirectory == "" {
		glog.Fatal("Invalid root directory path.")
	}
	rootDirectory = path.Clean(rootDirectory)
	if err := os.MkdirAll(rootDirectory, 0750); err != nil {
		glog.Fatalf("Error creating root directory: %v", err)
	}
}

// TODO: move this into pkg/capabilities
func SetupCapabilities(allowPrivileged bool) {
	capabilities.Initialize(capabilities.Capabilities{
		AllowPrivileged: allowPrivileged,
	})
}

// TODO: Split this up?
func SetupLogging() {
	etcd.SetLogger(util.NewLogger("etcd "))
	// Log the events locally too.
	record.StartLogging(glog.Infof)
}

// TODO: move this into pkg/client
func getApiserverClient(authPath string, apiServerList util.StringList) (*client.Client, error) {
	authInfo, err := clientauth.LoadFromFile(authPath)
	if err != nil {
		return nil, err
	}
	clientConfig, err := authInfo.MergeWithConfig(client.Config{})
	if err != nil {
		return nil, err
	}
	if len(apiServerList) < 1 {
		return nil, fmt.Errorf("no apiservers specified.")
	}
	// TODO: adapt Kube client to support LB over several servers
	if len(apiServerList) > 1 {
		glog.Infof("Mulitple api servers specified.  Picking first one")
	}
	clientConfig.Host = apiServerList[0]
	if c, err := client.New(&clientConfig); err != nil {
		return nil, err
	} else {
		return c, nil
	}
}

func SetupEventSending(authPath string, apiServerList util.StringList) {
	// Make an API client if possible.
	if len(apiServerList) < 1 {
		glog.Info("No api servers specified.")
	} else {
		if apiClient, err := getApiserverClient(authPath, apiServerList); err != nil {
			glog.Errorf("Unable to make apiserver client: %v", err)
		} else {
			// Send events to APIserver if there is a client.
			glog.Infof("Sending events to APIserver.")
			record.StartRecording(apiClient.Events(""), "kubelet")
		}
	}
}


text:
package ru.primetalk.typed.ontology

import org.json4s.{JField, JObject, JValue}
import ru.primetalk.typed.ontology.meta.metameta.{AnyTypeMappings, PropertyIdTypeClass, Record, RecordRepresentation, RecordTypeClass, SchemaBuilder}
import ru.primetalk.typed.ontology.meta.SimplePropertiesMeta
import ru.primetalk.typed.ontology.meta.SimplePropertiesMeta.PropertyId
import ru.primetalk.typed.ontology.meta.metameta

import scala.language.{higherKinds, implicitConversions}
/**
  * Package `meta` contains definitions that are used to express ontology.
  * For instance, here we define PropertyId class that represent a property description.
  * We might want to put any additional metainformation in it. For example,
  */
package object json extends RecordRepresentation {

  val meta = SimplePropertiesMeta

  implicit val recordSupport: RecordTypeClass[RecordImpl, meta.PropertyIdImpl] = JObjectRecord.JObjectRecordTypeClassInstance

  type RecordImpl[A] = JObjectRecord[A]

  trait JsonConverter[B] {
    def toJson(value: B): JValue
    def fromJson(jvalue: JValue): B
  }

  case class JObjectRecord[A](jobject: JObject)

  object JObjectRecord {

//    implicit def f
    implicit def mapRecordToJObjectRecord[A]: metameta.TypeMapping[Record[A], JObjectRecord[A]] =
      metameta.typeMapping[Record[A], JObjectRecord[A]]

    implicit object JObjectRecordTypeClassInstance extends RecordTypeClass[JObjectRecord, PropertyId] {
      type PropertyHelper[A, B] = JsonConverter[B]
      class RecordWrapperImpl[A](val record: JObjectRecord[A]) extends RecordWrapper[A] {
        override def apply[B, D](key: Key[B])(implicit bd: metameta.TypeMapping[B, D], helper: PropertyHelper[A,B]): D =
          record.jobject.obj.collect{
            case (key.name, value) => helper.fromJson(value)
          }.
            head.
            asInstanceOf[D]

        override def get[B, D](key: Key[B])(implicit bd: metameta.TypeMapping[B, D], helper: PropertyHelper[A,B]): Option[D] =
          record.jobject.obj.collect{
            case (key.name, value) => helper.fromJson(value)
          }.
            headOption.
            asInstanceOf[Option[D]]

        override def updated[B, D](key: Key[B], value: D)(implicit bd: metameta.TypeMapping[B, D], helper: PropertyHelper[A,B]): JObjectRecord[A] =
          JObjectRecord(JObject((key.name, helper.toJson(value.asInstanceOf[B])) ::
            record.jobject.obj.filterNot(_._1 == key.name)))

        override def remove[B, D](key: Key[B])(implicit bd: metameta.TypeMapping[B, D], helper: PropertyHelper[A,B]): JObjectRecord[A] =
          JObjectRecord(JObject(record.jobject.obj.filterNot(_._1 == key.name)))
      }
      override def apply[A](record: JObjectRecord[A]):
        RecordWrapper[A] = new RecordWrapperImpl[A](record)

      class SchemaBuilderOps[A](schemaBuilder: SchemaBuilder[A]) extends RecordSchemaBuilderOps[A] {
        def empty: JObjectRecord[A] = JObjectRecord[A](JObject())
        def record(propValueList: PropertyValue[A, _, _]*): JObjectRecord[A] =
          JObjectRecord(JObject(
            propValueList.collect{
              case PropertyValue(key, Some(value), _, _, jsonConverter) =>
                (key.asInstanceOf[PropertyId[A,_]].name, jsonConverter.toJson(value)):JField
            }.toList
          ))

      }

      implicit def schemaBuilderOps[A](schemaBuilder: SchemaBuilder[A]): RecordSchemaBuilderOps[A] = new SchemaBuilderOps[A](schemaBuilder)

      case class PropertyValue[A, B, D](
        propertyId: PropertyId[Record[A],B],
        value: Option[D],
        bd: metameta.TypeMapping[B, D],
        r: PropertyIdTypeClass[PropertyId],
        jsonConverter: JsonConverter[D]
      )

      implicit class PropertyIdOps[A,B](propertyId: PropertyId[Record[A],B])(implicit val r: PropertyIdTypeClass[PropertyId]) {

        def :=[D](value: D)(implicit bd: metameta.TypeMapping[B, D], jsonConverter: JsonConverter[D]): PropertyValue[A, B, D] =
          PropertyValue[A, B, D](propertyId, Some(value), bd, r, jsonConverter)

        def ?=[D](value: Option[D])(implicit bd: metameta.TypeMapping[B, D], jsonConverter: JsonConverter[D]): PropertyValue[A, B, D] =
          PropertyValue[A, B, D](propertyId, value, bd, r, jsonConverter)
      }

    }

  }

  trait RecordTypeMappings extends AnyTypeMappings {
    implicit def mapRecordToJObjectRecord[A]: metameta.TypeMapping[Record[A], JObjectRecord[A]] =
      JObjectRecord.mapRecordToJObjectRecord
  }

  object RecordTypeMappings extends RecordTypeMappings

}


text:
project_dir=$(pwd)

# Sourcing vars
source $project_dir/scripts/.deployment-profile

./vendor/terraform/terraform remote config \
    -backend=s3 \
    -backend-config="bucket=${STATES_BUCKET}" \
    -backend-config="key=${STATES_KEY}" \
    -backend-config="region=${AWS_REGION}"

./vendor/terraform/terraform get -update=true infra
./vendor/terraform/terraform apply \
    -var "environment=${ENVIRONMENT}" \
    -var "aws_access_key=${AWS_ACCESS_KEY_ID}" \
    -var "aws_secret_key=${AWS_SECRET_ACCESS_KEY}" \
    -var "aws_region=${AWS_REGION}" \
    -var "hubot_slack_token=${HUBOT_SLACK_TOKEN}" \
    -var "hubot_google_cse_id=${HUBOT_GOOGLE_CSE_ID}" \
    -var "hubot_google_cse_key=${HUBOT_GOOGLE_CSE_KEY}" \
    infra


text:
package com.waimai.da.shockwave.web.mapper;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.springframework.stereotype.Repository;

import com.waimai.da.shockwave.bean.TableField;
import com.waimai.da.shockwave.web.mapper.provider.DBProvider;

/**
 * 目标表的数据库持久化类
 *
 * Created by jsong on 2017/6/1.
 */
@Repository
@Named("dbMapper")
public interface DBMapper {

    @InsertProvider(type = DBProvider.class, method = "insertAllSQL")
    int insertAll(
            @Param("list") List<Map<String, Object>> list,
            @Param("tableName") String tableName
    );

    @InsertProvider(type = DBProvider.class, method = "createTableSQL")
    void createTable(
            @Param("tableFields") List<TableField> tableFields,
            @Param("tableName") String tableName
    );

    @Select("SHOW TABLES LIKE #{tableName}")
    List<String> isExistenceTable(
            @Param("tableName") String tableName
    );

    @SelectProvider(type = DBProvider.class, method = "selectByTimestampSQL")
    @ResultType(Map.class)
    List<Map<String, Object>> findData(
            @Param("tableName") String tableName,
            @Param("startTimestamp") Date startTimestamp,
            @Param("endTimestamp") Date endTimestamp
    );

    @Select("SHOW TABLES")
    List<String> findAllTable();

}