text:
import bottle
#import os
import sys
import requests
import json
import pyproj
import traceback
import math
#from datetime import datetime
from multiprocessing import Process, Pipe

from shapely.geometry import shape,MultiPoint,Point,mapping
from shapely.geometry.polygon import Polygon
from shapely.geometry.multipolygon import MultiPolygon
from shapely.geometry.collection import GeometryCollection
from shapely.geometry.base import BaseGeometry
from shapely import ops
from functools import partial

from . import settings
from . import kmi

proj_aea = lambda geometry: pyproj.Proj("+proj=aea +lat_1=-17.5 +lat_2=-31.5 +lat_0=0 +lon_0=121 +x_0=5000000 +y_0=10000000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs")

def exportGeojson(feat,fname):
    if isinstance(feat,BaseGeometry):
        geojson = {
            "type":"FeatureCollection",
            "features":[
                {
                    "type":"Feature",
                    "geometry":mapping(feat),
                    "properties":{}
                }
            ]
        }
    elif isinstance(feat,tuple):
        geojson = {
            "type":"FeatureCollection",
            "features":[
                {
                    "type":"Feature",
                    "geometry":mapping(feat[0]),
                    "properties":feat[1] or {}
                }
            ]
        }
    elif isinstance(feat,list):
        features = []
        geojson = {
            "type":"FeatureCollection",
            "features":features
        }
        for f in feat:
            if isinstance(f,BaseGeometry):
                features.append({
                    "type":"Feature",
                    "geometry":mapping(f),
                    "properties":{}
                })
            elif isinstance(f,tuple):
                features.append({
                    "type":"Feature",
                    "geometry":mapping(f[0]),
                    "properties":f[1] or {}
                })
            else:
                raise Exception("Unsupported type({}.{})".format(f.__class__.__module__,f.__class__.__name__))
    else:
        raise Exception("Unsupported type({}.{})".format(feat.__class__.__module__,feat.__class__.__name__))

    with open(fname,'w') as f:
        f.write(json.dumps(geojson,indent=True))

    return fname

proj_wgs84 = pyproj.Proj(init='epsg:4326')
def buffer(lon, lat, meters,resolution=16):
    """
    Create a buffer around a point
    """
    # Azimuthal equidistant projection
    aeqd_proj = '+proj=aeqd +lat_0={} +lon_0={} +x_0=0 +y_0=0'
    project = partial(
        pyproj.transform,
        pyproj.Proj(aeqd_proj.format(lat, lon)),
        proj_wgs84)
    buf = Point(0, 0).buffer(meters,resolution=resolution)  # distance in metres
    return ops.transform(project, buf).exterior.coords[:]

def getShapelyGeometry(feature):
    if not feature["geometry"]:
        return None
    elif feature["geometry"]["type"] == "GeometryCollection":
        return GeometryCollection([shape(g) for g in feature["geometry"]["geometries"]])
    else:
        return shape(feature["geometry"])

def transform(geometry,src_proj="EPSG:4326",target_proj='aea'):
    if src_proj == target_proj:
        return geometry
    else:
        if src_proj == 'aea':
            src_proj = proj_aea(geometry)
        else:
            src_proj = pyproj.Proj(init=src_proj)

        if target_proj == 'aea':
            target_proj = proj_aea(geometry)
        else:
            target_proj = pyproj.Proj(init=target_proj)

        return ops.transform(
            partial(
                pyproj.transform,
                src_proj,
                #pyproj.Proj(proj="aea",lat1=geometry.bounds[1],lat2=geometry.bounds[3])
                #use projection 'Albers Equal Conic Area for WA' to calcuate the area
                target_proj
            ),
            geometry
        )
def getGeometryArea(geometry,unit,src_proj="EPSG:4326"):
    """
    Get polygon's area using albers equal conic area
    """
    if src_proj == 'aea':
        geometry_aea = geometry
    else:
        geometry_aea = ops.transform(
            partial(
                pyproj.transform,
                pyproj.Proj(init=src_proj),
                #pyproj.Proj(proj="aea",lat1=geometry.bounds[1],lat2=geometry.bounds[3])
                #use projection 'Albers Equal Conic Area for WA' to calcuate the area
                proj_aea(geometry)
            ),
            geometry
        )
    data = geometry_aea.area
    if unit == "ha" :
        return data / 10000.00
    elif unit == "km2":
        return data / 1000000.00
    else:
        return data

degrees2radians = math.pi / 180
radians2degrees = 180 /math.pi
def getBearing(p1,p2):
    lon1 = degrees2radians * p1.x
    lon2 = degrees2radians * p2.x
    lat1 = degrees2radians * p1.y
    lat2 = degrees2radians * p2.y
    a = math.sin(lon2 - lon1) * math.cos(lat2)
    b = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(lon2 - lon1);

    bearing = radians2degrees * math.atan2(a, b);
    return bearing if bearing >= 0 else bearing + 360

