text:
@interface JanyBaiduMapView ()<BMKMapViewDelegate>
{
    CLLocationCoordinate2D _dvCLLocation;//设备位置
    UIImage *_dvImage;//设备大头针图片
    NSObject *_dvInfor;//定位点相应气泡上的信息
    UIColor *_guijiLineColor;
    UIColor *_fenceStrokerColor;
    UIColor *_fenceFillColor;
    CGFloat _guijiLineWidth;

    UIImage *_startImage;
    UIImage *_endImage;
    UIImage *_middleImage;
    UIImage *_wifiImage;
    UIImage *_gpsImage;
    UIImage *_lbsImage;
    UIImage *_moveImage;
    UIImage *_fenceImage;
    UIImage *_guijiLineImage;
    NSArray *_guijiModelArray;
    NSMutableArray *_coordinate2DArray;

    NSInteger _clusterZoom;//聚合级别
    NSMutableArray *_clusterCaches;//点聚合缓存标注
}
@property (nonatomic, strong)BMKMapView *myMap;
@property (nonatomic, strong)UserLocation *myPosition;
@property (nonatomic, strong)JanyGeoCodeSearch *geoCodeSearch;
@property (nonatomic, strong)PointAnnotation *pointAnnotation;
@property (nonatomic, strong)PaopaoCustomView *locatePaopao;
@property (nonatomic, strong)BMKPolyline *guijiLine;
@property (nonatomic, strong)MovePolyline *movePolyLine;
@property (nonatomic, strong)MovePointAnnotation *movePointAnnotation;
@property (nonatomic, strong)BMKPinAnnotationView *animationPinAnnotationView;
@property (nonatomic, strong)FenceCentreAnnotation *fenceAnnotation;
@property (nonatomic, strong)BMKClusterManager *clusterManager;
@property (nonatomic, weak)ReverseAddressAndCoordinate geoBack;
@end

@implementation JanyBaiduMapView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _dvCLLocation = CLLocationCoordinate2DMake(11110, 111110);
        [self addSubview:self.myMap];

        [self initDataForMap];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        _dvCLLocation = CLLocationCoordinate2DMake(11110, 111110);
        [self addSubview:self.myMap];

        [self initDataForMap];

    }
    return self;
}

#pragma mark ============================== setupUI ==============================
- (BMKMapView *)myMap
{
    if (!_myMap) {

        _myMap = [[BMKMapView alloc]initWithFrame:self.bounds];
        [_myMap setShowsUserLocation:YES];
        [_myMap setRotateEnabled:NO];
        [_myMap setZoomLevel:15.f];
        [_myMap setDelegate:self];
    }

    return _myMap;
}

- (PointAnnotation *)pointAnnotation
{
    if (!_pointAnnotation) {
        _pointAnnotation = [[PointAnnotation alloc] init];
        [_pointAnnotation setTag:1];
    }

    return _pointAnnotation;
}

- (MovePointAnnotation *)movePointAnnotation
{
    if (!_movePointAnnotation) {
        _movePointAnnotation = [[MovePointAnnotation alloc] init];
    }

    return _movePointAnnotation;
}

- (FenceCentreAnnotation *)fenceAnnotation
{
    if (!_fenceAnnotation) {
        _fenceAnnotation = [[FenceCentreAnnotation alloc] init];
    }

    return _fenceAnnotation;
}

- (BMKPolyline *)guijiLine
{
    if (!_guijiLine) {
        _guijiLine = [[BMKPolyline alloc] init];
    }
    return _guijiLine;
}

- (MovePolyline *)movePolyLine
{
    if (!_movePolyLine) {
        _movePolyLine = [[MovePolyline alloc] init];
    }
    return _movePolyLine;
}

- (PaopaoCustomView *)locatePaopao
{
    if (!_locatePaopao) {
        _locatePaopao = [[PaopaoCustomView alloc] initWithFrame:CGRectMake(0.f, 0.f, 200.f, 100)];
    }
    return _locatePaopao;
}

- (BMKClusterManager *)clusterManager
{
    if (!_clusterManager) {
        _clusterManager = [[BMKClusterManager alloc] init];
    }
    return _clusterManager;
}

#pragma mark ============================== 初始化数据 ==============================
- (void)initDataForMap
{
    _coordinate2DArray = [NSMutableArray arrayWithCapacity:20];
    _guijiModelArray = [NSArray array];

}
#pragma mark ============================== 定位手机的当前位置 ==============================
- (UserLocation *)myPosition
{
    if (!_myPosition) {
        _myPosition = [[UserLocation alloc] initWithMap:_myMap];
    }

    return _myPosition;
}

#pragma mark ============================== 反转经纬度 ==============================
- (JanyGeoCodeSearch *)geoCodeSearch
{
    if (!_geoCodeSearch) {
        _geoCodeSearch = [[JanyGeoCodeSearch alloc] init];
    }
    return _geoCodeSearch;
}

#pragma mark ============================== delegate ==============================
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated//渲染完成后执行
{
    if (mapView.zoomLevel == 21) {
        //由于俯视角度变化和放大级别不能同时进行,所以这样操作
        [mapView setOverlooking:-45.f];
    }

    if (mapView.zoomLevel < 15) {
        [mapView setOverlooking:0];
    }

    [self moveMap:mapView];
}

- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    if (_animationPinAnnotationView.selected) {
        [_animationPinAnnotationView setSelected:NO animated:YES];
        [_animationPinAnnotationView.paopaoView removeFromSuperview];
    }
}

- (void)mapViewDidFinishLoading:(BMKMapView *)mapView
{
    if (_coordinate2DArray.count > 0) {
        [self updateClusters];
    }
}

- (void)mapView:(BMKMapView *)mapView onDrawMapFrame:(BMKMapStatus *)status {
    if (_clusterZoom != 0 && _clusterZoom != (NSInteger)mapView.zoomLevel && _coordinate2DArray.count > 0) {
        [self updateClusters];
    }
}

//根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[PointAnnotation class]]) {
        NSString *AnnotationViewID = @"deviceMark";
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];

            BMKActionPaopaoView *paopao=[[BMKActionPaopaoView alloc] initWithCustomView:self.locatePaopao];
            annotationView.paopaoView = paopao;
            [annotationView setCalloutOffset:CGPointMake(0, -10)];

            _animationPinAnnotationView = annotationView;
        }

        if (_dvImage) {
            annotationView.image = _dvImage;
        }else{
            annotationView.pinColor = BMKPinAnnotationColorGreen;
        }

        return annotationView;
    }

    if ([annotation isKindOfClass:[MovePointAnnotation class]]) {
        NSString *AnnotationViewID = @"moveMark";
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];

        }

        BMKActionPaopaoView *paopao=[[BMKActionPaopaoView alloc] initWithCustomView:[[PaopaoCustomView alloc] initWithFrame:CGRectMake(0.f, 0.f, 200.f, 100.f)]];
        annotationView.paopaoView = paopao;

        if (_moveImage) {
            annotationView.image = _moveImage;
        }else{
            annotationView.pinColor = BMKPinAnnotationColorGreen;
        }

        return annotationView;
    }

    if ([annotation isKindOfClass:[GuiJiAnnotation class]]) {

        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:annotation.coordinate.latitude ],@"lat",[NSNumber numberWithDouble:annotation.coordinate.longitude],@"lon", nil];

        NSString *AnnotationViewID = @"guijiMark";
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];

        }

        BMKActionPaopaoView *paopao = [[BMKActionPaopaoView alloc] initWithCustomView:[[PaopaoCustomView alloc] initWithFrame:CGRectMake(0.f, 0.f, 200.f, 100.f)]];
        annotationView.paopaoView = paopao;
        [annotationView setCalloutOffset:CGPointMake(0, -10)];

        if ([_coordinate2DArray indexOfObject:dic] == 0) {
            //轨迹起点
            if (_startImage) {
                annotationView.image = _startImage;
            }else{
                annotationView.pinColor = BMKPinAnnotationColorGreen;
            }

        }else if ([_coordinate2DArray indexOfObject:dic] == _coordinate2DArray.count - 1){
            //轨迹终点
            if (_endImage) {
                annotationView.image = _endImage;
            }else{
                annotationView.pinColor = BMKPinAnnotationColorRed;
            }

        }else{

            //中间点,如果要区分中间点的定位类型,可以根据_guijiModelArray的model类型来切换图片
            //NSLog(@"%d----%d",_coordinate2DArray.count,_guijiModelArray.count);
            NSUInteger index = [_coordinate2DArray indexOfObject:dic];
            NSAssert(index != NSNotFound, @"数组里面的数据还没有完全同步,造成数据不一致");
            if (index != NSNotFound) {

                Model *model = _guijiModelArray[index];

                if (model.type == 0) {
                    annotationView.image = _wifiImage;
                }else if (model.type == 1){
                    annotationView.image = _gpsImage;
                }else if (model.type == 2){
                    annotationView.image = _lbsImage;
                }else{
                    annotationView.image = _middleImage;
                }

            }

        }

        return annotationView;
    }

    if ([annotation isKindOfClass:[FenceCentreAnnotation class]]) {
        NSString *AnnotationViewID = @"fenceMark";
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];

        }

        CGRect endFrame = annotationView.frame;
        annotationView.frame = CGRectOffset(endFrame, 0.f, -30.f);
        [UIView animateWithDuration:2.f delay:0.f usingSpringWithDamping:0.3f initialSpringVelocity:0.f options:UIViewAnimationOptionLayoutSubviews animations:^{

            annotationView.frame = endFrame;
        } completion:^(BOOL finished) {

        }];

        if (_fenceImage) {
            annotationView.image = _fenceImage;
        }else{
            annotationView.pinColor = BMKPinAnnotationColorGreen;
        }

        return annotationView;
    }

    return nil;
}

//根据overlay生成对应的View
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]){

        BMKPolylineView *polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.lineWidth = _guijiLineWidth;

        if (_guijiLineColor) {

            polylineView.strokeColor = _guijiLineColor;

        }else{

            [polylineView loadStrokeTextureImage:_guijiLineImage];
        }

        return polylineView;
    }

    if ([overlay isKindOfClass:[BMKCircle class]]) {

        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.strokeColor = _fenceStrokerColor;
        circleView.fillColor = _fenceFillColor;
        circleView.lineWidth = 1.f;

        return circleView;
    }

    return nil;
}

- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    //走此函数说明有值
    if ([view.reuseIdentifier isEqualToString:@"deviceMark"]) {

        [UIView animateWithDuration:0.3f animations:^{
            view.transform = CGAffineTransformScale(view.transform, 1.2f, 1.2f);
        }];

    }else if([view.reuseIdentifier isEqualToString:@"guijiMark"]){

        PaopaoCustomView *linePaopao = view.paopaoView.subviews[0];

        [UIView animateWithDuration:0.3f animations:^{
            view.transform = CGAffineTransformScale(view.transform, 1.2f, 1.2f);
        }];

        [self.geoCodeSearch reverseWithCoordinate2D:view.annotation.coordinate success:^(BMKReverseGeoCodeResult *result) {
            [linePaopao setTitle:result.address];
        } fail:^(BMKSearchErrorCode error) {
            [linePaopao setTitle:@"反转失败"];
        }];
    }else if ([view.reuseIdentifier isEqualToString:@"moveMark"]){

        PaopaoCustomView *movePaopao = view.paopaoView.subviews[0];

        [self.geoCodeSearch reverseWithCoordinate2D:view.annotation.coordinate success:^(BMKReverseGeoCodeResult *result) {
            [movePaopao setTitle:result.address];
        } fail:^(BMKSearchErrorCode error) {
            [movePaopao setTitle:@"反转失败"];
        }];
    }
}

- (void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view
{
    if ([view.reuseIdentifier isEqualToString:@"deviceMark"]) {

        [UIView animateWithDuration:0.3f animations:^{
            view.transform = CGAffineTransformIdentity;
        }];

    }else if ([view.reuseIdentifier isEqualToString:@"guijiMark"]){

        [UIView animateWithDuration:0.3f animations:^{
            view.transform = CGAffineTransformIdentity;
        }];
    }
}

#pragma mark ============================== 返回地图可视区域 ==============================
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_myMap setVisibleMapRect:rect];
    _myMap.zoomLevel = _myMap.zoomLevel - 0.3;
}

#pragma mark ============================== 父类方法 ==============================
- (void)setMapDispalyType:(MapDisplayType)mapDispalyType
{
    switch (mapDispalyType) {
        case MapNormal:
            [_myMap setMapType:BMKMapTypeStandard];
            [_myMap setOverlooking:3.f];
            break;
        case MapSatellite:
            [_myMap setMapType:BMKMapTypeSatellite];
            [_myMap setOverlooking:3.f];
            break;
        case Map3D:
            [_myMap setMapType:BMKMapTypeStandard];
            [_myMap setZoomLevel:21];
            break;
        default:
            break;
    }
}

- (void)startLocationSuccess:(void (^)(void))success fail:(void (^)(NSError *))fail
{
    __weak typeof (self)weakSelf = self;
    [self.myPosition startLocationSuccess:^(CLLocationCoordinate2D ll) {
        success();

        if (CLLocationCoordinate2DIsValid(_dvCLLocation)) {

            CLLocationCoordinate2D coors[2];
            coors[0] = ll;
            coors[1] = _dvCLLocation;
            [weakSelf mapViewFitPolyLine:[BMKPolyline polylineWithCoordinates:coors count:2]];

        }else{

            CLLocationCoordinate2D coors[1];
            coors[0] = ll;
            [weakSelf mapViewFitPolyLine:[BMKPolyline polylineWithCoordinates:coors count:1]];
        }

    } fail:^(NSError *error) {
        fail(error);
    }];
}

- (void)stopLocation
{
    [self.myPosition stopLocation];
}

#pragma mark ============================== 定位 ==============================
- (void)jany_locateWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D Coordinate2DType:(Coordinate2DType)llType
{
    [self jany_locateWithCoordinate2D:coordinate2D Coordinate2DType:llType annotationImage:nil annotationInfor:nil success:nil fail:nil];
}

- (void)jany_locateWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D Coordinate2DType:(Coordinate2DType)llType annotationImage:(UIImage *)annotationImage
{
    [self jany_locateWithCoordinate2D:coordinate2D Coordinate2DType:llType annotationImage:annotationImage annotationInfor:nil success:nil fail:nil];
}

- (void)jany_locateWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D Coordinate2DType:(Coordinate2DType)llType success:(ReverseSuccess)success fail:(ReverseFail)fail
{
    [self jany_locateWithCoordinate2D:coordinate2D Coordinate2DType:llType annotationImage:nil annotationInfor:nil success:success fail:fail];
}

- (void)jany_locateWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D Coordinate2DType:(Coordinate2DType)llType annotationImage:(UIImage *)annotationImage success:(ReverseSuccess)success fail:(ReverseFail)fail
{
    [self jany_locateWithCoordinate2D:coordinate2D Coordinate2DType:llType annotationImage:annotationImage annotationInfor:nil success:success fail:fail];
}

- (void)jany_locateWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D Coordinate2DType:(Coordinate2DType)llType annotationImage:(UIImage *)annotationImage annotationInfor:(NSObject *)infor
{
    [self jany_locateWithCoordinate2D:coordinate2D Coordinate2DType:llType annotationImage:annotationImage annotationInfor:infor success:nil fail:nil];
}