directions = {
    4:[360/4,math.floor(360 / 8 * 100) / 100,["N","E","S","W"]],
    8:[360/8,math.floor(360 / 16 * 100) / 100,["N","NE","E","SE","S","SW","W","NW"]],
    16:[360/16,math.floor(360 / 32 * 100) / 100,["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]],
    32:[360/32,math.floor(360 / 64 * 100) / 100,["N","NbE","NNE","NEbN","NE","NEbE","ENE","EbN","E","EbS","ESE","SEbE","SE","SEbS","SSE","SbE","S","SbW","SSW","SWbS","SW","SWbW","WSW","WbS","W","WbN","WNW","NWbW","NW","NWbN","NNW","NbW"]],
}

def getDirection(bearing,mode = 16):
    mode = mode or 16
    if mode not in directions:
        mode = 16

    index = int((math.floor(bearing / directions[mode][0])  + 0 if ((round(bearing % directions[mode][0],2) <= directions[mode][1])) else 1) % mode)
    return directions[mode][2][index]

def getDistance(p1,p2,unit="m",p1_proj="EPSG:4326",p2_proj="EPSG:4326"):
    if p1_proj == 'aea':
        p1_aea = p1
    else:
        p1_aea = ops.transform(
            partial(
                pyproj.transform,
                pyproj.Proj(init=p1_proj),
                #pyproj.Proj(proj="aea",lat1=geometry.bounds[1],lat2=geometry.bounds[3])
                #use projection 'Albers Equal Conic Area for WA' to calcuate the area
                proj_aea(p1)
            ),
            p1
        )

    if p2_proj == 'aea':
        p2_aea = p2
    else:
        p2_aea = ops.transform(
            partial(
                pyproj.transform,
                pyproj.Proj(init=p2_proj),
                #pyproj.Proj(proj="aea",lat1=geometry.bounds[1],lat2=geometry.bounds[3])
                #use projection 'Albers Equal Conic Area for WA' to calcuate the area
                proj_aea(p2)
            ),
            p2
        )

    data = p1_aea.distance(p2_aea)
    if unit == "km" :
        return data / 1000.00
    else:
        return data

#return polygon or multipolygons if have, otherwise return None
def extractPolygons(geom):
    if not geom:
        return None
    elif isinstance(geom,Polygon) or isinstance(geom,MultiPolygon):
        return geom
    elif isinstance(geom,GeometryCollection):
        result = None
        for g in geom:
            p = extractPolygons(g)
            if not p:
                continue
            elif not result:
                result = p
            elif isinstance(result,MultiPolygon):
                result = [geom1 for geom1 in result.geoms]
                if isinstance(p,Polygon):
                    result.append(p)
                    result = MultiPolygon(result)
                else:
                    for geom1 in p.geoms:
                        result.append(geom1)
                    result = MultiPolygon(result)
            else:
                if isinstance(p,Polygon):
                    result = MultiPolygon([result,p])
                else:
                    result = [result]
                    for geom1 in p.geoms:
                        result.append(geom1)
                    result = MultiPolygon(result)
        return result
    else:
        return None

def extractPoints(geom):
    if isinstance(geom,Point) or isinstance(geom,MultiPoint):
        return geom
    elif isinstance(geom,GeometryCollection):
        result = None
        for g in geom:
            p = extractPoints(g)
            if not p:
                continue
            elif not result:
                result = p
            elif isinstance(result,MultiPoint):
                result = [geom1 for geom1 in result.geoms]
                if isinstance(p,Point):
                    result.append(p)
                    result = MultiPoint(result)
                else:
                    for geom1 in p.geoms:
                        result.append(geom1)
                    result = MultiPoint(result)
            else:
                if isinstance(p,Point):
                    result = MultiPoint([result,p])
                else:
                    result = [result]
                    for geom1 in p.geoms:
                        result.append(geom1)
                    result = MultiPoint(result)
        return result
    else:
        return None

def retrieveFeatures(url,session_cookies):
        res = requests.get(url,verify=False,cookies=session_cookies)
        res.raise_for_status()
        return res.json()

def checkOverlap(session_cookies,feature,options,logfile):
    # needs gdal 1.10+
    layers = options["layers"]

    geometry = extractPolygons(getShapelyGeometry(feature))

    if not geometry :
        return

    features = {}
    #retrieve all related features from layers
    for layer in layers:
        if layer.get('cqlfilter'):
            layer_url="{}/wfs?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&cql_filter=BBOX({},{},{},{},{}) AND {}".format(layer["kmiservice"],layer["layerid"],layerdefinition(layer)["geometry_property"]["name"],geometry.bounds[1],geometry.bounds[0],geometry.bounds[3],geometry.bounds[2],layer['cqlfilter'])
        else:
            layer_url="{}/wfs?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&bbox={},{},{},{}".format(layer["kmiservice"],layer["layerid"],geometry.bounds[1],geometry.bounds[0],geometry.bounds[3],geometry.bounds[2])
        features[layer["id"]] = retrieveFeatures(layer_url, session_cookies)["features"]

        for layer_feature in features[layer["id"]]:
            layer_geometry = getShapelyGeometry(layer_feature)
            layer_feature["geometry"] = layer_geometry

    #check whether the features from different layers are overlap or not
    layergroup_index1 = 0
    while layergroup_index1 < len(layers) - 1:
        layer1 = layers[layergroup_index1]
        layergroup_index1 += 1
        layer_features1 = features[layer1["id"]]

        #check whether layer's features are overlap or not.
        feature_index1 = 0
        while feature_index1 < len(layer_features1):
            feature1 = layer_features1[feature_index1]
            feature_index1 += 1
            feature_geometry1 = feature1["geometry"]
            if not isinstance(feature_geometry1,Polygon) and not isinstance(feature_geometry1,MultiPolygon):
                continue

            layergroup_index2 = layergroup_index1
            while layergroup_index2 < len(layers):
                layer2 = layers[layergroup_index2]
                layergroup_index2 += 1
                layer_features2 = features[layer2["id"]]
                feature_index2 = 0

                while feature_index2 < len(layer_features2):
                    feature2 = layer_features2[feature_index2]
                    feature_index2 += 1
                    feature_geometry2 = feature2["geometry"]
                    feature_geometry1 = feature1["geometry"]
                    if not isinstance(feature_geometry2,Polygon) and not isinstance(feature_geometry2,MultiPolygon):
                        continue
                    intersections = extractPolygons(feature_geometry1.intersection(feature_geometry2))
                    if not intersections:
                        continue

                    layer1_pk = layer1.get("primary_key")
                    layer2_pk = layer2.get("primary_key")

                    if layer1_pk:
                        if isinstance(layer1_pk,basestring):
                            feat1 = "{}({}={})".format(layer1["layerid"],layer1_pk,feature1["properties"][layer1_pk])
                        else:
                            feat1 = "{}({})".format(layer1["layerid"],", ".join(["{}={}".format(k,v) for k,v in feature1["properties"].iteritems() if k in layer1_pk ]))
                    else:
                        feat1 = "{}({})".format(layer1["layerid"],json.dumps(feature1["properties"]))

                    if layer2_pk:
                        if isinstance(layer2_pk,basestring):
                            feat2 = "{}({}={})".format(layer2["layerid"],layer2_pk,feature2["properties"][layer2_pk])
                        else:
                            feat2 = "{}({})".format(layer2["layerid"],", ".join(["{}={}".format(k,v) for k,v in feature2["properties"].iteritems() if k in layer2_pk ]))
                    else:
                        feat2 = "{}({})".format(layer2["layerid"],json.dumps(feature2["properties"]))

                    msg = "intersect({}, {}) = {} ".format( feat1,feat2, intersections )
                    with open(logfile,"a") as f:
                        f.write(msg)
                        f.write("\n")

def calculateArea(feature,session_cookies,options):
    """
    return:{
        status {
             "invalid" : invalid message;
             "failed" : failed message;
             "overlapped" : overlap message

        }
        data: {
            total_area: 100   //exist if status_code = 1
            other_area: 10    //exist if status_code = 1 and len(layers) > 0
            layers: {   //exist if status_code = 1 and len(layers) > 0
                layer id: {
                    total_area: 12
                    areas:[
                        {area:1, properties:{
                            name:value
                        }}
                    ]
                }
            }
        }
    }
    The reason to calculate the area in another process is to releace the memory immediately right after area is calculated.
    """
    if not settings.CALCULATE_AREA_IN_SEPARATE_PROCESS:
        return  _calculateArea(feature,session_cookies,options,False)

    parent_conn,child_conn = Pipe(True)
    p = Process(target=calculateAreaInProcess,args=(child_conn,))
    p.daemon = True
    p.start()
    parent_conn.send([feature,session_cookies,options])
    result = parent_conn.recv()
    parent_conn.close()
    #p.join()
    #print("{}:get the area result from other process".format(datetime.now()))
    return result

def calculateAreaInProcess(conn):
    feature,session_cookies,options = conn.recv()
    result = _calculateArea(feature,session_cookies,options,True)
    if "overlap_logfile" in result:
        overlapLogfile = result["overlap_logfile"]
        del result["overlap_logfile"]
    else:
        overlapLogfile = None
    conn.send(result)
    conn.close()
    #print("{}:Calculating area finiahed".format(datetime.now()))
    #import time
    #time.sleep(30)
    #if overlapLogfile:
    #    try:
    #        if os.path.exists(overlapLogfile):
    #            os.remove(overlapLogfile)
    #    except:
    #        pass
    #    checkOverlap(session_cookies,feature,options,overlapLogfile)
    #print("{}:subprocess finished".format(datetime.now()))

def calculateFeatureArea(feature,src_proj="EPSG:4326",unit='ha'):
    return calculateGeometryArea(getShapelyGeometry(feature),src_proj=src_proj,unit=unit)

def calculateGeometryArea(geometry,src_proj="EPSG:4326",unit='ha'):
    geometry = extractPolygons(geometry)
    if not geometry :
        return 0

    valid,msg = geometry.check_valid
    if not valid:
        print("geometry is invalid.{}", msg)

    geometry_aea = transform(geometry,src_proj=src_proj,target_proj='aea')

    return  getGeometryArea(geometry_aea,unit,'aea')

def _calculateArea(feature,session_cookies,options,run_in_other_process=False):
    # needs gdal 1.10+
    layers = options["layers"]
    unit = options["unit"] or "ha"
    overlap = options["layer_overlap"] or False
    merge_result = options.get("merge_result",False)

    area_data = {}
    status = {}
    result = {"status":status,"data":area_data}

    total_area = 0
    total_layer_area = 0

    geometry = extractPolygons(getShapelyGeometry(feature))

    if not geometry :
        area_data["total_area"] = 0
        return result

    #before calculating area, check the polygon first.
    #if polygon is invalid, throw exception
    valid,msg = geometry.check_valid
    if not valid:
        status["invalid"] = msg

    geometry_aea = transform(geometry,target_proj='aea')

    try:
        area_data["total_area"] = getGeometryArea(geometry_aea,unit,'aea')
    except:
        traceback.print_exc()
        if "invalid" in status:
            status["failed"] = "Calculate total area failed.{}".format("\r\n".join(status["invalid"]))
        else:
            status["failed"] = "Calculate total area failed.{}".format(traceback.format_exception_only(sys.exc_type,sys.exc_value))

        return result

    if not layers:
        return result

    if settings.EXPORT_CALCULATE_AREA_FILES_4_DEBUG:
        #export geometry for debug
        properties = feature["properties"]
        properties.update({"area":area_data["total_area"]})
        exportGeojson((geometry_aea,properties),"/tmp/feature.geojson")

    for layer in layers:
        if "layerid" not in layer and "id" not in layer:
            raise Exception("Both 'id' and 'layerid' are missing in layer declaration")
        elif "layerid" not in layer:
            layer["layerid"] = layer["id"]
        elif "id" not in layer:
            layer["id"] = layer["layerid"]

    area_data["layers"] = {}
    areas_map = {} if merge_result else None
    for layer in layers:
        try:
            layer_area_data = []
            total_layer_area = 0
            area_data["layers"][layer["id"]] = {"areas":layer_area_data}

            if layer.get('cqlfilter'):
                layer_url="{}/wfs?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&cql_filter=BBOX({},{},{},{},{}) AND {}".format(layer["kmiservice"],layer["layerid"],layerdefinition(layer)["geometry_property"]["name"],geometry.bounds[1],geometry.bounds[0],geometry.bounds[3],geometry.bounds[2],layer['cqlfilter'])
            else:
                layer_url="{}/wfs?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&bbox={},{},{},{}".format(layer["kmiservice"],layer["layerid"],geometry.bounds[1],geometry.bounds[0],geometry.bounds[3],geometry.bounds[2])

            #print(layer_url)
            layer_features = retrieveFeatures(layer_url,session_cookies)["features"]

            if settings.EXPORT_CALCULATE_AREA_FILES_4_DEBUG:
                #export intersected areas for debug
                intersected_features = []
                intersected_layer_features = []

            for layer_feature in layer_features:
                layer_geometry = getShapelyGeometry(layer_feature)
                layer_geometry = transform(layer_geometry,target_proj='aea')
                if not isinstance(layer_geometry,Polygon) and not isinstance(layer_geometry,MultiPolygon):
                    continue
                intersections = extractPolygons(geometry_aea.intersection(layer_geometry))

                if not intersections:
                    continue

                layer_feature_area_data = None
                #try to get the area data from map
                if merge_result:
                    area_key = []
                    for key,value in layer["properties"].iteritems():
                        area_key.append(layer_feature["properties"][value])

                    area_key = tuple(area_key)
                    layer_feature_area_data = areas_map.get(area_key)

                if not layer_feature_area_data:
                     #map is not enabled,or data does not exist in map,create a new one
                    layer_feature_area_data = {"area":0}
                    for key,value in layer["properties"].iteritems():
                        layer_feature_area_data[key] = layer_feature["properties"][value]
                    layer_area_data.append(layer_feature_area_data)

                    if merge_result:
                        #save it into map
                        areas_map[area_key] = layer_feature_area_data

                feature_area = getGeometryArea(intersections,unit,src_proj='aea')
                layer_feature_area_data["area"] += feature_area
                total_layer_area  += feature_area

                if settings.EXPORT_CALCULATE_AREA_FILES_4_DEBUG:
                    #export intersected areas for debug
                    properties = layer_feature["properties"]
                    properties.update({"area":feature_area})
                    intersected_features.append((intersections,properties))
                    intersected_layer_features.append((layer_geometry,properties))

            if settings.EXPORT_CALCULATE_AREA_FILES_4_DEBUG:
                #export intersected areas for debug
                if intersected_features:
                    for feat in intersected_features:
                        feat[1].update({"total_area":total_layer_area})
                    exportGeojson(intersected_features,'/tmp/feature_area_{}_intersection.geojson'.format(layer["id"]))
                    exportGeojson(intersected_layer_features,'/tmp/feature_area_{}.geojson'.format(layer["id"]))

            area_data["layers"][layer["id"]]["total_area"] = total_layer_area
            total_area += total_layer_area
            if not overlap and total_area >= area_data["total_area"] :
                break

        except:
            traceback.print_exc()
            status["failed"] = "Calculate intersection area between fire boundary and layer '{}' failed.{}".format(layer["layerid"] or layer["id"],traceback.format_exception_only(sys.exc_type,sys.exc_value))

            break

    if "failed" in status:
        #calcuating area failed
        return result

    if not overlap :
        area_data["other_area"] = area_data["total_area"] - total_area
        if area_data["other_area"] < -0.01: #tiny difference is allowed.
            #some layers are overlap
            if not settings.CHECK_OVERLAP_IF_CALCULATE_AREA_FAILED:
                status["overlapped"] = "The sum({0}) of the burning areas in individual layers are ({2}) greater than the total burning area({1}).\r\n The features from layers({3}) are overlaped, please check.".format(round(total_area,2),round(area_data["total_area"],2),round(math.fabs(area_data["other_area"]),2),", ".join([layer["id"] for layer in layers]))
            else:
                filename = "/tmp/overlap_{}.log".format(feature["properties"].get("id","feature"))
                status["overlapped"] = "Features from layers are overlaped,please check the log file in server side '{}'".format(filename)
                if run_in_other_process:
                    result["overlap_logfile"] = filename
                else:
                    checkOverlap(session_cookies,feature,options,filename)

    return result

def layermetadata(layer):
    if not layer.get("_layermetadata"):
        layer["_layermetadata"] = kmi.get_layermetadata(layer["layerid"],kmiserver=layer["kmiservice"])
    return layer["_layermetadata"]

def layerdefinition(layer):
    if not layer.get("_layerdefinition"):
        layerdefinition = kmi.get_layerdefinition(layer["layerid"],kmiserver=layer["kmiservice"])
        layer["_layerdefinition"] = layerdefinition
    else:
        layerdefinition = layer["_layerdefinition"]

    if not layerdefinition["geometry_property"]:
        if layerdefinition["geometry_property_msg"]:
            raise Exception(layerdefinition["geometry_property_msg"])
        elif not layerdefinition["geometry_properties"]:
            raise Exception("The layer '{}' is not a spatial layer".format(layer["layerid"]))
        else:
            raise Exception("Failed to identify the geometry property of the layer '{}'".format(layer["layerid"]))

    return layerdefinition

def getFeature(feature,session_cookies,options):
    """
    options:{
        format: properties or geojson//optional default is properties
        action: getFeature or getIntersectedFeatures or getClosestFeature
        layers:[
            {
                id:     //if missing, use 'layerid' as id
                layerid: //layerid in kmi, in most cases, layerid is equal with id, if missing, use 'id' as layerid
                kmiservice: //optinoal,
                properties:{  //optional
                    name:column in dataset
                }
            },
            ...
        ]

    }
    getFeature result:[
        {
            id:
            layer:
            failed:  message if failed; otherwise is null
            properties: {
                name:value
            }
        },
    ]
    """
    # needs gdal 1.10+
    layers = options["layers"]
    #check whether layers is not empty
    if not layers:
        raise Exception("Layers must not be empty.")
    #check whether layers is list
    if not isinstance(layers,(list,tuple)):
        raise Exception("Layers must be list type.")

    #layers must be list of layers
    if  not isinstance(layers,(list,tuple)):
        layers = [layers]
    for layer in layers:
        if "layerid" not in layer and "id" not in layer:
            raise Exception("Both 'id' and 'layerid' are missing in layer declaration")
        elif "layerid" not in layer:
            layer["layerid"] = layer["id"]
        elif "id" not in layer:
            layer["id"] = layer["layerid"]

    get_feature_data = {"id":None,"layer":None,"failed":None}

    geometry = getShapelyGeometry(feature)
    try:
        for layer in layers:
            if not layer or not layer.get("kmiservice") or not layer["layerid"]:
                continue

            if layer.get('check_bbox'):
                #check whether feature is in layer's bbox
                layer_bbox = layermetadata(layer).get("latlonBoundingBox_EPSG:4326") or layermetadata(layer).get("latlonBoundingBox")
                if not layer_bbox:
                    get_feature_data["failed"] = "Can't find layer({})'s bounding box for epsg:4326".format(layer["layerid"])
                    break
                #buffered_bbox is  lonlatboundingbox
                if layer.get("buffer") and isinstance(geometry,Point):
                    checking_bbox = Polygon(buffer(geometry.x,geometry.y,layer["buffer"][-1] if isinstance(layer["buffer"],(list,tuple)) else layer["buffer"],resolution=1)).bounds
                else:
                    checking_bbox = geometry.bounds

                if checking_bbox[2] < layer_bbox[1] or checking_bbox[0] > layer_bbox[3] or checking_bbox[3] < layer_bbox[0] or checking_bbox[1] > layer_bbox[2]:
                    #not in this layer's bounding box
                    continue
            if options["action"] == "getFeature":
                get_feature_data["feature"] = None
                if isinstance(geometry,Point):
                    if layerdefinition(layer)["geometry_type"] in ["point",'multipoint']:
                        get_feature_data["failed"] = "The {1} layer '{0}' doesn't support action '{2}'. ".format(layer["layerid"],layerdefinition(layer)["geometry_property"]["localType"],options["action"])
                        break
                    else:
                        #polygon or line
                        layer_features = retrieveFeatures(
                            "{}/wfs?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&cql_filter=CONTAINS({},POINT({} {}))".format(layer["kmiservice"],layer["layerid"],layerdefinition(layer)["geometry_property"]["name"],geometry.y,geometry.x),
                            session_cookies
                        )["features"]

                else:
                    get_feature_data["failed"] = "Action '{}' Only support Point geometry.".format(options["action"])
                    break
            elif options["action"] == "getIntersectedFeatures":
                get_feature_data["features"] = None
                if isinstance(geometry,Point):
                    if not layer.get("buffer"):
                        get_feature_data["failed"] = "'buffer' is missing in layer '{}'".format(layer["id"])
                        break
                    buff_polygon = Polygon(buffer(geometry.x,geometry.y,layer["buffer"]))
                    layer_features = retrieveFeatures(
                        "{}/wfs?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&cql_filter=INTERSECTS({},POLYGON(({})))".format(layer["kmiservice"],layer["layerid"],layerdefinition(layer)["geometry_property"]["name"],"%2C".join(["{} {}".format(coord[0],coord[1]) for coord in list(buff_polygon.exterior.coords)])),
                        session_cookies
                    )["features"]
                elif isinstance(geometry,Polygon):
                    layer_features = retrieveFeatures(
                        "{}/wfs?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&cql_filter=INTERSECTS({},POLYGON(({})))".format(layer["kmiservice"],layer["layerid"],layerdefinition(layer)["geometry_property"]["name"],"%2C".join(["{} {}".format(coord[0],coord[1]) for coord in list(geometry.exterior.coords)])),
                        session_cookies
                    )["features"]
                else:
                    get_feature_data["failed"] = "Action '{}' Only support Point and Polygon geometry.".format(options["action"])
                    break

            elif options["action"] == "getClosestFeature":
                get_feature_data["feature"] = None
                layer_feature = None
                if not isinstance(geometry,Point):
                    get_feature_data["failed"] = "Action '{}' Only support Point geometry.".format(options["action"])
                    break
                #should get the grid data at the first try, if can't, set the grid data to null.
                for buff in layer["buffer"] if isinstance(layer["buffer"],(list,tuple)) else [layer["buffer"]]:
                    buff_bbox = Polygon(buffer(geometry.x,geometry.y,buff)).bounds
                    layer_features = retrieveFeatures(
                        "{}?service=wfs&version=2.0&request=GetFeature&typeNames={}&outputFormat=json&bbox={},{},{},{},urn:ogc:def:crs:EPSG:4326".format(layer["wfsservice"],layer["layerid"],buff_bbox[1],buff_bbox[0],buff_bbox[3],buff_bbox[2]),
                        session_cookies
                    )["features"]

                    if len(layer_features) == 1:
                        layer_feature = layer_features[0]
                        break
                    elif len(layer_features) > 1:
                        layer_feature = None
                        minDistance = None
                        for feat in layer_features:
                            if layer_feature is None:
                                layer_feature = feat
                                minDistance = getDistance(geometry,shape(feat["geometry"]),p2_proj=layermetadata(layer).get('srs') or "EPSG:4326")
                            else:
                                distance = getDistance(geometry,shape(feat["geometry"]),p2_proj=layermetadata(layer).get('srs') or "EPSG:4326")
                                if minDistance > distance:
                                    minDistance = distance
                                    layer_feature = feat
                        break
                if layer_feature:
                    layer_features = [layer_feature]
            else:
                get_feature_data["failed"] = "Action '{}' Not Support".format(options["action"])
                break

            if layer_features:
                if "feature" in get_feature_data and len(layer_features) > 1:
                    get_feature_data["failed"] = "Found {1} features in layer '{0}' ".format(layer["layerid"],len(layer_features))
                    break
                if layer_features:
                    get_feature_data["id"] = layer["id"]
                    get_feature_data["layer"] = layer["layerid"]
                    for layer_feature in layer_features:
                        feat = {}
                        if layer.get("properties"):
                            for name,column in layer["properties"].iteritems():
                                feat[name] = layer_feature["properties"][column]
                        else:
                            for key,value in layer_feature["properties"].iteritems():
                                feat[key] = value

                        if options.get("format") == "geojson":
                            #return geojson
                            layer_feature["properties"] = feat
                            feat = layer_feature
                        if "feature" in get_feature_data:
                            get_feature_data["feature"] = feat
                        elif "features" in get_feature_data:
                            if get_feature_data["features"]:
                                get_feature_data["features"].append(feat)
                            else:
                                get_feature_data["features"] = [feat]

                    break

    except:
        traceback.print_exc()
        get_feature_data["failed"] = "{} from layers ({}) failed.{}".format(options["action"],layers,traceback.format_exception_only(sys.exc_type,sys.exc_value))
    return get_feature_data

def spatial():
    # needs gdal 1.10+
    try:
        features = json.loads(bottle.request.forms.get("features"))
        options = bottle.request.forms.get("options")
        if options:
            options = json.loads(options)
        else:
            options = {}

        cookies = settings.get_session_cookie()
        results = []

        features = features["features"] or []
        index = 0
        while index < len(features):
            feature = features[index]
            index += 1
            feature_result = {}
            results.append(feature_result)
            for key,val in options.iteritems():
                if "action" not in val:
                    val["action"] = key
                if val["action"] == "getArea":
                    feature_result[key] = calculateArea(feature,cookies,val)
                else:
                    feature_result[key] = getFeature(feature,cookies,val)

        bottle.response.set_header("Content-Type", "application/json")
        #print("{}:return response to client.{}".format(datetime.now(),results))
        return {"total_features":len(results),"features":results}
    except:
        if bottle.response.status < 400 :
            bottle.response.status = 400
        bottle.response.set_header("Content-Type","text/plain")
        traceback.print_exc()
        return traceback.format_exception_only(sys.exc_type,sys.exc_value)


text:
package com.bxj.manager;

import com.bxj.AppConstants;
import com.bxj.domain.BXJListData;
import com.bxj.domain.WebData;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BXJDataParseMgr {
	private static BXJDataParseMgr mInstance;

	private BXJDataParseMgr() {
	}

	public static BXJDataParseMgr getInstance() {
		if (mInstance == null) {
			mInstance = new BXJDataParseMgr();
		}
		return mInstance;
	}

	public List<? extends WebData> parse(File saveHtmlFile) throws IOException {
		List<WebData> result = new ArrayList<>();
		FileInputStream in = new FileInputStream(saveHtmlFile);
		Document doc = Jsoup.parse(in, "utf-8", AppConstants.URL_BXJ);
		// Document doc = Jsoup.connect(URL_MAIN).get();
		Elements lis = doc.select(".show-list li");
		for (Element li : lis) {// 遍历
			// 获取p_title 包括所有的帖子信息
			Element titleUrl = li.select(".titlelink a").first();
			Element replyCount = li.select(".ansour").first();// 回复数 标签
			// 亮贴数 标签
			Elements light_r = li.getElementsByClass("light_r").select(
					"a[title]");
			BXJListData data = new BXJListData();
			if (light_r != null && light_r.size() > 0) {
				// 设置亮贴数 得到的字符格式为"有2个亮了的回帖" 需要截取
				String strLight = light_r.get(0).attr("title");
				strLight = strLight.substring(1, strLight.indexOf("个"));
				data.setLightCount(strLight);
			} else {
				data.setLightCount("0");
			}
			// 电脑版网址
			// data.setUrl("http://bbs.hupu.com" +
			// tmp.attr("href"));
			// 手机版网址
			data.setUrl("http://m.hupu.com/bbs" + titleUrl.attr("href"));
			data.setTitle(titleUrl.text());
			// 回复的格式为 12/36 回复/浏览数 现在只取回复数
			data.setReplyCount(replyCount.text().split("/")[0]);
			result.add(data);
		}
		return result;
	}
}

redpajama_set_name: RedPajamaGithub


text:
#include "ds3_response_header_utils.h"
#include "ds3_string_multimap_impl.h"
#include "ds3_utils.h"

#define BLOB_CHECKSUM_HEADER "ds3-blob-checksum-offset-"
#define BLOB_CHECKSUM_TYPE_HEADER "ds3-blob-checksum-type"

// Converts a ds3_str* containing a checksum value into a ds3_checksum_type*.
// If conversion is not possible, then NULL is returned.
static ds3_checksum_type* _convert_str_to_checksum_type(const ds3_log* log, const ds3_str* checksum_str) {
    if (checksum_str == NULL || checksum_str->value == NULL) {
        return NULL;
    }
    ds3_checksum_type* checksum_type = g_new0(ds3_checksum_type, 1);
    if (strcmp(checksum_str->value, "CRC_32") == 0) {
        *checksum_type = DS3_CHECKSUM_TYPE_CRC_32;
        return checksum_type;
    }
    if (strcmp(checksum_str->value, "CRC_32C") == 0) {
        *checksum_type = DS3_CHECKSUM_TYPE_CRC_32C;
        return checksum_type;
    }
    if (strcmp(checksum_str->value, "MD5") == 0) {
        *checksum_type = DS3_CHECKSUM_TYPE_MD5;
        return checksum_type;
    }
    if (strcmp(checksum_str->value, "SHA_256") == 0) {
        *checksum_type = DS3_CHECKSUM_TYPE_SHA_256;
        return checksum_type;
    }
    if (strcmp(checksum_str->value, "SHA_512") == 0) {
        *checksum_type = DS3_CHECKSUM_TYPE_SHA_512;
        return checksum_type;
    }
    g_free(checksum_type);
    ds3_log_message(log, DS3_ERROR, "ERROR: Unknown value of '%s' for ds3_checksum_type.", checksum_str->value);
    return NULL;
}

// Retrieves the blob checksum type from the response headers.
ds3_checksum_type* get_blob_checksum_type(const ds3_log* log, ds3_string_multimap* response_headers) {
    ds3_checksum_type* checksum_type = NULL;

    ds3_str* header_key = ds3_str_init(BLOB_CHECKSUM_TYPE_HEADER);
    ds3_string_multimap_entry* entry = ds3_string_multimap_lookup(response_headers, header_key);
    ds3_str_free(header_key);

    if (entry == NULL) {
        return NULL;
    }

    ds3_str* value = ds3_string_multimap_entry_get_value_by_index(entry, 0);
    ds3_string_multimap_entry_free(entry);

    checksum_type = _convert_str_to_checksum_type(log, value);
    ds3_str_free(value);

    return checksum_type;
}

// Retrieves the offset value at the end of a blob checksum header
static uint64_t* _get_offset_from_key(const ds3_str* key) {
    if (key == NULL) {
        return NULL;
    }

    uint64_t* offset = g_new0(uint64_t, 1);
    *offset = strtoull(key->value+strlen(BLOB_CHECKSUM_HEADER), NULL, 10);
    return offset;
}

// Retrieves the blob checksums from the response headers.
ds3_uint64_string_map* get_blob_checksums(const ds3_log* log, ds3_string_multimap* response_headers) {
    if (response_headers == NULL) {
        ds3_log_message(log, DS3_WARN, "Cannot parse blob checksum headers: response headers was null\n");
        return NULL;
    }

    ds3_uint64_string_map* blob_map = ds3_uint64_string_map_init();

    GHashTableIter iter;
    gpointer _key, _value;
    ds3_str* key = NULL;

    g_hash_table_iter_init(&iter, ds3_string_multimap_get_hashtable(response_headers));
    while(g_hash_table_iter_next(&iter, &_key, &_value)) {
        key = (ds3_str*) _key;
        if (g_str_has_prefix(key->value, BLOB_CHECKSUM_HEADER)) {
            ds3_string_multimap_entry* entry = ds3_string_multimap_lookup(response_headers, key);
            if (entry != NULL && ds3_string_multimap_entry_get_num_values(entry) > 0) {
                uint64_t* offset = _get_offset_from_key(key);
                if (offset != NULL) {
                    ds3_str* value = ds3_string_multimap_entry_get_value_by_index(entry, 0);
                    ds3_uint64_string_map_insert(blob_map, offset, value);
                    ds3_str_free(value);
                }
                g_free(offset);
            }
            ds3_string_multimap_entry_free(entry);
        }
    }
    return blob_map;
}


text:
```c
The VM entry/exit path is a giant inline assembly statement. Simplify it
by doing CR2 context switching in plain C. Move CR2 restore behind IBRS
clearing, so we reduce the amount of code we execute with IBRS on.

Signed-off-by: Julian Stecklina <jsteckli@amazon.de>
Reviewed-by: Jan H. Schönherr <jschoenh@amazon.de>
Reviewed-by: Konrad Jan Miller <kjm@amazon.de>
Reviewed-by: Jim Mattson <jmattson@google.com>
Reviewed-by: Sean Christopherson <sean.j.christopherson@intel.com>
---
 arch/x86/kvm/vmx.c | 15 +++++----------
 1 file changed, 5 insertions(+), 10 deletions(-)

```


text:
package cmd

import (
	"fmt"
	"log"
	entity "github.com/LeungChiHo/agenda/entity"
	"github.com/spf13/cobra"
)

// MeetingDeleteCmd represents the MeetingDelete command
var MeetingDeleteCmd = &cobra.Command{
	Use:   "deleteM -t [title]",
	Short: "delete meeting with the title [title]",
	Long:  `you can delete one meeting with the title [title]`,
	Run: func(cmd *cobra.Command, args []string) {
		debugLog := log.New(logFile,"[Result]", log.Ldate|log.Ltime|log.Lshortfile)
		if entity.StartAgenda() == false {
			debugLog.Println("Fail, please log in")
			fmt.Println("Fail, please log in")
		}
		arg_t, _ := cmd.Flags().GetString("Title")

		if entity.DeleteMeeting(entity.CurrentUser.Name, arg_t) {
			debugLog.Println("Cancel meeting successfully")
			fmt.Println("Cancel meeting successfully")
		} else {
			debugLog.Println("Fail to Cancel meeting")
			fmt.Println("Fail to Cancel meeting")
		}
		entity.QuitAgenda()
	},
}

func init() {
	RootCmd.AddCommand(MeetingDeleteCmd)
	MeetingDeleteCmd.Flags().StringP("Title", "t", "", "meeting title")
	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// MeetingDeleteCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// MeetingDeleteCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}


text:
local logger = {}

function logger:info(line)
  line = tostring(line)
  print(string.format("%s [INFO] %s", os.date("%Y-%m-%d %H:%M:%S", os.time()), line))
end

function logger:warn(line)
  line = tostring(line)
  print(string.format("%s [WARN] %s", os.date("%Y-%m-%d %H:%M:%S", os.time()), line))
end

function logger:error(line)
  line = tostring(line)
  print(string.format("%s [ERROR] %s", os.date("%Y-%m-%d %H:%M:%S", os.time()), line))
end

return logger


text:
<?php

namespace spec\Sylius\Bundle\CoreBundle\Form\Type;

use PhpSpec\ObjectBehavior;

class TaxonTypeSpec extends ObjectBehavior
{
    function let()
    {
        $this->beConstructedWith('Taxon', array());
    }

    function it_should_be_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\CoreBundle\Form\Type\TaxonType');
    }

    function it_should_be_a_form_type()
    {
        $this->shouldImplement('Symfony\Component\Form\FormTypeInterface');
    }

    function it_should_extend_Sylius_taxon_base_form_type()
    {
        $this->shouldHaveType('Sylius\Bundle\TaxonomyBundle\Form\Type\TaxonType');
    }
}


text:
import numpy as np

class Dataset(object):
    def __init__(self, word_data, tag_data):
        self._start = 0
        self._cursor = 0
        self._num_samples = word_data.shape[0]
        self._word_data = word_data
        self._tag_data = tag_data

    @property
    def word_data(self):
        return self._word_data

    @property
    def tag_data(self):
        return self._tag_data

    @property
    def num_samples(self):
        return self._num_samples

    def has_next(self):
        return self._cursor < self._num_samples

    def reset(self):
        self._cursor = 0
        self._start = 0

    def next_batch(self, batch_size):
        """Return the next `batch_size` examples from this data set."""
        self._start = self._cursor
        self._cursor += batch_size
        if self._start + batch_size > self._num_samples:
            rest_num_samples = self._num_samples - self._start
            word_batch = np.zeros((batch_size, self._word_data.shape[1]), dtype=np.int32)
            tag_batch = np.zeros((batch_size, self._word_data.shape[1]), dtype=np.int32)
            word_batch[0:rest_num_samples] = self._word_data[self._start:self._num_samples]
            tag_batch[0:rest_num_samples] = self._tag_data[self._start:self._num_samples]

            return word_batch, tag_batch
        else:
            end = self._cursor
            return self._word_data[self._start:end], self._tag_data[self._start:end]


text:
define(/*=='curl/plugin/_fetchText',==*/ [], function () {

	var xhr, progIds;

	progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];

	xhr = function () {
		if (typeof XMLHttpRequest !== "undefined") {
			// rewrite the getXhr method to always return the native implementation
			xhr = function () {
				return new XMLHttpRequest();
			};
		}
		else {
			// keep trying progIds until we find the correct one, then rewrite the getXhr method
			// to always return that one.
			var noXhr = xhr = function () {
				throw new Error("getXhr(): XMLHttpRequest not available");
			};
			while (progIds.length > 0 && xhr === noXhr) (function (id) {
				try {
					new ActiveXObject(id);
					xhr = function () {
						return new ActiveXObject(id);
					};
				}
				catch (ex) {
				}
			}(progIds.shift()));
		}
		return xhr();
	};

	function fetchText (url, callback, errback) {
		var x = xhr();
		x.open('GET', url, true);
		x.onreadystatechange = function (e) {
			if (x.readyState === 4) {
				if (x.status < 400) {
					callback(x.responseText);
				}
				else {
					errback(new Error('fetchText() failed. status: ' + x.statusText));
				}
			}
		};
		x.send(null);
	}

	return fetchText;

});


text:
using System;
using System.Collections.Generic;
using System.Text;
//
using net.silverfoxserver.core.model;
using DdzServer.net.silverfoxserver.extmodel;
using DdzServer.net.silverfoxserver.extfactory;

namespace DdzServer.net.silverfoxserver.extmodel
{
    public class TabModelByDdz : ITabModel
    {
        /// <summary>
        /// 房间种类,父级
        /// 对应客户端的tab navigate 序号
        /// </summary>
        private int _tab;

        public int Id {

            get {

                return _tab;

            }
        }

        public int Tab {

            get {

                return _tab;

            }

        }

        public int getId()
        {

            return _tab;

        }

        public int getTab()
        {

            return _tab;

        }

          /**
         *
         *
         */
        private String _tabName;

        public String getTabName()
        {

            return _tabName;

        }

        public void setTabName(String value)
        {

            this._tabName = value;

        }

        /// <summary>
        ///
        /// </summary>
        private int _roomCount;

        public int roomCount
        {
            get
            {
                return this._roomCount;
            }
        }

        public int getRoomCount()
        {
                return this._roomCount;
        }

        public void setRoomCount(int value)
        {
            _roomCount = value;

        }

        /// <summary>
        ///
        /// </summary>
        private int _roomG;

        public int roomG
        {
            get
            {
                return this._roomG;
            }
        }

        public int getRoomG()
        {
                return this._roomG;
        }

        public void setRoomG(int value)
        {
            _roomG = value;
        }

        /// <summary>
        ///
        /// </summary>
        private int _roomCarryG;

        public int roomCarryG
        {
            get
            {
                return this._roomCarryG;
            }
        }

        public int getRoomCarryG()
        {
                return this._roomCarryG;
        }

        public void setRoomCarryG(int value)
        {
            _roomCarryG = value;

        }

        /// <summary>
        ///
        /// </summary>
        private float _roomCostG;

        public float roomCostG
        {
            get
            {
                return this._roomCostG;
            }
        }

        public float getRoomCostG()
        {

            return this._roomCostG;

        }

        public void setRoomCostG(float value)
        {
            _roomCostG = value;
        }

        /// <summary>
        /// 防作弊自动匹配房间模式
        /// </summary>
        private int _tabAutoMatchMode;

        public bool isTabAutoMatchMode
        {
            get
            {

                if (0 == this._tabAutoMatchMode)
                {
                    return false;
                }

                return true;

            }

        }

        public void setTabAutoMatchMode(int tabAutoMatchMode)
        {
            this._tabAutoMatchMode = tabAutoMatchMode;

        }

        /// <summary>
        ///
        /// </summary>
        private int _tabQuickRoomMode;

        public bool isTabQuickRoomMode
        {
            get
            {
                if (0 == this._tabQuickRoomMode)
                {
                    return false;
                }

                return true;
            }

        }

        public void setQuickMode(int value)
        {
            this._tabQuickRoomMode = value;

        }

        /// <summary>
        ///
        /// </summary>
        private string[] _roomName;

        public string[] getRoomName()
        {
            if (null == _roomName)
            {
                 _roomName = new string[_roomCount];
            }

            if (_roomName.Length != _roomCount)
            {
                 _roomName = new string[_roomCount];
            }

            return _roomName;

        }

        public TabModelByDdz(int tab)
        {
            this._tab = tab;

        }

        public int getTabAutoMatchMode()
        {
            return this._tabAutoMatchMode;

        }

        public int getTabQuickRoomMode()
        {
            return this._tabQuickRoomMode;

        }

    }

}


text:
package com.aerolitec.SMXL.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.aerolitec.SMXL.R;
import com.aerolitec.SMXL.model.User;
import com.aerolitec.SMXL.tools.manager.UserManager;
import com.aerolitec.SMXL.ui.SMXL;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import au.com.bytecode.opencsv.CSVWriter;

public class CSVCreationActivity extends Activity {
    SQLiteDatabase myDatabase = null;
    String DataBase_Name = "SIZEGUIDE_DB";
    User user;

    /*
    ArrayList<Group> groups;
    ArrayList<String> listSize;
    ExpandableListView listView;
    EListAdapter adapter;
    */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_profil);

        user = UserManager.get().getUser();

        if(user == null) {
            finish();
            return;
        }

        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setTitle(user.getNickname());

        /*
        groups = new ArrayList<Group>();
        listSize = new ArrayList<>();

        listSize = SMXL.getDataBase().getUserSizes(user);
        getJSONObject();
        listView = (ExpandableListView) findViewById(R.id.listView);
        adapter = new EListAdapter(this, groups);
        listView.setAdapter(adapter);
        listView.setOnChildClickListener(adapter);

        */

        try {
            myDatabase = this.openOrCreateDatabase(DataBase_Name, MODE_PRIVATE, null);
            new ExportDatabaseCSVTask().execute("");

        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            Log.e("Error in Main Activity", ex.toString());
        }

    }

    /*
    private void getJSONObject() {
        String jsonShare ="";
        String jsonStr = "{'CommunityUsersResult':[{'CommunityUsersList':[{'fullname':'a111','userid':11,'username':'a1'}"
                + ",{'fullname':'b222','userid':12,'username':'b2'}],'id':1,'title':'Mesure'},{'CommunityUsersList':[{'fullname':"
                + "'c333','userid':13,'username':'c3'},{'fullname':'d444','userid':14,'username':'d4'},{'fullname':'e555','userid':"
                + "15,'username':'e5'}],'id':2,'title':'Vetement'}]}";

        if(listSize.size() != 0) {
            jsonShare = "{'Share':[{'User':[{'sexe':'" + user.getSexe() + "','birthday':'" +user.getBirthday()
                    + "','size':'" + listSize.get(0) + "','avatar':'" + user.getAvatar() + "','pictureDressingRoom':'" + user.getPictureDressingRoom()
                    + "','weight':'" + listSize.get(1) + "','bust':'" + listSize.get(2) + "','chest':'" + listSize.get(3)
                    + "','collar':'" + listSize.get(4) + "','waist':'" + listSize.get(5) + "','hips':'" + listSize.get(6)
                    + "','sleeve':'" + listSize.get(7) + "','inseam':'" + listSize.get(8) + "','feet':'" + listSize.get(9)
                    + "','unitL':'" + listSize.get(10) + "','unitW':'" + listSize.get(11) + "','pointure':'" + listSize.get(12) +  "'}],'id':1,'title':'" + user.getNickname() + "'}]}";
        }
        else {
            Toast.makeText(this, "Completer votre profil avant de l'exporter", Toast.LENGTH_SHORT).show();
            finish();
        }

        try {
            JSONObject values = new JSONObject(jsonShare);
            JSONArray groupList = values.getJSONArray("Share");

            for (int i = 0; i < groupList.length(); i++) {
                JSONObject groupObj = (JSONObject) groupList.get(i);
                Group group = new Group(groupObj.getString("id"), groupObj.getString("title"));
                JSONArray childrenList = groupObj.getJSONArray("User");

                for (int j = 0; j < childrenList.length(); j++) {
                    JSONObject childObj = (JSONObject) childrenList.get(j);
                    Child child = new Child(childObj.getString("birthday"), childObj.getString("avatar"),
                            childObj.getString("pictureDressingRoom"), childObj.getString("size"),
                            childObj.getString("weight"), childObj.getString("bust"), childObj.getString("chest"),
                            childObj.getString("collar"), childObj.getString("waist"), childObj.getString("hips"),
                            childObj.getString("sleeve"), childObj.getString("inseam"), childObj.getString("feet"),
                            childObj.getString("unitL"), childObj.getString("unitW"), childObj.getString("pointure"));

                    group.addChildrenItem(child);
                }

                groups.add(group);
            }
        } catch (JSONException e) {
            Log.d("allenj", e.toString());
        }
    }
    */

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.profil_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case android.R.id.home:
                if (getFragmentManager().findFragmentByTag("addMesure") != null || getFragmentManager().findFragmentByTag("addGarment") != null) {
                    getFragmentManager().popBackStack();
                } else {
                    finish();
                }
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> {
        private final ProgressDialog dialog = new ProgressDialog(CSVCreationActivity.this);

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Exporting database...");
            this.dialog.show();
        }

        protected Boolean doInBackground(final String... args) {
            File dbFile = getDatabasePath("myDatabase.db");
            File exportDir = new File(Environment.getExternalStorageDirectory(), "");

            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }

            File file = new File(exportDir, user.getNickname() + ".smxl");
            try {
                String tableUser = "user";
                String tableGarment = "user_clothes";
                file.createNewFile();
                CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
                String requestUser = "SELECT * FROM " + tableUser + " WHERE userid=" + String.valueOf(user.getId_user());
                String requestGarment = "SELECT * FROM " + tableGarment + " WHERE userid=" + String.valueOf(user.getId_user());

                while (myDatabase == null) {
                    dialog.show();
                }

                SMXL.getUserDBManager().getUser(user.getId_user());

                Cursor curGarment = myDatabase.rawQuery(requestGarment, null);
                Cursor curUser = myDatabase.rawQuery(requestUser, null);

                while (curUser.moveToNext()) {
                    String arrStr[] = {tableUser, curUser.getString(0), curUser.getString(1), curUser.getString(2), curUser.getString(3), curUser.getString(4),
                            curUser.getString(5), curUser.getString(6), curUser.getString(7), curUser.getString(8), curUser.getString(9), curUser.getString(10),
                            curUser.getString(11), curUser.getString(12), curUser.getString(13), curUser.getString(14), curUser.getString(15), curUser.getString(16),
                            curUser.getString(17), curUser.getString(18), curUser.getString(19), curUser.getString(20), curUser.getString(21), curUser.getString(22),
                            curUser.getString(23), curUser.getString(24), curUser.getString(25)};
                    csvWrite.writeNext(arrStr);
                }

                while (curGarment.moveToNext()){
                    String arrStr[] = {tableGarment, curGarment.getString(0), curGarment.getString(1), curGarment.getString(2), curGarment.getString(3), curGarment.getString(4),
                            curGarment.getString(5), curGarment.getString(6)};
                    csvWrite.writeNext(arrStr);
                }

                csvWrite.close();
                curGarment.close();
                curUser.close();
                send(file);
                return true;

            } catch (SQLException sqlEx) {
                Log.e("CSVCreation", sqlEx.getMessage(), sqlEx);
                return false;
            } catch (IOException e) {
                Log.e("CSVCreation", e.getMessage(), e);
                return false;
            }
        }

        private void send(File file) {
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
        }

        protected void onPostExecute(final Boolean success) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
            if (success) {
                Toast.makeText(CSVCreationActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(CSVCreationActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
            }
        }
    }

}