- (void)jany_locateWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D Coordinate2DType:(Coordinate2DType)llType annotationImage:(UIImage *)annotationImage annotationInfor:(NSObject *)infor success:(ReverseSuccess)success fail:(ReverseFail)fail
{
    if (llType == Wgs84) {//坐标转换
        _dvCLLocation = [JZLocationConverter wgs84ToBd09:coordinate2D];
    }else if (llType == Gcj02){
        _dvCLLocation = [JZLocationConverter gcj02ToBd09:coordinate2D];
    }else{
        _dvCLLocation = coordinate2D;
    }

    _dvImage = annotationImage;
    _dvInfor = infor;

    [_myMap setCenterCoordinate:_dvCLLocation animated:YES];

    [self.pointAnnotation setCoordinate:_dvCLLocation];
    [_myMap addAnnotation:_pointAnnotation];

    if (success && fail) {

        [self.geoCodeSearch reverseWithCoordinate2D:_dvCLLocation success:^(BMKReverseGeoCodeResult *result) {
            success(result.address);
            [_locatePaopao setTitle:result.address];
        } fail:^(BMKSearchErrorCode error) {
            fail();
            [_locatePaopao setTitle:@"反转失败"];
        }];
    }

    //大头针动画
    CGRect endFrame = _animationPinAnnotationView.frame;
    _animationPinAnnotationView.frame = CGRectOffset(endFrame, 0.f, -30.f);
    [UIView animateWithDuration:2.f delay:0.f usingSpringWithDamping:0.3f initialSpringVelocity:0.f options:UIViewAnimationOptionLayoutSubviews animations:^{

        _animationPinAnnotationView.frame = endFrame;
    } completion:^(BOOL finished) {

    }];

}

#pragma mark ============================== 轨迹操作 ==============================
- (void)jany_pathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType startImage:(UIImage *)startImage endImage:(UIImage *)endImage
{
    [self jany_pathMoveWithData:dataArr coordinate2DType:llType startImage:startImage middleImage:nil endImage:endImage lineWidth:4 lineColor:[UIColor redColor]];
}
- (void)jany_pathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType startImage:(UIImage *)startImage middleImage:(UIImage *)img endImage:(UIImage *)endImage
{
    [self jany_pathMoveWithData:dataArr coordinate2DType:llType startImage:startImage middleImage:img endImage:endImage lineWidth:4 lineColor:[UIColor redColor]];
}

- (void)jany_pathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType startImage:(UIImage *)startImage wifiImgae:(UIImage *)wifiImgae gpsImage:(UIImage *)gpsImage lbsImage:(UIImage *)lbsImage endImage:(UIImage *)endImage
{
    [self jany_pathMoveWithData:dataArr coordinate2DType:llType startImage:startImage wifiImgae:wifiImgae gpsImage:gpsImage lbsImage:lbsImage endImage:endImage lineWidth:4 lineColor:[UIColor redColor]];

}

- (void)jany_imagePathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType startImage:(UIImage *)startImage middleImage:(UIImage *)img endImage:(UIImage *)endImage lineWidth:(CGFloat)width lineImage:(UIImage *)lineImage
{
    _guijiLineImage = lineImage;
    [self jany_pathMoveWithData:dataArr coordinate2DType:llType startImage:startImage middleImage:img endImage:endImage lineWidth:width lineColor:nil];
}

- (void)jany_imagePathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType startImage:(UIImage *)startImage wifiImgae:(UIImage *)wifiImgae gpsImage:(UIImage *)gpsImage lbsImage:(UIImage *)lbsImage endImage:(UIImage *)endImage lineWidth:(CGFloat)width lineImage:(UIImage *)lineImage
{
    _guijiLineImage = lineImage;

    [self jany_pathMoveWithData:dataArr coordinate2DType:llType startImage:startImage wifiImgae:wifiImgae gpsImage:gpsImage lbsImage:lbsImage endImage:endImage lineWidth:width lineColor:nil];
}

- (void)jany_pathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType startImage:(UIImage *)startImage middleImage:(UIImage *)img endImage:(UIImage *)endImage lineWidth:(CGFloat)width lineColor:(UIColor *)lineColor
{
    _startImage = startImage;
    _endImage = endImage;
    _middleImage = img;
    _guijiLineWidth = width;
    _guijiLineColor = lineColor;

    _wifiImage = nil;
    _gpsImage = nil;
    _lbsImage = nil;

    if (img) {

        @synchronized (dataArr) {

            [self guijiAnnotation:dataArr coordinate2DType:llType];
        }
    }else{

        @synchronized (dataArr) {

            [self guijiNoAnnotation:dataArr coordinate2DType:llType];
        }
    }
}

- (void)jany_pathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType startImage:(UIImage *)startImage wifiImgae:(UIImage *)wifiImgae gpsImage:(UIImage *)gpsImage lbsImage:(UIImage *)lbsImage endImage:(UIImage *)endImage lineWidth:(CGFloat)width lineColor:(UIColor *)lineColor
{
    _wifiImage = wifiImgae;
    _gpsImage = gpsImage;
    _lbsImage = lbsImage;
    _startImage = startImage;
    _endImage = endImage;
    _middleImage = nil;
    _guijiLineWidth = width;
    _guijiLineColor = lineColor;

    if (wifiImgae || gpsImage || lbsImage) {

        @synchronized (dataArr) {

            [self guijiAnnotation:dataArr coordinate2DType:llType];
        }

    }else{

        @synchronized (dataArr) {

            [self guijiNoAnnotation:dataArr coordinate2DType:llType];
        }
    }
}

- (void)jany_pathMoveWithData:(NSArray *)dataArr coordinate2DType:(Coordinate2DType)llType moveImage:(UIImage *)moveImage lineWidth:(CGFloat)width lineColor:(UIColor *)lineColor
{
    if (dataArr.count == 0) {
        [_myMap removeAnnotation:_movePointAnnotation];
        return;
    }

    @synchronized(dataArr){

        CLLocationCoordinate2D coors[dataArr.count];
        for (int i = 0; i < dataArr.count; i ++) {

            Model *model = dataArr[i];
            CLLocationCoordinate2D LL = CLLocationCoordinate2DMake(model.lat,model.lon);
            if (llType == Wgs84) {//坐标转换
                LL = [JZLocationConverter wgs84ToBd09:LL];
            }else if (llType == Gcj02){
                LL = [JZLocationConverter gcj02ToBd09:LL];
            }else{
                LL = LL;
            }

            coors[i] = LL;
        }

        _moveImage = moveImage;
        _guijiLineWidth = width;
        _guijiLineColor = lineColor;

        CLLocationCoordinate2D lastLL = coors[dataArr.count - 1];

        if ([self.movePolyLine setPolylineWithCoordinates:coors count:dataArr.count]) {
            [_myMap addOverlay: _movePolyLine];
        }

        [UIView animateWithDuration:0.5 animations:^{

            [self.movePointAnnotation setCoordinate:lastLL];

        } completion:^(BOOL finished) {

            [_myMap addAnnotation:_movePointAnnotation];

        }];
    }
}

- (void)guijiNoAnnotation:(NSArray *)arr coordinate2DType:(Coordinate2DType)llType
{
    [_myMap removeOverlays:_myMap.overlays];
    [_myMap removeAnnotations:_myMap.annotations];

    NSMutableArray *guijiAnnotationArray = [NSMutableArray array];
    CLLocationCoordinate2D coors[arr.count];
    [_coordinate2DArray removeAllObjects];

    for (int i = 0; i < arr.count; i ++) {

        Model *model = arr[i];
        CLLocationCoordinate2D LL = CLLocationCoordinate2DMake(model.lat,model.lon);

        if (llType == Wgs84) {//坐标转换
            LL = [JZLocationConverter wgs84ToBd09:LL];
        }else if (llType == Gcj02){
            LL = [JZLocationConverter gcj02ToBd09:LL];
        }else{
            LL = LL;
        }

        coors[i] = LL;

        if (i == 0 || i == arr.count - 1) {

            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:model.lat],@"lat",[NSNumber numberWithDouble:model.lon],@"lon", nil];
            [_coordinate2DArray addObject:dic];

            GuiJiAnnotation *annotation = [[GuiJiAnnotation alloc] init];
            [annotation setCoordinate:LL];
            [guijiAnnotationArray addObject:annotation];
        }
    }

    _guijiModelArray = [arr copy];
    [_myMap addAnnotations:guijiAnnotationArray];

    if ([self.guijiLine setPolylineWithCoordinates:coors count:arr.count]) {
        [_myMap addOverlay: _guijiLine];
        [self mapViewFitPolyLine:_guijiLine];
    }

    [guijiAnnotationArray removeAllObjects];
}

- (void)guijiAnnotation:(NSArray *)arr coordinate2DType:(Coordinate2DType)llType
{
    [_myMap removeOverlays:_myMap.overlays];
    [_myMap removeAnnotations:_myMap.annotations];
    [self.clusterManager clearClusterItems];

    [_coordinate2DArray removeAllObjects];
    [_clusterCaches removeAllObjects];
    CLLocationCoordinate2D coors[arr.count];

    _clusterCaches = [[NSMutableArray alloc] init];
    for (NSInteger i = 3; i < 22; i++) {
        [_clusterCaches addObject:[NSMutableArray array]];
    }

    for (int i = 0; i < arr.count; i ++) {

        Model *model = arr[i];
        CLLocationCoordinate2D LL = CLLocationCoordinate2DMake(model.lat,model.lon);

        if (llType == Wgs84) {//坐标转换
            LL = [JZLocationConverter wgs84ToBd09:LL];
        }else if (llType == Gcj02){
            LL = [JZLocationConverter gcj02ToBd09:LL];
        }else{
            LL = LL;
        }

        coors[i] = LL;

        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:model.lat],@"lat",[NSNumber numberWithDouble:model.lon],@"lon", nil];
        [_coordinate2DArray addObject:dic];

        BMKClusterItem *clusterItem = [[BMKClusterItem alloc] init];
        clusterItem.coor = LL;
        [self.clusterManager addClusterItem:clusterItem];
    }

    _guijiModelArray = [arr copy];
    [self updateClusters];

    if ([self.guijiLine setPolylineWithCoordinates:coors count:arr.count]) {
        [_myMap addOverlay: _guijiLine];
        [self mapViewFitPolyLine:_guijiLine];
    }
}

#pragma mark ============================== 更新聚合状态 ==============================
- (void)updateClusters {

    _clusterZoom = (NSInteger)_myMap.zoomLevel;
    @synchronized(_clusterCaches) {
        __block NSMutableArray *clusters = [_clusterCaches objectAtIndex:(_clusterZoom - 3)];

        if (clusters.count > 0) {
            [_myMap removeAnnotations:_myMap.annotations];
            [_myMap addAnnotations:clusters];
        } else {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{

                ///获取聚合后的标注
                __block NSArray *array = [_clusterManager getClusters:_clusterZoom];

                dispatch_async(dispatch_get_main_queue(), ^{
                    for (BMKCluster *item in array) {
                        GuiJiAnnotation *annotation = [[GuiJiAnnotation alloc] init];
                        [annotation setCoordinate:item.coordinate];
                        [clusters addObject:annotation];
                    }
                    [_myMap removeAnnotations:_myMap.annotations];
                    [_myMap addAnnotations:clusters];
                });
            });
        }
    }
}

- (void)jany_cleanAllPath
{
    [_coordinate2DArray removeAllObjects];
    [_myMap removeOverlays:_myMap.overlays];
    [_myMap removeAnnotations:_myMap.annotations];
}

CLLocationCoordinate2D myFenceCoordinate;
Coordinate2DType myFenceType;
CGFloat myRadiu;
#pragma mark ============================== 电子围栏 ==============================
- (void)jany_drawFenceWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D coordinate2DType:(Coordinate2DType)llType centreImage:(UIImage *)centreImage radiu:(CGFloat)radiu lineColor:(UIColor *)lineColor coverColor:(UIColor *)coverColor
{
    [self jany_drawFenceWithCoordinate2D:coordinate2D coordinate2DType:llType centreImage:centreImage radiu:radiu lineColor:lineColor coverColor:coverColor success:nil fail:nil];
}

- (void)jany_drawFenceWithCoordinate2D:(CLLocationCoordinate2D)coordinate2D coordinate2DType:(Coordinate2DType)llType centreImage:(UIImage *)centreImage radiu:(CGFloat)radiu lineColor:(UIColor *)lineColor coverColor:(UIColor *)coverColor success:(ReverseAddressAndCoordinate)success fail:(ReverseFail)fail
{
    myFenceType = llType;
    myRadiu = radiu;
    if (llType == Wgs84) {//坐标转换
        coordinate2D = [JZLocationConverter wgs84ToBd09:coordinate2D];
    }else if (llType == Gcj02){
        coordinate2D = [JZLocationConverter gcj02ToBd09:coordinate2D];
    }else{
        coordinate2D = coordinate2D;
    }

    myFenceCoordinate = coordinate2D;
    _fenceStrokerColor = lineColor;
    _fenceFillColor = coverColor;
    _fenceImage = centreImage;

    NSArray *objArr = _myMap.overlays;
    for (NSObject *obj in objArr) {

        if ([obj isKindOfClass:[BMKCircle class]]) {
            BMKCircle *fenceCircle = (BMKCircle *)obj;
            [_myMap removeOverlay:fenceCircle];
        }
    }

    BMKCircle *fenceCircle = [BMKCircle circleWithCenterCoordinate:coordinate2D radius:radiu];
    [_myMap addOverlay:fenceCircle];

    [self.fenceAnnotation setCoordinate:coordinate2D];
    [_myMap addAnnotation:_fenceAnnotation];
    [_myMap setCenterCoordinate:coordinate2D animated:YES];

    if (success && fail) {

        [self.geoCodeSearch reverseWithCoordinate2D:coordinate2D success:^(BMKReverseGeoCodeResult *result) {
            success(coordinate2D,result.address);
        } fail:^(BMKSearchErrorCode error) {
            fail();
        }];
    }

    _geoBack = success;
}

- (void)jany_setRadiu:(CGFloat)radiu
{
    NSArray *objArr = _myMap.overlays;
    for (NSObject *obj in objArr) {

        if ([obj isKindOfClass:[BMKCircle class]]) {
            BMKCircle *fenceCircle = (BMKCircle *)obj;
            [fenceCircle setCircleWithCenterCoordinate:myFenceCoordinate radius:radiu];
        }
    }
}

- (void)moveMap:(BMKMapView *)mapView
{
    if (_geoBack) {

        CLLocationCoordinate2D coordinate2D = mapView.centerCoordinate;

        if (myFenceType == Wgs84) {//坐标转换
            coordinate2D = [JZLocationConverter wgs84ToBd09:coordinate2D];
        }else if (myFenceType == Gcj02){
            coordinate2D = [JZLocationConverter gcj02ToBd09:coordinate2D];
        }else{
            coordinate2D = coordinate2D;
        }

        myFenceCoordinate = coordinate2D;

        NSArray *objArr = _myMap.overlays;
        for (NSObject *obj in objArr) {

            if ([obj isKindOfClass:[BMKCircle class]]) {
                BMKCircle *fenceCircle = (BMKCircle *)obj;
                [fenceCircle setCircleWithCenterCoordinate:coordinate2D radius:myRadiu];
            }
        }

        [self.fenceAnnotation setCoordinate:coordinate2D];
        [_myMap addAnnotation:_fenceAnnotation];
        [_myMap setCenterCoordinate:coordinate2D animated:YES];
    }
}

- (void)jany_drawFenceWithCoordinate2D:(NSArray *)fenceArrary coordinate2DType:(Coordinate2DType)llType images:(NSArray *)imageArrary objectModelLatKey:(NSString *)latKey objectModelonKey:(NSString *)lonKey objectModelRadiuKey:(NSString *)radiuKey lineColor:(UIColor *)lineColor coverColor:(UIColor *)coverColor
{
    CLLocationCoordinate2D coors[fenceArrary.count];
    _fenceStrokerColor = lineColor;
    _fenceFillColor = coverColor;

    NSArray *objArr = _myMap.overlays;
    for (NSObject *obj in objArr) {

        if ([obj isKindOfClass:[BMKCircle class]]) {
            BMKCircle *fenceCircle = (BMKCircle *)obj;
            [_myMap removeOverlay:fenceCircle];
        }
    }

    NSArray *objAnnotations = _myMap.annotations;
    for (NSObject *obj in objAnnotations) {
        if ([obj isKindOfClass:[FenceCentreAnnotation class]]) {
            FenceCentreAnnotation *fenceAnnotation = (FenceCentreAnnotation *)obj;
            [_myMap removeAnnotation:fenceAnnotation];
        }
    }

    for (int i = 0; i < fenceArrary.count; i ++) {

        NSObject *fenceModel = fenceArrary[i];
        NSString *latValue = [fenceModel valueForKey:latKey];
        NSString *lonValue = [fenceModel valueForKey:lonKey];
        NSString *radiuValue = [fenceModel valueForKey:radiuKey];
        CLLocationCoordinate2D LL = CLLocationCoordinate2DMake(latValue.doubleValue,lonValue.doubleValue);

        if (llType == Wgs84) {//坐标转换
            LL = [JZLocationConverter wgs84ToBd09:LL];
        }else if (llType == Gcj02){
            LL = [JZLocationConverter gcj02ToBd09:LL];
        }else{
            LL = LL;
        }
        _fenceImage = [UIImage imageNamed:imageArrary[i]];

        coors[i] = LL;

        FenceCentreAnnotation *annotation = [[FenceCentreAnnotation alloc] init];
        [annotation setCoordinate:LL];
        [_myMap addAnnotation:annotation];

        BMKCircle *fenceCircle = [BMKCircle circleWithCenterCoordinate:LL radius:radiuValue.floatValue];
        [_myMap addOverlay:fenceCircle];
    }

    [self mapViewFitPolyLine:[BMKPolyline polylineWithCoordinates:coors count:fenceArrary.count]];

}
@end