text:
extern NSString *const PNDTestCharKey;
extern NSString *const PNDTestIntKey;
extern NSString *const PNDTestShortKey;
extern NSString *const PNDTestLongKey;
extern NSString *const PNDTestLongLongKey;
extern NSString *const PNDTestUnsignedCharKey;
extern NSString *const PNDTestUnsignedIntKey;
extern NSString *const PNDTestUnsignedShortKey;
extern NSString *const PNDTestUnsignedLongKey;
extern NSString *const PNDTestUnsignedLongLongKey;
extern NSString *const PNDTestFloatKey;
extern NSString *const PNDTestDoubleKey;
extern NSString *const PNDTestBooleanKey;
extern NSString *const PNDTestIdKey;
extern NSString *const PNDTestClassKey;
extern NSString *const PNDTestCGAffineTransformKey;
extern NSString *const PNDTestCGPointKey;
extern NSString *const PNDTestCGRectKey;
extern NSString *const PNDTestCGSizeKey;
extern NSString *const PNDTestRangeKey;
extern NSString *const PNDTestUIEdgeInsetsKey;
extern NSString *const PNDTestUIOffsetKey;

@interface PNDTestUserDefaultsController : PNDUserDefaultsController

@property (nonatomic) char testChar;
@property (nonatomic) int testInt;
@property (nonatomic) short testShort;
@property (nonatomic) long testLong;
@property (nonatomic) long long testLongLong;
@property (nonatomic) unsigned char testUnsignedChar;
@property (nonatomic) unsigned int testUnsignedInt;
@property (nonatomic) unsigned short testUnsignedShort;
@property (nonatomic) unsigned long testUnsignedLong;
@property (nonatomic) unsigned long long testUnsignedLongLong;
@property (nonatomic) float testFloat;
@property (nonatomic) double testDouble;
@property (nonatomic) Boolean testBoolean;
@property (nonatomic, strong) id testId;
@property (nonatomic, strong) Class testClass;
@property (nonatomic) CGAffineTransform testCGAffineTransform;
@property (nonatomic) CGPoint testCGPoint;
@property (nonatomic) CGRect testCGRect;
@property (nonatomic) CGSize testCGSize;
@property (nonatomic) NSRange testRange;
@property (nonatomic) UIEdgeInsets testUIEdgeInsets;
@property (nonatomic) UIOffset testUIOffset;