text:
package pl.org.tomaszjaneczko.mouproject.math;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Class representing a parametrised polynomial.
 * Form:
 * x^k * (A*a1 + B*a2 + ...) + x^(k-1) * (A*b1 + ...) +
 *
 * Examples:
 * Ax^2 + Bx + C
 * (A - B)x^2 + (C-A)x + B + A
 *
 * @author tomaszj
 *
 */
public class ParametrisedPolynomial {

    /** Array of parameters stored as strings. */
    private String[] params;

    /** Array representing linear combinations of parameters to reflect the polynomial. */
    private Double[][] paramValues;

    /**
     * Constructor, creating polynomial of form:
     * params[0] * x^k + params[1] * x^(k-1) + ... + params[k]
     * @param parameters - Array of params
     */
    public ParametrisedPolynomial(final String[] parameters) {
        params = parameters;

        int matrixSize = parameters.length;

        paramValues = createZeroMatrixForDegreeAndParamsCount(matrixSize - 1, matrixSize);

        for (int i = 0; i < matrixSize; i++) {
            paramValues[i][i] = 1.0;
        }
    }

    /**
     * Protected constructor for creating a zero polynomial for given parameters.
     * @param size number of parameters and degree-1 at the same time
     */
    protected ParametrisedPolynomial(final int size) {
        params = new String[size];

        paramValues = createZeroMatrixForDegreeAndParamsCount(size - 1, size);
    }

    /**
     * Constructor creating a parametrised polynomial of a given degree with
     * specific number of parameters.
     *
     * @param degree of a polynomial
     * @param paramsCount Count of parameters used. They still need to be set!
     */
    protected ParametrisedPolynomial(final int degree, final int paramsCount) {
        params = new String[paramsCount];

        paramValues = createZeroMatrixForDegreeAndParamsCount(degree, paramsCount);
    }

    /**
     * Method returns params used in the polynomial.
     * @return params used in polynomial
     */
    public final String[] getParams() {
        return params;
    }

    /**
     * Param values for a given degree of a polynomial.
     * @param degree of a polynomial component
     * @return map representing a linear combination of parameters
     */
    public final Map<String, Double> getParamValuesForDegree(final int degree) {

        Map<String, Double> paramsMap = new HashMap<String, Double>();
        int indexOfDegree = getPolynomialDegree() - degree;

        for (int i = 0; i < params.length; i++) {
            paramsMap.put(params[i], paramValues[indexOfDegree][i]);
        }

        return paramsMap;
    }

    /**
     * Param values for a given degree of a polynomial.
     * @param degree of a polynomial component
     * @return array representing a linear combination of parameters
     */
    public final Double[] getParamValuesForDegreeAsArray(final int degree) {

        Double[] result = new Double[params.length];

        int indexOfDegree = getPolynomialDegree() - degree;

        for (int i = 0; i < params.length; i++) {
            result[i] = paramValues[indexOfDegree][i];
        }

        return result;
    }

    /**
     * Method adds two parametrised polynomials, summing appropriate parameters.
     * @param poly to be added
     * @return sum of two polynomials
     */
    public final ParametrisedPolynomial add(final ParametrisedPolynomial poly) {
        ParametrisedPolynomial resultPoly = new ParametrisedPolynomial(getPolynomialDegree(), params.length);

        if (!Arrays.equals(params, poly.params) || getPolynomialDegree() != poly.getPolynomialDegree()) {
            // Throw an exception if arrays aren't equal
            throw new IllegalArgumentException("Param arrays should be the same!");
        }

        resultPoly.params = params;

        for (int i = 0; i <= getPolynomialDegree(); i++) {
            for (int j = 0; j < params.length; j++) {
                resultPoly.paramValues[i][j] = paramValues[i][j] + poly.paramValues[i][j];
            }
        }

        return resultPoly;
    }

    /**
     * Method multiplies a polynomial by a given scalar.
     * @param scalar used to multiply
     * @return multiplied polynomial
     */
    public final ParametrisedPolynomial multiplyByScalar(final double scalar) {
        ParametrisedPolynomial resultPoly = new ParametrisedPolynomial(
                getPolynomialDegree(), params.length);

        resultPoly.params = params;

        for (int i = 0; i <= getPolynomialDegree(); i++) {
            for (int j = 0; j < params.length; j++) {
                resultPoly.paramValues[i][j] = paramValues[i][j] * scalar;
            }
        }

        return resultPoly;
    }

    /**
     * Method multiplies the parametrised polynomial by a polynomial given.
     * @param polynomial to be used for multiplication
     * @return multiplied parametrised polynomial
     */
    public final ParametrisedPolynomial multiplyByPolynomial(final Polynomial polynomial) {
        int polynomialDegree = polynomial.getDegree();

        // Extend the polynomial to appropriate size.
        ParametrisedPolynomial resultPoly = new ParametrisedPolynomial(
                getPolynomialDegree() + polynomialDegree, params.length);
        resultPoly.params = params;

        for (int polynomialDegreeIndex = 0; polynomialDegreeIndex <= polynomialDegree; polynomialDegreeIndex++) {
            ParametrisedPolynomial scaledPoly = this.multiplyByScalar(polynomial
                    .getCoefficientForDegree(polynomialDegreeIndex));

            for (int i = 0; i <= getPolynomialDegree(); i++) {
                for (int j = 0; j < params.length; j++) {
                    resultPoly.paramValues[i + polynomialDegree
                                           - polynomialDegreeIndex][j] += scaledPoly.paramValues[i][j];
                }
            }
        }

        return resultPoly;
    }

    /**
     * Method returns a matrix of all values.
     * @return matrix of all params for given degrees
     */
    public final Double[][] getParamMatrix() {
        return paramValues;
    }

    /**
     * Method differentiating a polynomial and returning its derived version.
     * @return differentiated polynomial
     */
    public final ParametrisedPolynomial differentiate() {
        ParametrisedPolynomial resultPoly = new ParametrisedPolynomial(
                getPolynomialDegree(), params.length);
        resultPoly.params = params;

        for (int powerIndex = 0; powerIndex <= getPolynomialDegree() - 1; powerIndex++) {
            int powerValue = getPolynomialDegree() - powerIndex;

            for (int j = 0; j < params.length; j++) {
                resultPoly.paramValues[powerIndex + 1][j] = powerValue * paramValues[powerIndex][j];
            }
        }

        return resultPoly;
    }

    /**
     * Method evaluates Parametrised Polynomial using given values and returns respective polynomial.
     * @param values of consecutive parameters
     * @return evaluated polynomial
     */
    public final Polynomial getPolynomialForParameterValues(final Double[] values) {
        Double[] coefficients = new Double[paramValues.length];

        if (params.length != values.length) {
            throw new IllegalArgumentException("Parameters and values arrays don't match!");
        }

        for (int i = 0; i < paramValues.length; i++) {

            double sum = 0;
            for (int j = 0; j < params.length; j++) {
                sum += paramValues[i][j] * values[j];
            }

            coefficients[i] = sum;
        }

        return new Polynomial(coefficients);
    }

    /**
     * Factory method used to create a zero polynomial using given parameters.
     * @param params Parameters used in a polynomial
     * @return zero parametrised polynomial
     */
    public static ParametrisedPolynomial zeroPolynomial(final String[] params) {
        ParametrisedPolynomial poly = new ParametrisedPolynomial(params.length);
        poly.params = params;

        return poly;
    }

    /**
     * Method creates an array of default params for given count. It's in the form of "a1", "a2", "a3", etc.
     * @param count of params requested
     * @return list of params
     */
    public static String[] getDefaultParamsOfCount(final int count) {
        String[] params = new String[count];
        for (int i = 0; i < count; i++) {
            params[i] = "a" + String.valueOf(i + 1);
        }

        return params;
    }

    /**
     * Method creates a matrix with all elements set to zero.
     * @param degree of a polynomial
     * @param paramsCount count of params used
     * @return zero matrix
     */
    private Double[][] createZeroMatrixForDegreeAndParamsCount(final int degree, final int paramsCount) {

        Double[][] zeroMatrix = new Double[degree + 1][paramsCount];

        // Zero the values of the matrix
        for (Double[] row : zeroMatrix) {
            Arrays.fill(row, 0.0);
        }

        return zeroMatrix;
    }

    /**
     * Method returns a polynomial degree.
     * @return polynomial degree
     */
    private int getPolynomialDegree() {
        if (paramValues.length == 0) {
            return 0;
        } else {
            return paramValues.length - 1; // Number of rows determines the degree of a polynomial
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
import sys
import re
import json
import time
import traceback
import logging
import logging.handlers

from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
from lxml.html.clean import Cleaner
import requests

headers = {}
headers['Accept-Language'] = 'zh-CN,zh;q=0.8'
headers['User-Agent'] = 'User-AgentMozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'

"""
transform 'YYYY-mm-dd' date to seconds since the Epoch
"""
def getEpoch(adate):
    return int(time.mktime(time.strptime(adate,'%Y-%m-%d')))

def get_file_logger(name, logfilepath):
    alogger = logging.getLogger(name)
    alogger.setLevel(logging.DEBUG)
    fh = logging.handlers.RotatingFileHandler(logfilepath, 'a', 104857600)
    fh.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
    fh.setFormatter(formatter)
    alogger.addHandler(fh)

    return alogger

logger = get_file_logger('stk', 'w.log')

def start_watch(code):
    stime = int(time.time())
    stime2 = stime
    now_price = 0
    now_vol = 0
    last_vol = None
    five_min_ago_vol = None
    three_second_delta_vol = None
    last_three_second_delta_vol = None
    five_min_delta_vol = None
    last_five_min_delta_vol = None

    sh_now_vol = 0
    sh_last_vol = None
    sh_five_min_ago_vol = None
    sh_three_second_delta_vol = None
    sh_last_three_second_delta_vol = None
    sh_five_min_delta_vol = None
    sh_last_five_min_delta_vol = None

    sz_now_vol = 0
    sz_last_vol = None
    sz_five_min_ago_vol = None
    sz_three_second_delta_vol = None
    sz_last_three_second_delta_vol = None
    sz_five_min_delta_vol = None
    sz_last_five_min_delta_vol = None

    while True:
        result = grab_detail(code)
        now_price = result['realPrice']
        now_vol = result['itaa']
        if last_vol is None:
            last_vol = now_vol
        if five_min_ago_vol is None:
            five_min_ago_vol = now_vol

        three_second_vol_rate = 0
        three_second_delta_vol = now_vol - last_vol
        if last_three_second_delta_vol is None:
            last_three_second_delta_vol = three_second_delta_vol

        if last_three_second_delta_vol > 0:
            three_second_vol_rate = round((three_second_delta_vol-last_three_second_delta_vol)/float(last_three_second_delta_vol),3)

        last_vol = now_vol
        last_three_second_delta_vol = three_second_delta_vol

        sh_now_vol = int(result['sh_vol'])
        if sh_last_vol is None:
            sh_last_vol = sh_now_vol
        if sh_five_min_ago_vol is None:
            sh_five_min_ago_vol = sh_now_vol

        sh_three_second_vol_rate = 0
        sh_three_second_delta_vol = sh_now_vol - sh_last_vol
        if sh_last_three_second_delta_vol is None:
            sh_last_three_second_delta_vol = sh_three_second_delta_vol

        if sh_last_three_second_delta_vol > 0:
            sh_three_second_vol_rate = round((sh_three_second_delta_vol-sh_last_three_second_delta_vol)/float(sh_last_three_second_delta_vol),3)

        sh_last_vol = sh_now_vol
        sh_last_three_second_delta_vol = sh_three_second_delta_vol

        now_time = int(time.time())
        pass_time = now_time - stime2
        five_min_delta_vol = 0
        five_min_vol_rate = 0

        sh_five_min_delta_vol = 0
        sh_five_min_vol_rate = 0

        sz_five_min_delta_vol = 0
        sz_five_min_vol_rate = 0

        if pass_time == 60: #use 1 min
            stime2 = now_time
            five_min_delta_vol = now_vol - five_min_ago_vol
            if last_five_min_delta_vol is None:
                last_five_min_delta_vol = five_min_delta_vol
            if last_five_min_delta_vol > 0:
                five_min_vol_rate = round((five_min_delta_vol - last_five_min_delta_vol) / float(last_five_min_delta_vol), 3)

            five_min_ago_vol = now_vol
            last_five_min_delta_vol = five_min_delta_vol

            sh_five_min_delta_vol = sh_now_vol - sh_five_min_ago_vol
            if sh_last_five_min_delta_vol is None:
                sh_last_five_min_delta_vol = sh_five_min_delta_vol
            if sh_last_five_min_delta_vol > 0:
                sh_five_min_vol_rate = round((sh_five_min_delta_vol - sh_last_five_min_delta_vol) / float(sh_last_five_min_delta_vol), 3)

            sh_five_min_ago_vol = sh_now_vol
            sh_last_five_min_delta_vol = sh_five_min_delta_vol

        print code+","+result['realPrice']+'/'+result['changeAmt']+'/'+result['changeRate']+','+\
            result['itba']+'|'+result['itbc']+'~'+result['itbd']+','+\
            str(result['itaa'])+'/'+str(result['itab'])+'/'+result['itca']+','+str(three_second_delta_vol)+'/'+str(three_second_vol_rate)+\
            ','+str(five_min_delta_vol)+'/'+str(five_min_vol_rate)+','+\
            result['sh_zs']+'/'+result['sh_changeAmt']+'/'+result['sh_changeRate']+','+result['sh_vol']+'/'+str(sh_three_second_delta_vol)+'/'+str(sh_three_second_vol_rate)+'/'+str(sh_five_min_delta_vol)+'/'+str(sh_five_min_vol_rate)+','+\
            result['sz_zs']+'/'+result['sz_changeAmt']+'/'+result['sz_changeRate']+','+result['sz_vol']

        time.sleep(3)

def grab_detail(code):
    url = 'http://hqdigi2.eastmoney.com/EM_Quote2010NumericApplication/CompatiblePage.aspx?Type=f&jsName=js&stk=%s1&Reference=xml&rt=0.%s' % (code,int(time.time()))
    print url
    if code[0] == '0' or code[0] == '3':
        url = 'http://hqdigi2.eastmoney.com/EM_Quote2010NumericApplication/CompatiblePage.aspx?Type=f&jsName=js&stk=%s2&Reference=xml&rt=0.%s' % (code,int(time.time()))

    res = requests.get(url, allow_redirects=False, headers=headers)
    if res.status_code == 200:
        left = res.text.find('{')
        right = res.text.find('}')
        skif = "skif"
        bsif = "bsif"
        dtif = "dtif"
        idsyif = "idsyif"
        dpif = "dpif"
        idsif = "idsif"
        content = eval(res.text[left:right+1])
        d = content[skif].split(',')
        for i in range(len(d)):
            pass
            #print 'd[',i,']=',d[i]

        output = {}
        output['realPrice'] = d[3]
        output['changeAmt'] = d[4]
        output['changeRate'] = d[5]
        output['itaa'] = int(d[17])
        output['itab'] = int(d[19])
        output['itba'] = d[8]
        output['itbb'] = d[9]
        output['itbc'] = d[10]
        output['itbd'] = d[11]
        output['itca'] = d[12]

        szzs = content[dpif][0].split(',')
        szcz = content[dpif][1].split(',')

        for i in range(len(szcz)):
            pass
            #print 'szcz[',i,']=',szcz[i]

        output['sh_zs'] = szzs[3]
        output['sh_changeAmt'] = szzs[4]
        output['sh_changeRate'] = szzs[5]
        output['sh_vol'] = szzs[6]

        output['sz_zs'] = szcz[3]
        output['sz_changeAmt'] = szcz[4]
        output['sz_changeRate'] = szcz[5]
        output['sz_vol'] = szcz[6]

        return output

        #output['itca'] = soup.find(id='itca').text

        """
        cleaner = Cleaner(page_structure=False)
        #soup = BeautifulSoup(cleaner.clean_html(res.text), "lxml")
        soup = BeautifulSoup(res.text, "lxml")
        print soup.find(od='maintop')
        output = {}
        output['realprice'] = soup.find(id='realprice').text
        output['changeAmt'] = soup.find(id='changeAmt').text
        output['changeRate'] = soup.find(id='changeRate').text
        output['itaa'] = int(soup.find(id='itaa').text)
        output['itab'] = int(soup.find(id='itab').text)
        output['itba'] = soup.find(id='itba').text
        output['itbb'] = soup.find(id='itbb').text
        output['itbc'] = soup.find(id='itbc').text
        output['itbd'] = soup.find(id='itbd').text
        output['itca'] = soup.find(id='itca').text
        """

        return output
    else:
        logger.error('Fetching url %s failed, status_code=%d', url, res.status_code)
        return False

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print >> sys.stderr, "Usage: %s <list|detail> <start_time|p2p_proj_url>" % sys.argv[0]
        sys.exit(1)

    try:
        code = sys.argv[1]
        start_watch(code)
    except Exception as e:
        print >> sys.stderr, str(e) + '\n' + traceback.format_exc()
        sys.exit(1)


text:
<!DOCTYPE html>

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

    <title>Peter Tomascik | Portfolio</title>

    <link href="img/favicon/favicon.ico" rel="shortcut icon">

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Home

                        My Projects

                        Documents

                        My Story

                        Peter Tomascik

                        Web Developer - Android Developer - User Experience Designer - Backend Developer

My Projects

Documents

If you have found my projects interesting please download my CV where you can find more details about me.

                         Curriculum Vitae

If you enjoy reading then please download my Application letter where you find out all details me.

                         Application Letter

Little more about myself

Work/ Internship

Edillion A/S
 - Android app developer, Script writing

Gratex s.r.o.
 - internship, Google queries, bash, JavaScript, web scraping

Marriot Hotel Copenhagen
 - housekeeping

Alibaba Slovakia
 - data entry, documentations

Stavona s.r.o.
 - Google My Business/ Analytics/ AdWords, web design

Freelancing
 - web design and programming , domain administrator

Education

Copenhagen Business Academy, Denmark
 - in progress

Copenhagen Business Academy, Denmark
 - AP degree in Computer Science

High school focused on computer and information science, Slovakia
 - secondary school

Eagle High School, USA
 - exhange year

Location

Nybrovej 304

2800  Kgs. Lyngby

Around the Web

Contact me

Feel free to contact me on
tomascik.peter@gmail.com
 or give me a call at

(+45) 50 12 29 16

                        Copyright © Peter Tomascik 2016

Android Development

Responsibilities

                                Design and build advanced applications for the Android platform;

                                Collaborate with cross-functional teams to define, design, and ship new features;

                                Work with outside data sources and API’s;

                                Unit-test code for robustness, including edge cases, usability, and general reliability;

                                Work on bug fixing and improving application performance;

                                Continuously discover, evaluate, and implement new technologies to maximize development efficiency;

Requirements

                                Have published  one original Android app;

                                Experience with Android SDK;

                                Experience working with remote data via REST and JSON;

                                Experience with third-party libraries and APIs;

                                Working knowledge of the general mobile landscape, architectures, trends, and emerging technologies;

                                Solid understanding of the full mobile development life cycle.;

Client:
                                     Edillion A/S

Period:
                                     5 months

Service:
                                    Android Development and Script writting

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

Web design and development

Duties

                                Writing and editing content

                                Designing webpage layout

                                Determining technical requirements

                                Updating websites

                                Creating back up files

                                Solving code problems

Responsibilities

                                meeting clients to identify their needs and liaising regularly with them;

                                drawing up detailed website specifications;

                                designing sample page layouts including text size and colours;

                                designing graphics, animations and manipulating digital photographs;

                                registering web domain names and organising the hosting of the website;

                                presenting initial design ideas to clients;

                                coding using a variety of software;

                                working with different content management systems;

                                search engine optimisation;

                                meeting relevant legal requirements such as accessibility standards, freedom of information and privacy;

                                designing the website's visual imagery and ensuring it's in line with company branding policy or the requirements of the client;

                                proofreading content and making changes where necessary;

                                editing content, debugging code and re-designing web pages;

                                working with web specialists including web developers and graphic designers;

                                liaising with outside agencies;

                                testing the website to ensure it is working;

                                handing the completed website over to the client;

                                post-sales technical support;

                                training client's staff;

                                researching current design trends;

                                continual professional development to keep up to date with new software developments.

Client:
                                    Stavona s.r.o., CFT Academy, Hands Up Crew

Date:
                                     N/A

Service:
                                     Web design and development

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

Data modeling and database creation

Responsibilities

                                    Create Logical Data Model

                                    Create Physical Data model from the existing logical data model

                                    Maintain Logical and Physical Data Model

                                    NOTE: Cannot describe this project any further here

Client:
                                    CFT Academy

Date:
                                     27.7.2016

Service:
                                    Data modeling and database creation

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

Backend

Responsibilities

                                Integration of user-facing elements developed by a front-end developers with server side logic;

                                Building reusable code and libraries for future use;

                                Optimization of the application for maximum speed and scalability;

                                Implementation of security and data protection;

                                Design and implementation of data storage solutions;

                                Creating back up files;

                                Solving code problems;

Skills And Qualifications

                                Good understanding of server-side CSS preprocessors, such as LESS and SASS;

                                User authentication and authorization between multiple systems, servers, and environments;

                                Integration of multiple data sources and databases into one system;

                                Setup and administration of backups;

                                Outputting data in different formats;

                                Creating database schemas that represent and support business processes;

                                Proficient understanding of code versioning tools, such as Git;

                                . . .

Client:
                                     School projects

Date:
                                    2014/ 2016

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

Security

Requirements

                                    Software development experience in Java, Javascript, SAS;

                                    Interest in all aspects of security research and development;

                                    Adequate knowledge of web related technologies (Web applications, Web Services and Service Oriented Architectures) and of network/web related protocols;

Responsibilities

                                    Implement, test and operate advanced software security techniques in compliance with technical reference architecture;

                                    Perform on-going security testing and code review to improve software security;

                                    Provide engineering designs for new software solutions to help mitigate security vulnerabilities;

                                    Contribute to all levels of the architecture;

                                    Maintain technical documentation;

                                    Consult team members on secure coding practices;

                                    Develop a familiarity with new tools and best practices;

Client:
                                    Start Bootstrap

Date:
                                    April 2014

Service:
                                    Web Development

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

Web analysis

Duties

                                    Data capture(Web Log Files, Web Analytics, Search Marketing Platforms);

                                    Data extraction(Regular Data Reports, Ad Hoc Data Reports);

                                    Data manipulation and presentation(Excel);

Responsibilities

                                    Analyzing current online marketing acquisition strategies and exploring new opportunities and/or new strategies;

                                    Trend and data reporting;

                                    Understanding on-site visitor behavior and experiences;

                                    Staying connected with the trends and the details;

Client:
                                    Hands Up Crew, Stavona s.r.o., CFT Academy

Date:
                                    since 2015

Service:
                                    Web Analysis

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


text:
define(function (require) {
	var test = require('intern!object'),
		assert = require('intern/chai!assert'),
		Query = require('../query').Query,
		executeQuery = require('../js-array').executeQuery;

	var data = [
		{
			'with/slash': 'slashed',
			nested: {
				property: 'value'
			},
			price: 10,
			name: 'ten',
			tags: [ 'fun', 'even' ]
		},
		{
			price: 5,
			name: 'five',
			tags: [ 'fun' ]
		}
	];

	test({
		name: 'rql/test/js-array',

		testFiltering: function () {
			assert.equal(executeQuery('price=lt=10', {}, data).length, 1);
			assert.equal(executeQuery('price=lt=11', {}, data).length, 2);
			assert.equal(executeQuery('nested/property=value', {}, data).length, 1);
			assert.equal(executeQuery('with%2Fslash=slashed', {}, data).length, 1);
			assert.equal(executeQuery('out(price,(5,10))', {}, data).length, 0);
			assert.equal(executeQuery('out(price,(5))', {}, data).length, 1);
			assert.equal(executeQuery('contains(tags,even)', {}, data).length, 1);
			assert.equal(executeQuery('contains(tags,fun)', {}, data).length, 2);
			assert.equal(executeQuery('excludes(tags,fun)', {}, data).length, 0);
			assert.equal(executeQuery('excludes(tags,ne(fun))', {}, data).length, 1);
			assert.equal(executeQuery('excludes(tags,ne(even))', {}, data).length, 0);
			// eq() on re: should trigger .match()
			assert.deepEqual(executeQuery('price=match=10', {}, data), [ data[0] ]);
			// ne() on re: should trigger .not(.match())
			assert.deepEqual(executeQuery('name=match=f.*', {}, data), [ data[1] ]);
			assert.deepEqual(executeQuery('name=match=glob:f*', {}, data), [ data[1] ]);
			assert.deepEqual(executeQuery(new Query().match('name', /f.*/), {}, data), [data[1]]);
		},

		testFiltering1: function () {
			var data = [
				{ 'path.1': [ 1, 2, 3 ] },
				{ 'path.1': [ 9, 3, 7 ] }
			];

			assert.deepEqual(executeQuery('contains(path,3)&sort()', {}, data), []); // path is undefined
			assert.deepEqual(executeQuery('contains(path.1,3)&sort()', {}, data), data); // 3 found in both
			assert.deepEqual(executeQuery('excludes(path.1,3)&sort()', {}, data), []); // 3 found in both
			assert.deepEqual(executeQuery('excludes(path.1,7)&sort()', {}, data), [ data[0] ]); // 7 found in second
		}
	});
});


text:
import React from 'react';
import ScrollableTabView, { DefaultTabBar } from 'react-native-scrollable-tab-view';
import styles from './style/';
import TabsProps from './PropsType';

class Tabs extends React.Component<TabsProps, any> {
  static defaultProps = {
    tabBarPosition: 'top',
    animated: true,
    swipeable: true,
    onChange() {},
    onTabClick() {},
    underlineColor: '#ddd',
    activeUnderlineColor: '#108ee9',
    textColor: '#000',
    activeTextColor: '#108ee9',
    styles: styles,
    barStyle: null,
  };

  static TabPane: any;
  activeIndex: number;

  constructor(props) {
    super(props);
    this.activeIndex = 0;
  }

  onTabClick = ({ i }) => {
    const key = this.getKey(i);
    const { onTabClick, onChange } = this.props;
    if (onTabClick) {
      onTabClick(key);
    }
    if (this.activeIndex !== i) {
      if (onChange) {
        onChange(key);
      }
      this.activeIndex = i;
    }
  }

  getContents() {
    const { children } = this.props;
    const newChildren: any[] = [];
    React.Children.forEach(children as any, (child: any, idx) => {
      newChildren.push(React.cloneElement(child, {
        key: idx,
        tabLabel: child.props.tab,
        children: child.props.children,
      }));
    });

    return newChildren;
  }

  getKey(index) {
    const children = this.props.children;
    let key = '';
    React.Children.forEach(children as any, (child: any, idx) => {
      if (index === idx) {
        key = child.key;
      }
    });
    return key;
  }

  renderTabBar = () => {
    const {
      tabBarPosition, underlineColor, activeUnderlineColor, textColor, activeTextColor, styles, barStyle,
    } = this.props;
    const barBaseStyle = tabBarPosition === 'top' ? styles.barTop : styles.barBottom;
    const linePosition = tabBarPosition === 'top' ? {} : { top: -1 };
    const underlineStyle = [styles.underline, {
      bottom: tabBarPosition === 'top' ? -1 : null,
      backgroundColor: activeUnderlineColor,
    }, linePosition];
    return (
      <DefaultTabBar
        activeTextColor={activeTextColor}
        inactiveTextColor={textColor}
        style={[barBaseStyle, { borderColor: underlineColor }, barStyle ]}
        textStyle={[styles.text]}
        tabStyle={[styles.tab]}
        underlineStyle={underlineStyle}
      />
    );
  }

  render() {
    const {
      tabBarPosition, defaultActiveKey, activeKey, animated, children, swipeable,
    } = this.props;

    let defaultActiveIndex = 0;
    let activeIndex = 0;
    React.Children.forEach(children as any, (child: any, idx) => {
      if (defaultActiveKey === child.key) {
        defaultActiveIndex = idx;
      }
      if (activeKey === child.key) {
        activeIndex = idx;
      }
    });

    this.activeIndex = activeIndex;

    return (
      <ScrollableTabView
        tabBarPosition={tabBarPosition}
        scrollWithoutAnimation={!animated}
        initialPage={defaultActiveIndex}
        page={activeIndex}
        locked={swipeable}
        renderTabBar={this.renderTabBar}
        onChangeTab={this.onTabClick}
      >
        {this.getContents()}
      </ScrollableTabView>
    );
  }
}

export default Tabs;


text:
//
//  GroundBase-Bridging-Header.h
//  GroundBase-swift
//
//  Created by Manuel Deneu on 25/10/2016.
//  Copyright © 2016 FlyLab. All rights reserved.
//

#ifndef Binn_Bridging_Heade_h
#define Binn_Bridging_Heade_h

#import "GBBinCoder_objc.h"
#import "GBSocket_objc.h"
#import "FKClient_objc.h"
//#import "Litterals.h"

#endif /* Binn_Bridging_Heade_h */


text:
package ca.farrelltonsolar.uicomponents;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by Graham on 05/12/2014.
 */

public class BaseComponent extends View {

    protected static final String TAG = BaseComponent.class.getSimpleName();
    private LabelConverter mLabelConverter;
    protected float mDensity = 1.0f;
    protected int mViewWidth;
    protected int mViewHeight;

    public BaseComponent(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
        mDensity = getResources().getDisplayMetrics().density;
    }

    public BaseComponent(final Context context, final AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BaseComponent(Context context) {
        this(context, null, 0);
    }

    public LabelConverter getLabelConverter() {
        return mLabelConverter;
    }

    public void setLabelConverter(LabelConverter labelConverter) {
        this.mLabelConverter = labelConverter;
        invalidateAll();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST) {
            //Must be this size
            mViewWidth = widthSize;
        } else {
            mViewWidth = getSuggestedMinimumWidth();
        }
        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY || heightMode == MeasureSpec.AT_MOST) {
            //Must be this size
            mViewHeight = heightSize;
        } else {
            mViewHeight = getSuggestedMinimumHeight();
        }
        //MUST CALL THIS
        setMeasuredDimension(mViewWidth, mViewHeight);
    }

    protected void invalidateAll() {

    }

    public static interface LabelConverter {
        String getLabelFor(float value, float min, float max);
    }
}


text:
import makeActionCreator from '../../shared/ActionCreator';
import NewReleasesConstants from './NewReleasesConstants';
import ApiBridge from '../../shared/ApiBridge';
import { handleError, setLoading } from '../app/AppActions';

export const setData = makeActionCreator(NewReleasesConstants.SET_DATA, 'payload');

export const getNewReleasesData = () => {
    return (dispatch) => {
    	dispatch(setLoading(true));
        ApiBridge.makeGet(`/v1/browse/new-releases`, [`country=US`], undefined, true)
            .then(res => {
            	dispatch(setLoading(false));
                dispatch(setData(res.albums));
            })
            .catch(err => {
                dispatch(handleError(err));
            })
    }
}


text: this is file 306