@end


text:
#ifndef __ASM_CPU_SH3_MMU_CONTEXT_H
#define __ASM_CPU_SH3_MMU_CONTEXT_H

#define MMU_PTEH	0xFFFFFFF0	/* Page table entry register HIGH */
#define MMU_PTEL	0xFFFFFFF4	/* Page table entry register LOW */
#define MMU_TTB		0xFFFFFFF8	/* Translation table base register */
#define MMU_TEA		0xFFFFFFFC	/* TLB Exception Address */

#define MMUCR		0xFFFFFFE0	/* MMU Control Register */

#define MMU_TLB_ADDRESS_ARRAY	0xF2000000
#define MMU_PAGE_ASSOC_BIT	0x80

#define MMU_NTLB_ENTRIES	128	/* for 7708 */
#define MMU_NTLB_WAYS		4
#define MMU_CONTROL_INIT	0x007	/* SV=0, TF=1, IX=1, AT=1 */

#define TRA	0xffffffd0
#define EXPEVT	0xffffffd4

#if defined(CONFIG_CPU_SUBTYPE_SH7707) || defined(CONFIG_CPU_SUBTYPE_SH7709) || \
    defined(CONFIG_CPU_SUBTYPE_SH7300) || defined(CONFIG_CPU_SUBTYPE_SH7705)
#define INTEVT	0xa4000000	/* INTEVTE2(0xa4000000) */
#else
#define INTEVT	0xffffffd8
#endif

#endif /* __ASM_CPU_SH3_MMU_CONTEXT_H */


text:
require 'webrick'
require 'drb/drb'
require 'drb/http0'
require 'thread'

module DRb
  module HTTP0

    def self.open_server(uri, config)
      unless /^http:/ =~ uri
	raise(DRbBadScheme, uri) unless uri =~ /^http:/
	raise(DRbBadURI, 'can\'t parse uri:' + uri)
      end
      Server.new(uri, config)
    end

    class Callback < WEBrick::HTTPServlet::AbstractServlet
      def initialize(config, drb)
	@config = config
	@drb = drb
	@queue = Queue.new
      end

      def do_POST(req, res)
	@req = req
	@res = res
	@drb.push(self)
	@res.body = @queue.pop
	@res['content-type'] = 'application/octet-stream;'
      end

      def req_body
	@req.body
      end

      def reply(body)
	@queue.push(body)
      end

      def close
	@queue.push('')
      end
    end

    class Server
      def initialize(uri, config)
	@uri = uri
	@config = config
	@queue = Queue.new
	setup_webrick(uri)
      end
      attr_reader :uri

      def close
	@server.shutdown if @server
	@server = nil
      end

      def push(callback)
	@queue.push(callback)
      end

      def accept
	client = @queue.pop
	ServerSide.new(client, @config)
      end

      def setup_webrick(uri)
	logger = WEBrick::Log::new($stderr, WEBrick::Log::FATAL)
	u = URI.parse(uri)
	s = WEBrick::HTTPServer.new(:Port => u.port,
				    :AddressFamily => Socket::AF_INET,
				    :BindAddress => u.host,
				    :Logger => logger,
				    :ServerType => Thread)
	s.mount(u.path, Callback, self)
	@server = s
	s.start
      end
    end

    class ServerSide
      def initialize(callback, config)
	@callback = callback
	@config = config
	@msg = DRbMessage.new(@config)
	@req_stream = StrStream.new(@callback.req_body)
      end

      def close
	@callback.close if @callback
	@callback = nil
      end

      def alive?; false; end

      def recv_request
	begin
	  @msg.recv_request(@req_stream)
	rescue
	  close
	  raise $!
	end
      end

      def send_reply(succ, result)
	begin
	  return unless @callback
	  stream = StrStream.new
	  @msg.send_reply(stream, succ, result)
	  @callback.reply(stream.buf)
	rescue
	  close
	  raise $!
	end
      end
    end
  end
end


text:
// When duplicates are allowed and position matters

namespace Variations
{
    using System;

    class VariationCalculator
    {
        static void Main()
        {
            int n = 3;
            int k = 3;

            int[] variation = new int[k];

            GetVariation(variation, 0, n);
        }

        private static void GetVariation(int[] variation, int index, int upperBound)
        {
            if (index == variation.Length)
            {
                Console.WriteLine(string.Join(" ", variation));
                return;
            }

            for (int i = 1; i <= upperBound; i++)
            {
                variation[index] = i;
                GetVariation(variation, index + 1, upperBound);
            }
        }
    }
}


text:
	SkyNet
Cable & Broadband

		About UsDigital CableBroadbandContact Us


text:
<?php
/*
 * Generated by CRUDigniter v2.3 Beta
 * www.crudigniter.com
 */

class Rollbackstateevolution_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    /*
     * Get rollbackstateevolution by rollbackId
     */
    function get_rollbackstateevolution($rollbackId)
    {
        return $this->db->get_where('rollbackstateevolution',array('rollbackId'=>$rollbackId))->result_array();
    }

    /*
     * Get all rollbackstateevolution
     */
    function get_all_rollbackstateevolution()
    {
        return $this->db->get('rollbackstateevolution')->result_array();
    }

    /*
     * function to add new rollbackstateevolution
     */
    function add_rollbackstateevolution($params)
    {
        $this->db->insert('rollbackstateevolution',$params);
        return $this->db->insert_id();
    }

    /*
     * function to update rollbackstateevolution
     */
    function update_rollbackstateevolution($rollbackStatevolutionId,$params)
    {
        $this->db->where('rollbackStatevolutionId',$rollbackStatevolutionId);
        $response = $this->db->update('rollbackstateevolution',$params);
        if($response)
        {
            return "rollbackstateevolution updated successfully";
        }
        else
        {
            return "Error occuring while updating rollbackstateevolution";
        }
    }

    /*
     * function to delete rollbackstateevolution
     */
    function delete_rollbackstateevolution($rollbackStatevolutionId)
    {
        $response = $this->db->delete('rollbackstateevolution',array('rollbackStatevolutionId'=>$rollbackStatevolutionId));
        if($response)
        {
            return "rollbackstateevolution deleted successfully";
        }
        else
        {
            return "Error occuring while deleting rollbackstateevolution";
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

  <description>
  Configuration file for the Inspektr package which handles auditing for Java applications.
  If enabled this should be modified to log audit and statistics information the same way
  your local applications do.  The default is currently to log to the console which is good
  for debugging/testing purposes.
  </description>

  <aop:aspectj-autoproxy/>

  <bean id="auditTrailManagementAspect" class="com.github.inspektr.audit.AuditTrailManagementAspect">
    <!-- String applicationCode -->
    <constructor-arg index="0" value="CAS" />

    <!-- PrincipalResolver auditablePrincipalResolver -->
    <constructor-arg index="1" ref="auditablePrincipalResolver" />

    <!-- List<AuditTrailManager> auditTrailManagers -->
    <constructor-arg index="2">
      <list>
        <ref bean="auditTrailManager"/>
        <ref local="auditManager" />
      </list>
    </constructor-arg>

    <!-- Map<String,AuditActionResolver> auditActionResolverMap -->
    <constructor-arg index="3">
      <map>
        <entry key="AUTHENTICATION_RESOLVER">
          <ref local="authenticationActionResolver" />
        </entry>
        <entry key="CREATE_TICKET_GRANTING_TICKET_RESOLVER">
          <ref local="ticketCreationActionResolver" />
        </entry>
        <entry key="DESTROY_TICKET_GRANTING_TICKET_RESOLVER">
          <bean class="com.github.inspektr.audit.spi.support.DefaultAuditActionResolver" />
        </entry>
        <entry key="GRANT_SERVICE_TICKET_RESOLVER">
          <ref local="ticketCreationActionResolver" />
        </entry>
        <entry key="GRANT_PROXY_GRANTING_TICKET_RESOLVER">
          <ref local="ticketCreationActionResolver" />
        </entry>
        <entry key="VALIDATE_SERVICE_TICKET_RESOLVER">
          <ref local="ticketValidationActionResolver" />
        </entry>
        <entry key="DELETE_SERVICE_ACTION_RESOLVER">
            <ref local="deleteServiceActionResolver" />
        </entry>
        <entry key="SAVE_SERVICE_ACTION_RESOLVER">
          <ref local="saveServiceActionResolver" />
        </entry>
      </map>
    </constructor-arg>

    <!-- Map<String,AuditResourceResolver> auditResourceResolverMap -->
    <constructor-arg index="4">
      <map>
        <entry key="AUTHENTICATION_RESOURCE_RESOLVER">
          <bean class="org.jasig.cas.audit.spi.CredentialsAsFirstParameterResourceResolver" />
        </entry>
        <entry key="CREATE_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER">
          <ref local="returnValueResourceResolver" />
        </entry>
        <entry key="DESTROY_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER">
          <ref local="ticketResourceResolver" />
        </entry>
        <entry key="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER">
          <bean class="org.jasig.cas.audit.spi.ServiceResourceResolver" />
        </entry>
        <entry key="GRANT_PROXY_GRANTING_TICKET_RESOURCE_RESOLVER">
          <ref local="returnValueResourceResolver" />
        </entry>
        <entry key="VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER">
          <ref local="ticketResourceResolver" />
        </entry>
        <entry key="DELETE_SERVICE_ACTION_RESOLVER">
          <ref local="returnValueResourceResolver" />
        </entry>
          <entry key="SAVE_SERVICE_RESOURCE_RESOLVER">
          <ref local="returnValueResourceResolver" />
        </entry>
        <entry key="DELETE_SERVICE_RESOURCE_RESOLVER">
            <ref local="deleteServiceResourceResolver" />
        </entry>
        <entry key="SAVE_SERVICE_RESOURCE_RESOLVER">
            <ref local="saveServiceResourceResolver" />
        </entry>
      </map>
    </constructor-arg>
  </bean>

    <bean id="saveServiceResourceResolver" class="com.github.inspektr.audit.spi.support.ParametersAsStringResourceResolver" />

    <bean id="deleteServiceResourceResolver" class="org.jasig.cas.audit.spi.ServiceManagementResourceResolver" />

    <bean id="saveServiceActionResolver" class="com.github.inspektr.audit.spi.support.DefaultAuditActionResolver">
        <constructor-arg index="0" value="_SUCCEEDED" />
        <constructor-arg index="1" value="_FAILED" />
    </bean>

    <bean id="deleteServiceActionResolver" class="com.github.inspektr.audit.spi.support.ObjectCreationAuditActionResolver">
        <constructor-arg index="0" value="_SUCCEEDED" />
        <constructor-arg index="1" value="_FAILED" />
    </bean>

  <bean id="auditablePrincipalResolver" class="org.jasig.cas.audit.spi.TicketOrCredentialPrincipalResolver">
      <constructor-arg index="0" ref="ticketRegistry" />
  </bean>

  <bean id="authenticationActionResolver"
    class="com.github.inspektr.audit.spi.support.DefaultAuditActionResolver">
    <!-- String successSuffix -->
    <constructor-arg index="0" value="_SUCCESS" />

    <!-- String failureSuffix -->
    <constructor-arg index="1" value="_FAILED" />
  </bean>

  <bean id="ticketCreationActionResolver"
    class="com.github.inspektr.audit.spi.support.DefaultAuditActionResolver">
    <!-- String successSuffix -->
    <constructor-arg index="0" value="_CREATED" />

    <!-- String failureSuffix -->
    <constructor-arg index="1" value="_NOT_CREATED" />
  </bean>

  <bean id="ticketValidationActionResolver"
    class="com.github.inspektr.audit.spi.support.DefaultAuditActionResolver">
    <!-- String successSuffix -->
    <constructor-arg index="0" value="D" />

    <!-- String failureSuffix -->
    <constructor-arg index="1" value="_FAILED" />
  </bean>

  <bean id="returnValueResourceResolver"
     class="com.github.inspektr.audit.spi.support.ReturnValueAsStringResourceResolver" />

  <bean id="ticketResourceResolver"
    class="org.jasig.cas.audit.spi.TicketAsFirstParameterResourceResolver" />

   <!--
  Uncomment following beans for JDBC support.
  Assumes there is a dataSource bean that defines a valid JDBC data source.
  -->

  <bean id="inspektrTransactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
    p:dataSource-ref="dataSource"
  />

  <bean id="inspektrTransactionTemplate"
    class="org.springframework.transaction.support.TransactionTemplate"
    p:transactionManager-ref="inspektrTransactionManager"
    p:isolationLevelName="ISOLATION_READ_COMMITTED"
    p:propagationBehaviorName="PROPAGATION_REQUIRED"
  />

  <bean id="auditManager" class="com.github.inspektr.audit.support.JdbcAuditTrailManager">
    <constructor-arg index="0" ref="inspektrTransactionTemplate" />
    <property name="dataSource" ref="dataSource" />
    <property name="cleanupCriteria" ref="auditCleanupCriteria" />
  </bean>

    <bean id="auditCleanupCriteria"
      class="com.github.inspektr.audit.support.MaxAgeWhereClauseMatchCriteria">
      <constructor-arg index="0" value="180" />
    </bean>

</beans>


text:
package com.github.horrorho.inflatabledonkey.args.filter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import javax.annotation.concurrent.Immutable;

/**
 * Index filter. Filters List elements with reference to their indices. Negative selection values indicate positions
 * relative to the last element, with the last element being -1. If no selections are specified, the filter is disabled
 * and all elements pass through un-filtered.
 *
 * @author Ahseya
 */
@Immutable
public final class IndexFilter<T> implements UnaryOperator<List<T>> {

    private final List<Integer> selection;

    public IndexFilter(Collection<Integer> selection) {
        this.selection = new ArrayList<>(selection);
    }

    @Override
    public List<T> apply(List<T> list) {
        return selection.isEmpty()
                ? list
                : filter(list);
    }

    List<T> filter(List<T> list) {
        return selection.stream()
                .map(i -> i < 0 ? list.size() + i : i)
                .filter(i -> i >= 0 && i < list.size())
                .map(list::get)
                .collect(Collectors.toList());
    }
}


text:
package org.apache.dubbo.registry.client.event.listener;

import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.event.EventListener;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.registry.client.event.ServiceInstancePreRegisteredEvent;

/**
 * Customize the {@link ServiceInstance} before registering to Registry.
 *
 * @since 2.7.5
 */
public class CustomizableServiceInstanceListener implements EventListener<ServiceInstancePreRegisteredEvent> {

    @Override
    public void onEvent(ServiceInstancePreRegisteredEvent event) {
        ExtensionLoader<ServiceInstanceCustomizer> loader =
                ExtensionLoader.getExtensionLoader(ServiceInstanceCustomizer.class);
        // FIXME, sort customizer before apply
        loader.getSupportedExtensionInstances().forEach(customizer -> {
            // customizes
            customizer.customize(event.getServiceInstance());
        });
    }
}


text:
{% extends "base.html" %}
{% block meta_title %}
News
{% endblock %}

{% block content %}

OSDC News

{% load wordpress_rss %}
{% wordpress_rss rss_category 10 as rss_results %}

{% for item in rss_results %}

	{{ item.title }}

Posted on {{ item.published }}

{{ item.content }}

{% endfor %}

{% endblock %}

{% block js %}
{% include "horizon/_scripts.html" %}

{% endblock %}


text:
        Product

 {{vendor.name}}

Product

{{product.name}}

{{vendor.name}}

	                  Category {{product.type}}

	                  Subcategory {{product.subcategory}}

	                  Measure Unit {{product.model}}

	                  <button class="btn btn-primary btn-block" ng-show="showNewInventoryForm==false" ng-click="newInventory()">Add Inventory</button>

	              		<form class="form-horizontal" ng-submit="addInventory(newinventory)" ng-show="showNewInventoryForm==true">

New Inventory Item

		                    Serial Number

		                      <input type="text" class="form-control" ng-model="newinventory.serialnumber" required/>

		                    Unit Price

		                      <input type="text" class="form-control" ng-model="newinventory.unitprice" required/>

		                    Restock

		                      <input type="text" class="form-control" ng-model="newinventory.restock" required/>

		                    Instock

		                      <input type="text" class="form-control" ng-model="newinventory.instock" required/>

<button type="submit" class="btn btn-success btn-block">Save</button>

<button type="button" class="btn btn-warning btn-block" ng-click="cancelNewInventory()">Cancel</button>

			              </form>

Inventory

Settings

	                  	Serial number
	                    Unit price
	                    Restock
	                    Instock
	                    Active

	                    <input type="text" ng-readonly="inventory.readonly==true" class="form-control" ng-model="inventory.serialnumber" />
	                    <input type="text" ng-readonly="inventory.readonly==true" class="form-control" ng-model="inventory.unitprice" />
	                    <input type="text" ng-readonly="inventory.readonly==true" class="form-control" ng-model="inventory.restock" />
	                    <input type="text" ng-readonly="inventory.readonly==true" class="form-control" ng-model="inventory.instock" />
	                    <input type="checkbox" ng-disabled="inventory.readonly==true" class="" ng-model="inventory.isdeleted" ng-true-value="0" ng-false-value="1"/>

	                    	<button type="button" ng-show="inventory.readonly==true" ng-click="editInventory(inventory)">Edit</button>
	                    	<button type="button" ng-show="inventory.readonly==false" ng-click="updateInventory(inventory)">Update</button>
	                    	<button type="button" ng-show="inventory.readonly==false" ng-click="cancelEditInventory(inventory)">Cancel</button>

                <form class="form-horizontal" ng-submit="save(product)">

                    Name

                      <input type="text" class="form-control" placeholder="Name" ng-model="product.name" required />

                    Category

                      <input type="text" class="form-control" placeholder="Category" ng-model="product.type" required />

                    Sub Category

                      <input type="text" class="form-control" placeholder="Sub Category" ng-model="product.subcategory" required />

                    Measure Unit

                      <input type="text" class="form-control" placeholder="Measure Unit" ng-model="product.model">

                      <button type="submit" class="btn btn-warning">Update</button>

                </form>


text:
{% extends "base.html" %}
{% load url %}
{% load static %}

{% block title %}{{ object.workstation.slug }} Session -
    {{ block.super }}{% endblock %}

{% block breadcrumbs %}

Viewers

{{ object.workstation_image.workstation.title }}

{{ object.workstation_image }}

{{ object }}

{% endblock %}

{% block content %}

Viewer Session

    {% if unsupported_browser_message %}

{{ unsupported_browser_message }}

    {% endif %}

    {% if object.status != object.STOPPED and object.status != object.FAILED %}

            This session will expire in {{ object.expires_at|timeuntil }}.

    {% endif %}

                        Loading
                            Workstation...

                    <button type="button" class="btn btn-secondary"
                            data-dismiss="modal">Close
                    </button>

{% endblock %}

{% block script %}
    {{ block.super }}

{% endblock %}


text:
#include "pch.h"
#include "BooleanToNegativeBooleanConverter.h"

using namespace Platform;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Interop;
using namespace Mntone::WinRtLibrary::UI::Xaml::Converters;

Object^ BooleanToNegativeBooleanConverter::Convert(Object^ value, TypeName /*targetType*/, Object^ /*parameter*/, String^ /*language*/)
{
	auto flag = dynamic_cast<IBox<bool>^>(value);
	if (flag != nullptr)
	{
		return !flag->Value;
	}
	return DependencyProperty::UnsetValue;
}

Object^ BooleanToNegativeBooleanConverter::ConvertBack(Object^ value, TypeName /*targetType*/, Object^ /*parameter*/, String^ /*language*/)
{
	auto flag = dynamic_cast<IBox<bool>^>(value);
	if (flag != nullptr)
	{
		return !flag->Value;
	}
	return nullptr;
}


text:
package com.github.maxopoly.commands;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;

public class CommandHandler implements CommandExecutor {
	private JavaPlugin plugin;
	HashMap<String, AbstractCommand> commands = new HashMap<String, AbstractCommand>();

	public CommandHandler(JavaPlugin instance) {
		plugin = instance;

		plugin.getCommand("ee").setExecutor(this);

		registerCommands(new AbstractCommand[] { new Reload(plugin),
				new WrathOfTheGods(plugin) });
	}

	private void registerCommands(AbstractCommand[] abstractCommands) {

		for (AbstractCommand abstractCommand : abstractCommands) {
			commands.put(abstractCommand.getName(), abstractCommand);
			List<String> aliases = abstractCommand.getAliases();
			if (abstractCommand.getAliases() != null) {
				for (String alias : aliases) {
					commands.put(alias, abstractCommand);
				}
			}
		}
	}

	public boolean onCommand(CommandSender sender, Command cmd, String label,
			String[] args) {

		if (args.length == 0 || !commands.containsKey(args[0].toLowerCase()))
			return false;

		AbstractCommand abstractCommand = commands.get(args[0].toLowerCase());

		if (abstractCommand.getPermission() != null
				&& !sender.hasPermission(abstractCommand.getPermission())) {
			sender.sendMessage("You don't have the permission to use this command!");
			return true;
		}

		if (abstractCommand.onCommand(sender,
				Arrays.asList(args).subList(1, args.length)) == false
				&& abstractCommand.getUsage() != null) {
			sender.sendMessage("The correct usage is"
					+ abstractCommand.getUsage());
		}

		return true;
	}
}


text:
package joshie.enchiridion.gui.book.features;

import joshie.enchiridion.api.book.IFeature;

public class FeatureError extends FeatureAbstract {
    public FeatureError() {
    }

    @Override
    public IFeature copy() {
        return new FeatureError();
    }
}


text:
title: Ola Mundo!
author: Tacio Santos
date: 2016-11-23 12:00:00 -0300
layout: post
description: Post introdutorio ao site
tags:
- motivacao
- mensagem
categories:
- mensagem
disqus: true
permalink : /posts/ola-mundo/
---

#### Há Muito tempo em uma galaxia muito distante...

Na verdade não foi a tanto tempo assim.

A mais ou menos uns 3 ou quatro anos eu comecei a fazer o curso de html do canal curso em video, e desde então estudo tudo relacionado a computadores, desenvolvimento web, java, c, etc. Não sou um especialista em desenvolvimento web mais estou disposto a apresentar aqui os conhecimentos que me forem possiveis.

Estou aqui montando este blog hj para tentar prover **de forma gratuita** o suporte que eu não tive nos meus primeiros contatos com a programação.

Sei que não é facil começar a estudar programação, muitos na verdade desistem, mas estou aqui disponível para sanar todas as dúvidas que forem possiveis.

Um bom dia e uma boa caminhada pelos caminhos do desenvolvimento!

*Tacio Santos*


text:
package com.badlogic.gdx.graphics.g3d;

import java.util.Comparator;
import java.util.Iterator;

import com.badlogic.gdx.utils.Array;

public class Attributes implements Iterable<Attribute>, Comparator<Attribute> {
	protected long mask;
	protected final Array<Attribute> attributes = new Array<Attribute>();

	protected boolean sorted = true;

	/** Sort the attributes by their ID */
	public final void sort () {
		if (!sorted) {
			attributes.sort(this);
			sorted = true;
		}
	}

	/** @return Bitwise mask of the ID's of all the containing attributes */
	public final long getMask () {
		return mask;
	}

	/** Example usage: ((BlendingAttribute)material.get(BlendingAttribute.ID)).sourceFunction;
	 * @return The attribute (which can safely be cast) if any, otherwise null */
	public final Attribute get (final long type) {
		if (has(type)) for (int i = 0; i < attributes.size; i++)
			if (attributes.get(i).type == type) return attributes.get(i);
		return null;
	}

	/** Example usage: ((BlendingAttribute)material.get(BlendingAttribute.ID)).sourceFunction;
	 * @return The attribute if any, otherwise null */
	public final <T extends Attribute> T get (Class<T> clazz, final long type) {
		return (T)get(type);
	}

	/** Get multiple attributes at once. Example: material.get(out, ColorAttribute.Diffuse | ColorAttribute.Specular |
	 * TextureAttribute.Diffuse); */
	public final Array<Attribute> get (final Array<Attribute> out, final long type) {
		for (int i = 0; i < attributes.size; i++)
			if ((attributes.get(i).type & type) != 0) out.add(attributes.get(i));
		return out;
	}

	/** Removes all attributes */
	public void clear () {
		mask = 0;
		attributes.clear();
	}

	/** @return The amount of attributes this material contains. */
	public int size () {
		return attributes.size;
	}

	private final void enable (final long mask) {
		this.mask |= mask;
	}

	private final void disable (final long mask) {
		this.mask &= -1L ^ mask;
	}

	/** Add a attribute to this material. If the material already contains an attribute of the same type it is overwritten. */
	public final void set (final Attribute attribute) {
		final int idx = indexOf(attribute.type);
		if (idx < 0) {
			enable(attribute.type);
			attributes.add(attribute);
			sorted = false;
		} else {
			attributes.set(idx, attribute);
		}
	}

	/** Add multiple attributes to this material. If the material already contains an attribute of the same type it is overwritten. */
	public final void set (final Attribute attribute1, final Attribute attribute2) {
		set(attribute1);
		set(attribute2);
	}

	/** Add multiple attributes to this material. If the material already contains an attribute of the same type it is overwritten. */
	public final void set (final Attribute attribute1, final Attribute attribute2, final Attribute attribute3) {
		set(attribute1);
		set(attribute2);
		set(attribute3);
	}

	/** Add multiple attributes to this material. If the material already contains an attribute of the same type it is overwritten. */
	public final void set (final Attribute attribute1, final Attribute attribute2, final Attribute attribute3,
		final Attribute attribute4) {
		set(attribute1);
		set(attribute2);
		set(attribute3);
		set(attribute4);
	}

	/** Add an array of attributes to this material. If the material already contains an attribute of the same type it is
	 * overwritten. */
	public final void set (final Attribute... attributes) {
		for (final Attribute attr : attributes)
			set(attr);
	}

	/** Add an array of attributes to this material. If the material already contains an attribute of the same type it is
	 * overwritten. */
	public final void set (final Iterable<Attribute> attributes) {
		for (final Attribute attr : attributes)
			set(attr);
	}

	/** Removes the attribute from the material, i.e.: material.remove(BlendingAttribute.ID); Can also be used to remove multiple
	 * attributes also, i.e. remove(AttributeA.ID | AttributeB.ID); */
	public final void remove (final long mask) {
		for (int i = 0; i < attributes.size; i++) {
			final long type = attributes.get(i).type;
			if ((mask & type) == type) {
				attributes.removeIndex(i);
				disable(type);
				sorted = false;
			}
		}
	}

	/** @return True if this collection has the specified attribute, i.e. attributes.has(ColorAttribute.Diffuse); Or when multiple
	 *         attribute types are specified, true if this collection has all specified attributes, i.e. attributes.has(out,
	 *         ColorAttribute.Diffuse | ColorAttribute.Specular | TextureAttribute.Diffuse); */
	public final boolean has (final long type) {
		return type > 0 && (this.mask & type) == type;
	}

	/** @return the index of the attribute with the specified type or negative if not available. */
	protected int indexOf (final long type) {
		if (has(type)) for (int i = 0; i < attributes.size; i++)
			if (attributes.get(i).type == type) return i;
		return -1;
	}

	/** Check if this collection has the same attributes as the other collection. If compareValues is true, it also compares the
	 * values of each attribute.
	 * @param compareValues True to compare attribute values, false to only compare attribute types
	 * @return True if this collection contains the same attributes (and optionally attribute values) as the other. */
	public final boolean same (final Attributes other, boolean compareValues) {
		if (other == this) return true;
		if ((other == null) || (mask != other.mask)) return false;
		if (!compareValues) return true;
		sort();
		other.sort();
		for (int i = 0; i < attributes.size; i++)
			if (!attributes.get(i).equals(other.attributes.get(i))) return false;
		return true;
	}

	/** See {@link #same(Attributes, boolean)}
	 * @return True if this collection contains the same attributes (but not values) as the other. */
	public final boolean same (final Attributes other) {
		return same(other, false);
	}

	/** Used for sorting attributes */
	@Override
	public final int compare (final Attribute arg0, final Attribute arg1) {
		return (int)(arg0.type - arg1.type);
	}

	/** Used for iterating through the attributes */
	@Override
	public final Iterator<Attribute> iterator () {
		return attributes.iterator();
	}
}


text:
whereami=`pwd`
mkdir -p dist/client
cd ../../../src/server
yarn publish-local
cd $whereami
yarn yalc link federated-learning-server
if [ -e ../client ]
then
  cd ../client
  yarn build
  cp dist/* ../server/dist/client
  cd $whereami
fi


text:
package integration

import (
	"fmt"
	"net/http"
	"testing"
	"time"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/sclevine/agouti"

	"github.com/kinhouse/kh-site/server"
)

func TestKhSite(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "KhSite Suite")
}

var agoutiDriver *agouti.WebDriver

var baseUrl string

const port = 5555

var _ = BeforeSuite(func() {
	var err error

	// Choose a WebDriver:

	// agoutiDriver = agouti.PhantomJS()
	// agoutiDriver = agouti.Selenium()
	agoutiDriver = agouti.ChromeDriver()

	Expect(err).NotTo(HaveOccurred())
	Expect(agoutiDriver.Start()).To(Succeed())

	s := server.BuildServer()
	go s.Run(fmt.Sprintf(":%d", port))

	baseUrl = fmt.Sprintf("http://localhost:%d", port)
	waitToBoot(baseUrl)

})

var _ = AfterSuite(func() {
	agoutiDriver.Stop()
})

func waitToBoot(route string) {
	fmt.Printf("Waiting for server to boot on %s\n", route)
	timer := time.After(0 * time.Second)
	timeout := time.After(10 * time.Second)
	for {
		select {
		case <-timeout:
			panic("Failed to boot!")
		case <-timer:
			resp, err := http.Get(route)
			defer resp.Body.Close()
			if err == nil {
				fmt.Printf("Test server booted\n")
				return
			}
			timer = time.After(1 * time.Second)
		}
	}
}


text:
    [![Version](http://img.shields.io/npm/v/mu-sort.svg)](https://www.npmjs.org/package/mu-sort)
    [![Version](http://img.shields.io/bower/v/mu-sort.svg)](https://github.com/mu-lib/mu-sort)
    [![Build Status](https://api.travis-ci.org/mu-lib/mu-sort.svg?branch=master)](https://travis-ci.org/mu-lib/mu-sort)
    [![Coverage Status](https://img.shields.io/coveralls/mu-lib/mu-sort/master.svg)](https://coveralls.io/r/mu-lib/mu-sort)

# mu-sort

Sort an array with [Merge Sort](http://en.wikipedia.org/wiki/Merge_sort).

`sort(arr, order)`

0. `arr {Array}` - The source array.
0. `order {Function}` - A custom order function. Optional. If a function is specified, it is called with 2
   elements from the array and should return `0` if the are equal, a positive number if `a` is bigger and a negative
   number if `b` is bigger.

**Notes:**

0. `arr` is modified by the sort.
0. The sort is stable.
0. If the `this` value of the function is defined, it will be used as the array (see examples). Thus it is
   possible to use this function to extend the Array prototype: `Array.prototype.sort2 = sort`.
0. It's probably faster to use `Array.prototype.sort`, although:
    0. The sorting method is not guaranteed and is [implementation dependent](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11).
    0. [Stability is not guaranteed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).

## Installation

- Node:
    0. `npm install mu-sort`
    0. `var sort = require('mu-sort');`
- AMD (install with bower):
    0. `bower install mu-sort`
    0. `require(['mu-sort'], function(sort){ /* ... */ });`

Build AMD and CJS dists with `make build`.

Run tests with `make test`.

Run coverage analysis with `make coverage` (coverage report is saved to `./coverage`).

## Examples

```Javascript
var arr = [1, 2, 1, 2, 3];
console.log(sort(arr)); // [1, 1, 2, 2, 3]
```

**With a custom order:**

```Javascript
var arr = ['world', 'hi', 'hello'];
sort(arr, function(a, b){
    // sort by the first character
    return a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0;
});
console.log(arr); // ['hi', 'hello', 'world']
```

**By setting the `this` value:**

```Javascript
var arr = [1, 2, 1, 2, 3];
sort.call(arr);
console.log(sort(arr)); // [1, 1, 2, 2, 3]
```


text:
/**
 * Handle config.
 *
 * @file
 * @module
 *
 * @author hello@ulrichmerkel.com (Ulrich Merkel), 2021
 */
import pictureSizes from '../pictures';
import { configFeatured } from './featured';

const {
    sizes: { keyvisualWorkPrint: pictureSizesKeyvisualWorkPrint }
} = pictureSizes;
const IMG = '/img/';

export const configPageWorkRevolution = {
    head: {
        title: 'intl-work-revolution-head-title',
        meta: [
            {
                name: 'description',
                content: 'intl-work-revolution-description'
            },
            {
                property: 'og:description',
                content: 'intl-work-revolution-description'
            },
            {
                name: 'twitter:description',
                content: 'intl-work-revolution-description'
            },
            {
                name: 'dcterms.Title',
                content: 'intl-work-revolution-head-title'
            },
            {
                name: 'dcterms.Description',
                content: 'intl-work-revolution-description'
            }
        ]
    },
    section1: {
        headline: 'intl-work-revolution-headline',
        lead: 'intl-work-revolution-subline',
        img: {
            name: 'revolution--keyvisual',
            ext: 'png',
            path: `${IMG}content/work/revolution/`,
            alt: 'intl-work-revolution-alt',
            sizes: pictureSizesKeyvisualWorkPrint
        },
        btnTitle: 'intl-btn-scroll-down-title',
        btnLabel: 'intl-btn-scroll-down-label',
        type: 'print'
    },
    section2: {
        headline: 'intl-work-revolution-headline',
        lead: 'intl-work-revolution-lead',
        text: [
            {
                content: ['intl-work-revolution-description']
            }
        ],
        timeStart: '2010',
        btnTo: '/',
        btnTitle: 'intl-btn-back-to-start-page-title',
        btnLabel: 'intl-btn-back-to-start-page-label'
    },
    section3: configFeatured
};