text:
@import Accelerate;

@implementation UIImage (LXExtension)
- (instancetype)lx_circleImage
{
    // self -> 圆形图片

    // 开启图形上下文
    UIGraphicsBeginImageContext(self.size);

    // 上下文
    CGContextRef context = UIGraphicsGetCurrentContext();

    // 添加一个圆
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(context, rect);

    // 裁剪
    CGContextClip(context);

    // 绘制图片到圆上面
    [self drawInRect:rect];

    // 获得图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 结束图形上下文
    UIGraphicsEndImageContext();

    return image;
}

+ (instancetype)lx_circleImageNamed:(NSString *)name
{
    return [[self imageNamed:name] lx_circleImage];
}

+ (UIImage *)imageWithOriginalImageName:(NSString *)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    return [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
- (UIImage *)applyLightEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
    return [self applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}

- (UIImage *)applyExtraLightEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
    return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}

- (UIImage *)applyDarkEffect
{
    UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
    return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}

- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
{
    const CGFloat EffectColorAlpha = 0.6;
    UIColor *effectColor = tintColor;
    int componentCount = (int)CGColorGetNumberOfComponents(tintColor.CGColor);
    if (componentCount == 2) {
        CGFloat b;
        if ([tintColor getWhite:&b alpha:NULL]) {
            effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
        }
    }
    else {
        CGFloat r, g, b;
        if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
            effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
        }
    }
    return [self applyBlurWithRadius:20
                           tintColor:effectColor
               saturationDeltaFactor:1.4
                           maskImage:nil];
}

- (UIImage *)blurImage
{
    return [self applyBlurWithRadius:20
                           tintColor:[UIColor colorWithWhite:0 alpha:0.0]
               saturationDeltaFactor:1.4
                           maskImage:nil];
}

- (UIImage *)blurImageWithRadius:(CGFloat)radius
{
    return [self applyBlurWithRadius:radius
                           tintColor:[UIColor colorWithWhite:0 alpha:0.0]
               saturationDeltaFactor:1.4
                           maskImage:nil];
}

- (UIImage *)blurImageWithRadius:(CGFloat)radius color:(UIColor *)color
{
    return [self applyBlurWithRadius:radius
                           tintColor:[UIColor colorWithWhite:0 alpha:0.0]
               saturationDeltaFactor:1.4
                           maskImage:nil];
}

- (UIImage *)blurImageWithMask:(UIImage *)maskImage
{
    return [self applyBlurWithRadius:20
                           tintColor:[UIColor colorWithWhite:0 alpha:0.0]
               saturationDeltaFactor:1.4
                           maskImage:maskImage];
}

- (UIImage *)blurImageAtFrame:(CGRect)frame
{
    return [self applyBlurWithRadius:20
                           tintColor:[UIColor colorWithWhite:0 alpha:0.0]
               saturationDeltaFactor:1.4
                           maskImage:nil
                             atFrame:frame];
}

// 核心代码
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
{
    // Check pre-conditions.
    if (self.size.width < 1 || self.size.height < 1) {
        NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
        return nil;
    }
    if (!self.CGImage) {
        NSLog (@"*** error: image must be backed by a CGImage: %@", self);
        return nil;
    }
    if (maskImage && !maskImage.CGImage) {
        NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
        return nil;
    }

    CGRect imageRect = { CGPointZero, self.size };
    UIImage *effectImage = self;

    BOOL hasBlur = blurRadius > __FLT_EPSILON__;
    BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
    if (hasBlur || hasSaturationChange) {
        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectInContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(effectInContext, 1.0, -1.0);
        CGContextTranslateCTM(effectInContext, 0, -self.size.height);
        CGContextDrawImage(effectInContext, imageRect, self.CGImage);

        vImage_Buffer effectInBuffer;
        effectInBuffer.data     = CGBitmapContextGetData(effectInContext);
        effectInBuffer.width    = CGBitmapContextGetWidth(effectInContext);
        effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
        effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);

        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
        vImage_Buffer effectOutBuffer;
        effectOutBuffer.data     = CGBitmapContextGetData(effectOutContext);
        effectOutBuffer.width    = CGBitmapContextGetWidth(effectOutContext);
        effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
        effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);

        if (hasBlur) {
            // A description of how to compute the box kernel width from the Gaussian
            // radius (aka standard deviation) appears in the SVG spec:
            // For larger values of 's' (s >= 2.0), an approximation can be used: Three
            // successive box-blurs build a piece-wise quadratic convolution kernel, which
            // approximates the Gaussian kernel to within roughly 3%.
            //
            // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
            //
            // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
            //
            CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
            NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
            if (radius % 2 != 1) {
                radius += 1; // force radius to be odd so that the three box-blur methodology works.
            }
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, (uint32_t)radius, (uint32_t)radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, (uint32_t)radius, (uint32_t)radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, (uint32_t)radius, (uint32_t)radius, 0, kvImageEdgeExtend);
        }
        BOOL effectImageBuffersAreSwapped = NO;
        if (hasSaturationChange) {
            CGFloat s = saturationDeltaFactor;
            CGFloat floatingPointSaturationMatrix[] = {
                0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
                0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
                0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
                0,                    0,                    0,  1,
            };
            const int32_t divisor = 256;
            NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
            int16_t saturationMatrix[matrixSize];
            for (NSUInteger i = 0; i < matrixSize; ++i) {
                saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
            }
            if (hasBlur) {
                vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                effectImageBuffersAreSwapped = YES;
            }
            else {
                vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
            }
        }
        if (!effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        if (effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    // Set up output context.
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef outputContext = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(outputContext, 1.0, -1.0);
    CGContextTranslateCTM(outputContext, 0, -self.size.height);

    // Draw base image.
    CGContextDrawImage(outputContext, imageRect, self.CGImage);

    // Draw effect image.
    if (hasBlur) {
        CGContextSaveGState(outputContext);
        if (maskImage) {
            CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
        }
        CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
        CGContextRestoreGState(outputContext);
    }

    // Add in color tint.
    if (tintColor) {
        CGContextSaveGState(outputContext);
        CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
        CGContextFillRect(outputContext, imageRect);
        CGContextRestoreGState(outputContext);
    }

    // Output image is ready.
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return outputImage;
}

- (UIImage *)grayScale
{
    int width = self.size.width;
    int height = self.size.height;

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    CGContextRef context = CGBitmapContextCreate(nil,
                                                 width,
                                                 height,
                                                 8, // bits per component
                                                 0,
                                                 colorSpace,
                                                 kCGBitmapByteOrderDefault);

    CGColorSpaceRelease(colorSpace);

    if (context == NULL) {
        return nil;
    }

    CGContextDrawImage(context,
                       CGRectMake(0, 0, width, height), self.CGImage);
    CGImageRef image = CGBitmapContextCreateImage(context);
    UIImage *grayImage = [UIImage imageWithCGImage:image];
    CFRelease(image);
    CGContextRelease(context);

    return grayImage;
}

- (UIImage *)scaleWithFixedWidth:(CGFloat)width
{
    float newHeight = self.size.height * (width / self.size.width);
    CGSize size = CGSizeMake(width, newHeight);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(context, 0.0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);

    UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return imageOut;
}

- (UIImage *)scaleWithFixedHeight:(CGFloat)height
{
    float newWidth = self.size.width * (height / self.size.height);
    CGSize size = CGSizeMake(newWidth, height);

    UIGraphicsBeginImageContextWithOptions(size, NO, 0);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(context, 0.0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeCopy);
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);

    UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return imageOut;
}

- (UIColor *)averageColor
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char rgba[4];
    CGContextRef context = CGBitmapContextCreate(rgba, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), self.CGImage);
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    if(rgba[3] > 0) {
        CGFloat alpha = ((CGFloat)rgba[3])/255.0;
        CGFloat multiplier = alpha/255.0;
        return [UIColor colorWithRed:((CGFloat)rgba[0])*multiplier
                               green:((CGFloat)rgba[1])*multiplier
                                blue:((CGFloat)rgba[2])*multiplier
                               alpha:alpha];
    }
    else {
        return [UIColor colorWithRed:((CGFloat)rgba[0])/255.0
                               green:((CGFloat)rgba[1])/255.0
                                blue:((CGFloat)rgba[2])/255.0
                               alpha:((CGFloat)rgba[3])/255.0];
    }
}

- (UIImage *)croppedImageAtFrame:(CGRect)frame
{
    frame = CGRectMake(frame.origin.x * self.scale, frame.origin.y * self.scale, frame.size.width * self.scale, frame.size.height * self.scale);
    CGImageRef sourceImageRef = [self CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, frame);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[self scale] orientation:[self imageOrientation]];
    CGImageRelease(newImageRef);
    return newImage;
}

- (UIImage *)addImageToImage:(UIImage *)img atRect:(CGRect)cropRect{

    CGSize size = CGSizeMake(self.size.width, self.size.height);
    UIGraphicsBeginImageContextWithOptions(size, NO, self.scale);

    CGPoint pointImg1 = CGPointMake(0,0);
    [self drawAtPoint:pointImg1];

    CGPoint pointImg2 = cropRect.origin;
    [img drawAtPoint: pointImg2];

    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}

- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius
                       tintColor:(UIColor *)tintColor
           saturationDeltaFactor:(CGFloat)saturationDeltaFactor
                       maskImage:(UIImage *)maskImage
                         atFrame:(CGRect)frame
{
    UIImage *blurredFrame = \
    [[self croppedImageAtFrame:frame] applyBlurWithRadius:blurRadius
                                                tintColor:tintColor
                                    saturationDeltaFactor:saturationDeltaFactor
                                                maskImage:maskImage];

    return [self addImageToImage:blurredFrame atRect:frame];
}

- (UIImage *)fillClipSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    CGContextRef imageContext = UIGraphicsGetCurrentContext();
    CGContextDrawTiledImage(imageContext, (CGRect){CGPointZero, self.size}, [self CGImage]);
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}

@end


text:
A record is a collection of fields (which can be of different types) that belong together. To define a record the `type` keyword is used. A record's fields are defined between `{` and `}` characters, and each field has a name _and_ a type. To create a record, specify the names of the fields and assign a value to them between `{` and `}` characters. All fields must be assigned a value when creating a record. A record instance's field values can be accessed using dot-notation.

When defining/creating a record, each field must either be on a separate line or separated by semicolons (`;`) when on a single line.

```fsharp
// Define a record
type Address =
    { Street: string
      HouseNumber: int }

// Create a record
let oldAddress: Address =
    { Street = "Main Street"
      HouseNumber = 17 }

// Single-line alternative
type ConciseAddress = { Street: string; HouseNumber: int }
let conciseAddress: ConciseAddress = { Street = "Main Street"; HouseNumber = 17 }
```

As records are immutable, once a record has been constructed, its field values can never change. If you'd like to change a record's values, the `with` keyword allows you to create a copy of an existing record, but with new values for one or more fields.

```fsharp
// Copy the old address but change the house number
let newAddress: Address = { oldAddress with HouseNumber = 86 }
newAddress.Street      // => "Main Street"
newAddress.HouseNumber // => 86
```

Records have _structural equality_, which means that two instances of the same record with identical values are equivalent.

Besides being able to use dot-notation to access a record's fields, records can also be _deconstructed_ in bindings and in pattern matching:

```fsharp
let myAddress: Address = { Street = "Broadway"; HouseNumber = 123 }
let { Street = myStreet; HouseNumber = myHouseNumber } = myAddress

match myAddress with
| { HouseNumber = 1 } -> printfn "First house"
| { HouseNumber = houseNumber; Street = street } -> printfn "House number %d on %s" houseNumber street
// => "House number 123 on Broadway
```

redpajama_set_name: RedPajamaGithub


text:
package com.rando.library;

/**
 * Created by SERGant on 11.10.2014.
 */
public class UserInterfaces {
    public interface IUser {
        public String GetUID(); // Unique id for user. Consists from letters (all cases) and digits
        public String GetUserName(); // Username - can be formed from letters (all cases) and digits
        public void SetUserName(String userName); // Sets the name in IUser
    }

    public interface ILoggedUser extends IUser {
        String GetUserEmail();
        void SetUserEmail(String userEmail);// Sets the email
    }

    public enum LOGINRESULT {
        SUCCESS, BADPASSWORD, NOTEXIST, UNDEFINED //for IUserLoginResult
    }

    public interface IUserLoginResult {
        LOGINRESULT GetUserLoginResult(); //See LOGINRESULT for possible values
        ILoggedUser GetLoggedUser(); // Returns null if login failed
    }

    public interface IUserLoginCallback {
        void OnUserLogin(IUserLoginResult loginResult);
    }

    public enum REGISTERRESULT {
        SUCCESS, USEREXISTS, BADPASSWORD, EMPTYDATA,UNDEFINED //for IUserRegisterResult
    }

    public interface IUserRegisterResult {
        REGISTERRESULT GetUserRegisterResult(); //see REGISTERRESULT for possible values
        IUser GetRegisteredUser(); // null if register failed
    }

    public interface IUserRegisterCallback {
        void OnUserRegister(IUserRegisterResult registerResult);
    }

    public interface IUserManager {
        public ILoggedUser GetCurrentUser(); //Returns current user by ParseUser.getCurrentUser (locally). Returns null if no logged user. - fast
        public void LogInUser(String userName, String userPassword, IUserLoginCallback loginCallback); //Login registered user - background web task - ~1 sec
        public void LogOffUser(); // Logoff current user - locally, web access optional - fast
        public void RegisterUser(String userName, String userPassword, String userEmail, IUserRegisterCallback registerCallback); // Register user - web background task - ~1 sec
    }
}


text:
<?php
class PostsController extends AppController {
	public $helpers = array(
	    'Cache',
	    'List',
	    'Rss',
	    'Textile',
	    'Category',
	    'Tree',
	    'Time',
	    'Paginator',
	);
	public $components = array('Email');

	/** Pagination options for the admin_index action **/
    public $paginate = array(
        'limit' => 12,
        'order' => array('Post.created' => 'desc'),
    );

    /**
     * Create a post and redirect to it's edit screen
     *
     */
    function admin_create() {
        // Generate UUID
        $uuid = sha1(String::uuid());
        // Check if unique
        while ($this->{$this->modelClass}->findByUuid($uuid)) {
            $uuid = sha1(String::uuid());
        }

        $defaultParams = array(
            'draft' => 1,
            'uuid' => $uuid,
			'comment_count' => 0
        );
        $this->data[$this->modelClass] = am($this->data[$this->modelClass], $defaultParams);
        $this->{$this->modelClass}->create($this->data);
        $this->{$this->modelClass}->save();
        $this->redirect(array('action' => 'admin_edit', $this->{$this->modelClass}->id));
    }

    /**
     * Manage post's comments
     *
     */
    function admin_comments($id = null, $status = null) {
        $spam = ($status == 'spam') ? 1 : 0;
        $approved = ($status == 'unapproved') ? 0 : 1;
        if ($spam) {
            // Spam comments should show no matter of approval status
            $approved = array(0, 1);
        }

        $this->data = $this->{$this->modelClass}->find('first', array(
            'conditions' => array('Post.id' => $id),
            'contain' => array(
                'Comment' => array(
                    'order' => 'Comment.created DESC',
                    'conditions' => array(compact('spam', 'approved'))
                ),
                'User'
            )
        ));

        $goBackAction = $this->referer(array('action' => 'edit', $this->data['Post']['id']));
        $this->set('goBackAction', $goBackAction);
    }

    /**
     * Posts overview
     *
     */
    function admin_index() {
    	$posts = $this->paginate($this->modelClass);
        $this->set('posts', $posts);
    }

    /**
     * Edit a post
     *
     * @param int $id
     */
    function admin_edit($id = null, $revisionNumber = null) {
        $this->Post->contain(array('User', 'Category'));
        $this->data = $this->Post->findById($id);
        //var_dump($this->data);

        // If viewing a revision, merge with revision content
        if ($revisionNumber) {
            $this->data = $this->Post->getRevision($id, $revisionNumber);

            $this->set(array('revisionId' => $revisionNumber, 'revisionCreated' => $this->data['Revision']['created']));
        }

        // View
        $hasUser = $this->data['User']['id'] ? true : false;
        $isDraft = ($this->data[$this->modelClass]['draft'] == 1) ? true : false;
        $isRevision = !is_null($revisionNumber);

        // Categories for select box
        $categories = $this->Post->Category->find('list', array('fields' => array('id', 'title')));
        $inCategories = Set::extract($this->data['Category'], '{n}.id');
        $isDraft = ($this->data[$this->modelClass]['draft'] == 1) ? true : false;
        $categoriesForTree = $this->Post->Category->find('all', array('order' => 'lft ASC', 'recursive' => -1));

        $this->set(compact('isRevision', 'hasUser', 'isDraft', 'categoriesForTree', 'inCategories'));
        $this->pageTitle = $this->data[$this->modelClass]['title'];
    }

    function admin_categorize($id = null) {
        $this->Post->contain(array('User', 'Category'));
        $this->data = $this->Post->findById($id);

        if (empty($this->data)) return $this->cakeError('object_not_found');

        $categories = $this->Post->Category->find('list', array('fields' => array('id', 'title')));
        $inCategories = Set::extract($this->data['Category'], '{n}.id');
        $isDraft = ($this->data[$this->modelClass]['draft'] == 1) ? true : false;
        $categoriesForTree = $this->Post->Category->find('all', array('order' => 'lft ASC', 'recursive' => -1));
        $this->set(compact('categories', 'inCategories', 'isDraft', 'categoriesForTree'));

        $this->pageTitle = $this->data[$this->modelClass]['title'];
    }

    function admin_options($id = null) {
        $this->Post->contain(array('User', 'Category'));
        $this->data = $this->Post->findById($id);

        if (empty($this->data)) return $this->cakeError('object_not_found');

        $isDraft = ($this->data[$this->modelClass]['draft'] == 1) ? true : false;
        $this->set(compact('isDraft'));

        $this->pageTitle = $this->data[$this->modelClass]['title'];
    }

    function admin_update() {
        //fb($this->data);
        $this->data[$this->modelClass]['user_id'] = $this->getLoggedInUserId();

        // Publish?
        if (isset($this->data['__save']['publish'])) {
            $this->data[$this->modelClass]['draft'] = 0;
        }
        unset($this->data['__save']);

        if (isset($this->data[$this->modelClass]['slug'])) {
            $this->data[$this->modelClass]['slug'] = $this->slug($this->data[$this->modelClass]['slug']);
        }

        $this->Post->create($this->data);

        if (!$this->Post->exists()) return $this->cakeError('object_not_found');

        if (isset($this->data[$this->modelClass]['categories_can_be_empty']) && !isset($this->data['Category'])) {
             // Delete all post categories
             $this->Post->query("DELETE FROM categories_posts WHERE post_id = {$this->Post->id}");
        }

        if (!$this->Post->save()) return $this->cakeError('save_error'); // @TODO Rendering the exact save errors would be better

        // $cacheName = str_replace('-', '_', $this->data[$this->modelClass]['slug']); // @TODO check cache for proper naming method
        // clearCache($cacheName, 'views', '.php');

        if ($this->RequestHandler->isAjax()) {
            $this->Post->contain('User');
            $this->data = $post = $this->Post->findById($this->Post->id); // @TODO clean up
            $this->set(compact('post'));
            return $this->render('admin_update');
        }

        $this->redirect(array('action' => 'edit', $this->Post->id));
    }

    function beforeFilter() {
    	parent::beforeFilter();

    	$this->pageTitle = 'Blog';

    	$this->params['current']['type'] = 'post';
    	$this->params['current']['slug'] = Configure::read('Wildflower.blogIndex');
    }

    function beforeRender() {
        parent::beforeRender();
        $this->set('isPosts', true);
        $this->params['Wildflower']['view']['isPosts'] = true;
    }

    // /**
    //  * Display posts from a certain category
    //  *
    //  */
    // function category() {
    //  $slug = WildflowerHelper::slug($this->params['slug']);
    //
    //  $this->Post->Category->Behaviors->attach('Containable');
    //     $this->Post->Category->contain("Post.id");
    //     $category = $this->Post->Category->findBySlug($slug);
    //
    //     $ids = array();
    //     foreach ($category[$this->modelClass] as $post) {
    //         $ids[] = $post['id'];
    //     }
    //
    //     $in = implode(', ', $ids);
    //     $scope = "Post.id IN ($in)";
    //  $posts = $this->paginate($this->modelClass, $scope);
    //
    //  $this->set(array('posts' => $posts, 'postsCategory' => $category));
    // }
    //
    /**
     * RSS feed for posts
     *
     */
    function rss() {
        $this->layout = 'rss/default';
        $posts = $this->Post->find('all', array(
             'order' => 'Post.created DESC',
             'contain' => array('User', 'Category'),
			 'limit' => 20,
			 'conditions' => 'Post.draft = 0',
        ));
        $this->set(compact('posts'));
        $this->RequestHandler->respondAs('text/xml');
    }

    /**
     * Posts index
     *
     */
    function index() {
        $this->cacheAction = true;

        $this->pageTitle = 'Blog';

        $this->paginate = array(
            'limit' => 4,
            'order' => array('Post.created' => 'desc'),
            'conditions' => 'Post.draft = 0'
        );
        $posts = $this->paginate($this->modelClass);

        if (isset($this->params['requested'])) {
            return $posts;
        }

        $sidebarCategories = $this->Post->Category->find('all', array(
            'order' => 'lft ASC',
            'recursive' => -1,
            'conditions' => array('parent_id' => Configure::read('App.blogCategoryId')),
        ));

        // Sidebar for blog
        $wfPostsSidebar = ClassRegistry::init('Sidebar')->findBlogSidebar();

        $this->set(compact('posts', 'sidebarCategories', 'wfPostsSidebar'));
    }

    /**
     * View posts from one category
     *
     */
    function category() {
        //$this->cacheAction = true;

        $this->pageTitle = 'Blog';

        $this->Post->Category->recursive = -1;
        $category = $this->Post->Category->findBySlug($this->params['slug']);
        $posts = $this->Post->CategoriesPost->find('all', array(
            'conditions' => array(
                'category_id' => $category['Category']['id'],
            )
        ));
        $postsIds = Set::extract($posts, '{n}.CategoriesPost.post_id');

        $this->paginate = array(
            'limit' => 10,
            'order' => array(
                'Post.created' => 'desc'
            ),
            'conditions' => array(
                'Post.draft' => 0,
                'Post.id' => $postsIds,
            ),
        );
        $posts = $this->paginate($this->modelClass);

        if (isset($this->params['requested'])) {
            return $posts;
        }

        $sidebarCategories = $this->Post->Category->find('all', array(
            'order' => 'lft ASC',
            'recursive' => -1,
            'conditions' => array('parent_id' => Configure::read('App.blogCategoryId')),
        ));

        // Sidebar for blog
        $wfPostsSidebar = ClassRegistry::init('Sidebar')->findBlogSidebar();

        $this->set(compact('posts', 'sidebarCategories', 'wfPostsSidebar'));
        $this->render('index');
    }

    /**
     * View a post
     *
     * @param string $slug
     */
    function view() {
        $this->_acceptComment();

		if (Configure::read('AppSettings.cache') == 'on') {
            $this->cacheAction = 60 * 60 * 24 * 3; // Cache for 3 days
        }

        $slug = $this->params['slug'];
        $this->Post->contain(array(
            'User',
            'Category',
            'Comment' => array(
                'conditions' => array('spam' => 0, 'approved' => 1),
            ),
        ));
        $post = $this->Post->findBySlugAndDraft($slug, 0);

		if (empty($post)) {
			return $this->do404();
		}

        // Post title
        $this->pageTitle = $post[$this->modelClass]['title'];

        if (isset($this->params['requested'])) {
            return $post;
        }

        $sidebarCategories = $this->Post->Category->find('all', array(
            'order' => 'lft ASC',
            'recursive' => -1,
            'conditions' => array('parent_id' => Configure::read('App.blogCategoryId')),
        ));

        // Sidebar for blog
        $wfPostsSidebar = ClassRegistry::init('Sidebar')->findBlogSidebar();

        $this->set(array(
            'post' => $post,
            'descriptionMetaTag' => $post[$this->modelClass]['description_meta_tag'],
            'sidebarCategories' => $sidebarCategories,
            'wfPostsSidebar' => $wfPostsSidebar
        ));
    }

    /**
     * Allow an action to accept a comment submit
     *
     * @return void
     */
    private function _acceptComment() {
        if (empty($this->data)) return; // Else we would have a redirect loop

        if (Configure::read('Wildflower.settings.approve_comments')) {
            $this->data['Comment']['approved'] = 0;
        }

        $this->Post->Comment->spamCheck = true;
        if ($this->Post->Comment->save($this->data)) {
            $postId = intval($this->data['Comment']['post_id']);

            // Clear post cache
            // @TODO find out better method
            // $cacheName = str_replace('-', '_', $postSlug);
            // clearCache($cacheName, 'views', '.php');

            // Email alert
    		$this->set($this->data['Comment']);
    		$message = $this->data['Comment']['content']; // @TODO remove Textile syntax - to plain text
    		$this->set(compact('postId', 'message'));

    		$this->_sendEmail('new_comment_notification',
				  Configure::read('Wildflower.settings.site_name') . ' - new comment from ' . $this->data['Comment']['name'],
				  array('to' => Configure::read('Wildflower.settings.contact_email')),
				  $this->data['Comment']['email'],
				  'text');

            $message = __('Comment succesfuly posted.', true);
            if (Configure::read('Wildflower.settings.approve_comments')) {
                $message = __('Your comment will be posted after it\'s approved by the administrator.', true);
            }
            $this->Session->setFlash($message);

            $this->redirect($this->data['Post']['permalink'] . '#comment-' . $this->Post->Comment->id);
        }
    }

    /*
     * Get all latest posts
     *
     * @return array
     */
	public function latest($category = null, $limit = 5){
		if(!empty($category)){
			$this->Post->bindModel(array(
				'hasOne' => array(
					'CategoriesPost',
					'FilterTag' => array(
						'className' => 'Category',
						'foreignKey' => false,
						'conditions' => array('FilterTag.id = CategoriesPost.category_id')
			))));
			$posts = $this->Post->find('all', array('order' => 'Post.created DESC', 'conditions' => 'Post.draft = 0 and FilterTag.slug = "'.$category.'" ', 'limit' => $limit));
		}else{
			$posts = $this->Post->find('all', array('order' => 'Post.created DESC', 'conditions' => 'Post.draft = 0', 'limit' => $limit));
		}
	return $posts;
	}
}


text:
Add sets a new value for a key if and only if that key doesn't already exist

```javascript
client
    .add('firstName', 'Victor')
    .then(function() {
        console.log('Successfully added the key firstName');
    });
```

### Error if key already exists

If a key already exists and you try to use the `add` command, Memcached will
return an error which Memcache Plus will throw.

```javascript
// If 'firstName' already exists
client
    .add('firstName', 'Victor')
    .then(function() {
        // This will not get hit because `add` will throw on error
        console.log('Successfully added the key firstName');
    })
    .catch(function(err) {
        // Will print: 'Cannot "add" for key "firstName" because it already exists'
        console.error(err);
    });
```

### Callbacks

Memcache Plus will always return a [Promise](https://www.promisejs.org), but it
can also take a traditional callback for any of its methods so it can work just
like most of the other Memcache modules out there. For example:

```javascript
client.add('firstName', 'Victor, function(err) {
    console.log('Successfully added the key firstName');
});
```

And if you try to add to a key that already exists:

```javascript
// If 'firstName' already exists
client.add('firstName', 'Victor', function(err) {
    // Will print: 'Cannot "add" for key "firstName" because it already exists'
    console.error(err);
});
```


text:
<?php

namespace InstantMovie\FrontendBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class FrontendBundle extends Bundle
{
}


text:
<!DOCTYPE html>

   <meta charset="UTF-8">
   <title>Lowes - WaysToSave</title>
   <link rel="stylesheet" type="text/css" href="sheet.css">

     <form id="contact" action="" method="post">

Payment Calculator

Contact us today, and get reply with in 24 hours!

       <fieldset>
         <input placeholder="Credit Balance" type="text" tabindex="1" required autofocus name="Balance">
       </fieldset>
       <fieldset>
         <input placeholder="Interest Rate" type="text" tabindex="2" required name="Rate">
       </fieldset>
       <fieldset>
         <input placeholder="How many months" type="text" tabindex="3" required name="months">
       </fieldset>
       <fieldset>
         <button name="submit" type="submit" id="contact-submit" data-submit="...Sending" onsubmit="">Submit</button>
       </fieldset>
     </form>

      <form id="result">

        <fieldset>
          <input placeholder="Result" type="text" tabindex="1">
        </fieldset>

      </form>


text:
import datetime
import shutil
import urllib.request as urlrequest
import boto3

disk_usage = shutil.disk_usage('/data')
disk_used_percent = disk_usage.used / disk_usage.total * 100
print('DiskUsedPercent {0}'.format(disk_used_percent))
timestamp = urlrequest.urlopen('http://localhost/api/timestamp').readline().decode('utf-8')
parsed = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ\n")
now = datetime.datetime.now()
replication_seconds_behind = (now - parsed).total_seconds()
print('ReplicationSecondsBehind {0}'.format(replication_seconds_behind))

boto3.client('cloudwatch','us-east-1').put_metric_data(
    Namespace="Overpass",
    MetricData=[
        {
            'MetricName':'ReplicationSecondsBehind',
            'Value':replication_seconds_behind,
            'Unit':'Seconds'
        },
        {
            'MetricName':'DiskUsedPercent',
            'Value':disk_used_percent,
            'Unit':'Percent'

        }
    ])


text:
[![TFX Addons package CI](https://github.com/tensorflow/tfx-addons/actions/workflows/ci.yml/badge.svg)](https://github.com/tensorflow/tfx-addons/actions/workflows/ci.yml)
[![TFX Addons CI for examples](https://github.com/tensorflow/tfx-addons/actions/workflows/ci_examples.yml/badge.svg)](https://github.com/tensorflow/tfx-addons/actions/workflows/ci_examples.yml)
[![PyPI](https://badge.fury.io/py/tfx-addons.svg)](https://badge.fury.io/py/tfx-addons)

SIG TFX-Addons is a community-led open source project. As such, the project depends on public contributions, bug fixes, and documentation. This project adheres to the [TensorFlow Code of Conduct](https://github.com/tensorflow/tensorflow/blob/master/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code.

## Maintainership

The maintainers of TensorFlow Addons can be found in the [CODEOWNERS](https://github.com/tensorflow/tfx-addons/blob/main/CODEOWNERS) file of the repo. If you would
like to maintain something, please feel free to submit a PR. We encourage multiple
owners for all submodules.

## Installation

TFX Addons is available on PyPI for all OS. To install the latest version,
run the following:

```
pip install tfx-addons
```

To ensure you have a compatible version of dependencies for any given project,
you can specify the project name  as an extra requirement during install:

```
pip install tfx-addons[feast_examplegen,schema_curation]
```

To use TFX Addons:

```python
from tfx import v1 as tfx
import tfx_addons as tfxa

# Then you can easily load projects tfxa.{project_name}. Ex:

tfxa.feast_examplegen.FeastExampleGen(...)

```

## TFX Addons projects

* [tfxa.mlmd_client](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/mlmd_client)
* [tfxa.schema_curation](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/schema_curation)
* [tfxa.feature_selection](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/feature_selection)
* [tfxa.feast_examplegen](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/feast_examplegen)
* [tfxa.xgboost_evaluator](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/xgboost_evaluator)
* [tfxa.sampling](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/sampling)
* [tfxa.message_exit_handler](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/message_exit_handler)
* [tfxa.pandas_transform](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/pandas_transform)
* [tfxa.firebase_publisher](https://github.com/tensorflow/tfx-addons/tree/main/tfx_addons/firebase_publisher)

Check out [proposals](https://github.com/tensorflow/tfx-addons/tree/main/proposals) for a list of existing or upcoming projects proposals for TFX Addons.

## Tutorials and examples
See [`examples/`](examples/)
for end-to-end examples of various addons.

## Contributing

TFX Addons is a community-led project. Please have a look at our contributing and development guides if you want to contribute to the project: [CONTRIBUTING.md](https://github.com/tensorflow/tfx-addons/blob/main/CONTRIBUTING.md)

### Meeting cadence:

We meet bi-weekly on Wednesday. Check out our [Meeting notes](https://docs.google.com/document/d/1T0uZPoZhwNStuKkeCNsfE-kfc-PINISKIitYxkTK3Gw/edit?resourcekey=0-N9vT9Tn171wYplyYn4IPjQ) and join [sig-tfx-addons@tensorflow.com](https://groups.google.com/a/tensorflow.org/g/sig-tfx-addons) to get invited to the meeting.

## Package releases

Check out [RELEASE.md](https://github.com/tensorflow/tfx-addons/blob/main/RELEASE.md) to learn how TFX Addons is released.

## Resources

- [sig-tfx-addons@tensorflow.org](https://groups.google.com/a/tensorflow.org/g/sig-tfx-addons) – Join our Google group
- [tfx@tensorflow.org](https://groups.google.com/a/tensorflow.org/g/tfx) – General TFX mailing list
- [TFX Addons Slack](https://tfxaddons.slack.com) -  join [here](https://join.slack.com/t/tfxaddons/shared_invite/zt-tu1981lj-npIhRSHF8gl9G0ldUovbcw)
- [SIG Repository](http://github.com/tensorflow/tfx-addons) (this repo)
- [SIG Charter](https://github.com/tensorflow/community/blob/master/sigs/tfx-addons/CHARTER.md)


text:
package com.litesuits.orm.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;

/**
 * @author MaTianyu
 * @date 2015-03-23
 */
public class TestNext {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        Stack<String> stack = new Stack<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        stack.add("a");
        stack.add("b");
        Iterator it = list.iterator();
        System.out.println(it.next());
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        //System.out.println(it.next());

        //it = stack.iterator();
        //System.out.println(it.next());
        //System.out.println(it.next());
        //System.out.println(it.next());
    }
}


text:
namespace GraphQLTemplate.IntegrationTest.Controllers;

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
#if Serilog
using Xunit.Abstractions;
#endif

public class SchemaTest : CustomWebApplicationFactory<Program>
{
    private readonly HttpClient client;

#if Serilog
    public SchemaTest(ITestOutputHelper testOutputHelper)
        : base(testOutputHelper) =>
#else
    public SchemaTest() =>
#endif
            this.client = this.CreateClient();

    [Fact]
    public async Task GetSchemaDescriptionLanguage_Default_Returns200OkAsync()
    {
        var response = await this.client.GetAsync(new Uri("/graphql?sdl", UriKind.Relative)).ConfigureAwait(false);
        var sdl = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.NotEmpty(sdl);
    }
}


text:
#ifndef SFML_VECTOR3_HPP
#define SFML_VECTOR3_HPP

namespace sf
{
////////////////////////////////////////////////////////////
/// Vector3 is an utility class for manipulating 3 dimensional
/// vectors. Template parameter defines the type of coordinates
/// (integer, float, ...)
////////////////////////////////////////////////////////////
template <typename T>
class Vector3
{
public :

    ////////////////////////////////////////////////////////////
    /// Default constructor
    ///
    ////////////////////////////////////////////////////////////
    Vector3();

    ////////////////////////////////////////////////////////////
    /// Construct the vector from its coordinates
    ///
    /// \param X : X coordinate
    /// \param Y : Y coordinate
    /// \param Z : Z coordinate
    ///
    ////////////////////////////////////////////////////////////
    Vector3(T X, T Y, T Z);

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    T x; ///< X coordinate of the vector
    T y; ///< Y coordinate of the vector
    T z; ///< Z coordinate of the vector
};

////////////////////////////////////////////////////////////
/// Operator - overload ; returns the opposite of a vector
///
/// \param V : Vector to negate
///
/// \return -V
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T> operator -(const Vector3<T>& V);

////////////////////////////////////////////////////////////
/// Operator += overload ; add two vectors and assign to the first op
///
/// \param V1 : First vector
/// \param V2 : Second vector
///
/// \return V1 + V2
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T>& operator +=(Vector3<T>& V1, const Vector3<T>& V2);

////////////////////////////////////////////////////////////
/// Operator -= overload ; subtract two vectors and assign to the first op
///
/// \param V1 : First vector
/// \param V2 : Second vector
///
/// \return V1 - V2
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T>& operator -=(Vector3<T>& V1, const Vector3<T>& V2);

////////////////////////////////////////////////////////////
/// Operator + overload ; adds two vectors
///
/// \param V1 : First vector
/// \param V2 : Second vector
///
/// \return V1 + V2
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T> operator +(const Vector3<T>& V1, const Vector3<T>& V2);

////////////////////////////////////////////////////////////
/// Operator - overload ; subtracts two vectors
///
/// \param V1 : First vector
/// \param V2 : Second vector
///
/// \return V1 - V2
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T> operator -(const Vector3<T>& V1, const Vector3<T>& V2);

////////////////////////////////////////////////////////////
/// Operator * overload ; multiply a vector by a scalar value
///
/// \param V : Vector
/// \param X : Scalar value
///
/// \return V * X
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T> operator *(const Vector3<T>& V, T X);

////////////////////////////////////////////////////////////
/// Operator * overload ; multiply a scalar value by a vector
///
/// \param X : Scalar value
/// \param V : Vector
///
/// \return X * V
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T> operator *(T X, const Vector3<T>& V);

////////////////////////////////////////////////////////////
/// Operator *= overload ; multiply-assign a vector by a scalar value
///
/// \param V : Vector
/// \param X : Scalar value
///
/// \return V * X
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T>& operator *=(Vector3<T>& V, T X);

////////////////////////////////////////////////////////////
/// Operator / overload ; divide a vector by a scalar value
///
/// \param V : Vector
/// \param X : Scalar value
///
/// \return V / X
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T> operator /(const Vector3<T>& V, T X);

////////////////////////////////////////////////////////////
/// Operator /= overload ; divide-assign a vector by a scalar value
///
/// \param V : Vector
/// \param X : Scalar value
///
/// \return V / X
///
////////////////////////////////////////////////////////////
template <typename T>
Vector3<T>& operator /=(Vector3<T>& V, T X);

////////////////////////////////////////////////////////////
/// Operator == overload ; compares the equality of two vectors
///
/// \param V1 : First vector
/// \param V2 : Second vector
///
/// \return True if V1 is equal to V2
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator ==(const Vector3<T>& V1, const Vector3<T>& V2);

////////////////////////////////////////////////////////////
/// Operator != overload ; compares the difference of two vectors
///
/// \param V1 : First vector
/// \param V2 : Second vector
///
/// \return True if V1 is different than V2
///
////////////////////////////////////////////////////////////
template <typename T>
bool operator !=(const Vector3<T>& V1, const Vector3<T>& V2);

#include <SFML/System/Vector3.inl>

// Define the most common types
typedef Vector3<int>   Vector3i;
typedef Vector3<float> Vector3f;

} // namespace sf

#endif // SFML_VECTOR3_HPP


text:
{# NOT DRY AT ALL #}
{% extends "base.html" %}
{% load staticfiles %}

{% block load_js %}
    {# CRUDE #}

{% endblock %}

{% block breadcrumbs %}

Diseases

{{ object }}

{% endblock %}

{% block content %}

                {{ object }} {{ page_name }}

        {# TEMPORARILY FOR COVID ONLY #}

            {% include "diseases/covid_links.html" %}

    {% if page_description %}

        <button class="btn btn-info" type="button" data-toggle="collapse" data-target="#disease_page_description" aria-expanded="false" aria-controls="example_expand">
            Show/Hide Page Description
        </button>
        {# Crude style #}

                {{ page_description.description }}

    {% endif %}

            {% for type_components in components %}
                {% if type_components.0 == 'MPS-Db Models' %}

                                    View
                                    Edit
                                    Model Name
                                    Organ
                                    Device
                                    Center
                                    Description

                            {% for disease_model in disease_models %}

                                    {# Why is the target blank here? #}
                                    View

                                    {% if disease_model.is_editable %}
                                    Edit
                                    {% else %}
                                    <button disabled class="btn btn-default" title="You do not have permission to edit this entry." >Edit</button>
                                    {% endif %}

                                    {{ disease_model }}
                                    {{ disease_model.organ|default_if_none:"" }}
                                    {{ disease_model.device|default_if_none:"" }}
                                    {{ disease_model.center|default_if_none:"" }}
                                    {{ disease_model.description }}

                            {% endfor %}

                {% else %}
                {% if type_components.1 %}
                {% include 'diseases/generic_disease_link_table.html' with type=type_components.0 components=type_components.1 subtype=type_components.2 %}
                {% else %}

                            Error:
                            No information available

                {% endif %}
                {% endif %}
            {% endfor %}

            Suggest Additional Sources

        {% if add_model_button %}

            Add New Model

        {% endif %}
        {% if add_study_button %}

            Add New Study

        {% endif %}

{% endblock %}


text:
package core

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/mitchellh/mapstructure"
)

type Workunit_Unique_Identifier struct {
	Task_Unique_Identifier `bson:",inline" json:",inline" mapstructure:",squash"` // TaskName, Workflow, JobId
	Rank                   int                                                    `bson:"rank" json:"rank" mapstructure:"rank"` // this is the local identifier, an abstract identifer for the data chunk
}

func New_Workunit_Unique_Identifier(task Task_Unique_Identifier, rank int) (wui Workunit_Unique_Identifier) {

	wui = Workunit_Unique_Identifier{}
	wui.Task_Unique_Identifier = task
	wui.Rank = rank

	return
}

func (w Workunit_Unique_Identifier) String() (work_str string, err error) {

	var task_string string
	task_string, err = w.Task_Unique_Identifier.String()

	work_str = fmt.Sprintf("%s_%d", task_string, w.Rank)
	return
}

func (w Workunit_Unique_Identifier) GetTask() Task_Unique_Identifier {
	return w.Task_Unique_Identifier
}

func New_Workunit_Unique_Identifier_from_interface(original interface{}) (wui Workunit_Unique_Identifier, err error) {

	wui = Workunit_Unique_Identifier{}

	err = mapstructure.Decode(original, &wui)
	if err != nil {
		err = fmt.Errorf("(New_Workunit_Unique_Identifier_from_interface) mapstructure returs: %s", err.Error())
		return
	}

	return
}

func New_Workunit_Unique_Identifier_FromString(old_style_id string) (w Workunit_Unique_Identifier, err error) {

	array := strings.Split(old_style_id, "_")

	//if len(array) != 3 {
	//	err = fmt.Errorf("Cannot parse workunit identifier: %s", old_style_id)
	//	return
	//}

	a_len := len(array)

	rank_string := array[a_len-1]
	rank, err := strconv.Atoi(rank_string)
	if err != nil {
		return
	}

	prefix := ""
	if len(array) > 1 {
		prefix = strings.Join(array[0:a_len-1], "_")
	}

	var t Task_Unique_Identifier
	t, err = New_Task_Unique_Identifier_FromString(prefix)
	if err != nil {
		err = fmt.Errorf("(New_Workunit_Unique_Identifier_FromString) New_Task_Unique_Identifier_FromString returns: %s (prefix=%s, old_style_id=%s)", err.Error(), prefix, old_style_id)
		return
	}

	w = New_Workunit_Unique_Identifier(t, rank)

	return
}


text:
	<?php echo create_breadcrumb('Home'); ?>

Setting Management Function to create setting

			<?php echo $error_message; ?>

Setting Management - Table

                	<?php echo form_open_multipart('setting/save',array('id' => 'form_add')); ?>

						<?php
						if($setting_list->num_rows() > 0) :
							foreach($setting_list->result() as $row_setting) :
								$filter_field = str_replace("_", " ", $row_setting->SETTING_NAME);
								$filter_field = ucwords(strtolower($filter_field));
								?>

							<?php echo form_label($filter_field.'*') ?>

								<?php echo form_hidden('setting_id[]', $row_setting->SETTING_ID); ?>
								<?php echo form_input(array('type' => 'text', 'name' => 'setting_value[]','value' => $row_setting->SETTING_VALUE,'class' => 'form-control')); ?>

								<?php if(preg_match('/^(https?:\/\/)/',$row_setting->SETTING_VALUE)) {
									echo '
									    Change URL from File Manager
									';
								} ?>

					    <?php endforeach;
					    endif; ?>

							<?php echo form_input(array('type' => 'hidden', 'name' => $csrf['name'],'value' => $csrf['hash'],'class' => 'form-control','required' => 'required')); ?>

							<?php echo form_submit('form_user_submit', 'Submit Form', 'class="btn btn-sm btn-primary"');?>

					        <button type="button" class="close" data-dismiss="modal">×</button>

File Manager

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

					<?php echo form_close(); ?>


text:
          {{ endpoint.host }}:{{ port.port }}
          <mat-icon *ngIf="!hideExternalIcon"
                    class="kd-endpoint-icon">open_in_new</mat-icon>

          {{ endpoint.host }}:{{ port.nodePort }}
          <mat-icon *ngIf="!hideExternalIcon"
                    class="kd-endpoint-icon">open_in_new</mat-icon>

        {{ endpoint.host }}
        <mat-icon *ngIf="!hideExternalIcon"
                  class="kd-endpoint-icon">open_in_new</mat-icon>

-


text:
class CFixFieldFormatter
{
public:
	CFixFieldFormatter();
	CFixFieldFormatter(const std::string& name);
public:
	void AddEnum(const std::string& key, const std::string& value);
	void AddEnums(const CFixFieldFormatter& formatter);
	void Format(const std::string& st, std::ostream& stream)const;
private:
	std::string m_name;
	std::map<std::string, std::string> m_enums;
};


text:
ServicioPedirInformacion::ServicioPedirInformacion(SharedDataBase* shared, MensajeHTTPRequest* mensajeHTTP, CredencialesDeUsuarios* credenciales){
    Logger::Instance()->log(INFO, "Se crea el Servicio para Pedir Informacion sobre un Usuario");
    this->shared = shared;
    this->mensajeHTTP = mensajeHTTP;
    this->credenciales = credenciales;

    this->atenderPedidoDeInformacion();
}

ServicioPedirInformacion::~ServicioPedirInformacion()
{
    //dtor
}

void ServicioPedirInformacion::atenderPedidoDeInformacion(){
    int idSharedUsuarioPedido = this->credenciales->getIDSharedDe(  this->mensajeHTTP->getHeader("UsuarioPedido")  );
    Usuario usuario = this->shared->obtenerPerfilDelUsuario(idSharedUsuarioPedido );
    RespuestaInformacionPedida* respuestaInformacion = new RespuestaInformacionPedida();
    respuestaInformacion->setRespuestaInformacionPedida(usuario);
    this->respuesta = respuestaInformacion;
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Code Editor + RequireJS</title>
  <link rel="stylesheet" href="style.css">

Code Editor + RequireJS Visual Test

Open Developer tools > Console

'use strict';

/* Animal.js */

var Entity = require('back4app-entity').models.Entity;

module.exports = Entity.specify({
  name: 'Animal',
  attributes: {
    name: {
      type: 'String'
    },
    createdAt: {
      type: 'Datetime',
      default: Date.now
    }
  },
  methods: {
    getInfo: function () {
      return 'I am ' + this.name + ', created at ' + new Date(this.createdAt);
    }
  }
});

    <button id="run-code-btn">Run Code</button>


text:
from selenium import webdriver
from time import sleep

driver=webdriver.Firefox()

for num in range(0,50):
    # driver = webdriver.Firefox()
    driver.get("*********")
    sleep(1)


text:
import diff from 'deep-diff';
import type { Difference } from 'deep-diff';

(diff('', ''): ?Difference[]);
(diff({}, {}): ?Difference[]);
const A: ?Difference[] = diff.diff(1, 2);

if (A) {
  // $ExpectError needs difference
  diff.applyChange({}, {});
  diff.applyChange({}, {}, A[0]);
  // $ExpectError needs difference
  diff.revertChange({}, {});
  diff.revertChange({}, {}, A[0])
}


text:
<?php

namespace console\models;

use Yii;

/**
 * This is the model class for table "field_data_field_series_picture_slideshow".
 *
 * @property string $entity_type
 * @property string $bundle
 * @property integer $deleted
 * @property string $entity_id
 * @property string $revision_id
 * @property string $language
 * @property string $delta
 * @property string $field_series_picture_slideshow_fid
 * @property string $field_series_picture_slideshow_alt
 * @property string $field_series_picture_slideshow_title
 * @property string $field_series_picture_slideshow_width
 * @property string $field_series_picture_slideshow_height
 */
class FieldDataFieldSeriesPictureSlideshow extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'field_data_field_series_picture_slideshow';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('db_tvod1');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['entity_type', 'deleted', 'entity_id', 'language', 'delta'], 'required'],
            [['deleted', 'entity_id', 'revision_id', 'delta', 'field_series_picture_slideshow_fid', 'field_series_picture_slideshow_width', 'field_series_picture_slideshow_height'], 'integer'],
            [['entity_type', 'bundle'], 'string', 'max' => 128],
            [['language'], 'string', 'max' => 32],
            [['field_series_picture_slideshow_alt'], 'string', 'max' => 512],
            [['field_series_picture_slideshow_title'], 'string', 'max' => 1024]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'entity_type' => 'Entity Type',
            'bundle' => 'Bundle',
            'deleted' => 'Deleted',
            'entity_id' => 'Entity ID',
            'revision_id' => 'Revision ID',
            'language' => 'Language',
            'delta' => 'Delta',
            'field_series_picture_slideshow_fid' => 'Field Series Picture Slideshow Fid',
            'field_series_picture_slideshow_alt' => 'Field Series Picture Slideshow Alt',
            'field_series_picture_slideshow_title' => 'Field Series Picture Slideshow Title',
            'field_series_picture_slideshow_width' => 'Field Series Picture Slideshow Width',
            'field_series_picture_slideshow_height' => 'Field Series Picture Slideshow Height',
        ];
    }
}


text:
<!DOCTYPE html>

<meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#fff">

  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">

<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">

  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">

    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">

<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">

  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">

  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">

  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#fff">

  <meta name="keywords" content="neuroscience, computation, systems biology, quantitative biology, physics, latex, matlab, python, adobe illustrator, graphics">

  <link rel="alternate" href="/atom.xml" title="shan" type="application/atom+xml">

<meta name="description" content="生命不息,折腾不止">
<meta property="og:type" content="website">
<meta property="og:title" content="shan">
<meta property="og:url" content="https://shawnqin.github.io/archives/2017/02/index.html">
<meta property="og:site_name" content="shan">
<meta property="og:description" content="生命不息,折腾不止">
<meta property="og:locale" content="zh-CN">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shan">
<meta name="twitter:description" content="生命不息,折腾不止">

  <link rel="canonical" href="https://shawnqin.github.io/archives/2017/02/">

  <title>Archive | shan</title>

        shan

    <button>

    </button>

            Home

            About

            Tags

            Categories

            Archives

            Search

      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">

        Um..! 29 posts in total. Keep on posting.

2017

                Learning python

        <time class="post-time" itemprop="dateCreated" datetime="2017-02-16T00:00:00+08:00" content="2017-02-16">
          02-16
        </time>

                Deep learning

        <time class="post-time" itemprop="dateCreated" datetime="2017-02-15T00:00:00+08:00" content="2017-02-15">
          02-15
        </time>

                Google scholar alerts

        <time class="post-time" itemprop="dateCreated" datetime="2017-02-14T00:00:00+08:00" content="2017-02-14">
          02-14
        </time>

Shanshan Qin

生命不息,折腾不止

                  29
                  posts

                  9
                  categories

                  66
                  tags

                RSS

                        GitHub

                        E-Mail

                        Twitter

                        FB Page

© 2016 — 2019

  Shanshan Qin

    总访问量次
    |
    总访客人
    |

    |

      Site words total count:

    12.8k

          0%


text:
package ru.job4j.collection.statistickollection;

import java.util.ArrayList;

public class Info {

    /**
     * показывает количество добавленных элеметов в коллекцию.
     */
    private int infoAboutNewAdded;

    /**
     * показывает количество удаленных элеметов в коллекции.
     */
    private int infoAbDeleletedElement;

    /**
     * показывает количество добавленных и удаленных элементов, и изменнных.
     */
    private java.util.List<String> listInfo = new ArrayList<>();

    private int changedElement = 0;

    /**
     * информируют объект о количестве добавленных и удалленнх элементов путем сравнения двух коллекций.
     *
     * @param previoues предыдущая коллекция.
     * @param current   текущая коллекция
     */
    public void makeInfoAboutAddadedElements(java.util.List<Store.User> previoues, java.util.List<Store.User> current) {
        String info;
        int sameElements = 0;
        for (Store.User userPr : previoues) {
            for (Store.User userCurrent : current) {
                if (userPr.id == userCurrent.id) {
                    sameElements++;
                }
            }
        }
        infoAbDeleletedElement = previoues.size() - sameElements;
        info = "" + infoAbDeleletedElement + "Was deleted";
        listInfo.add(info);
        infoAboutNewAdded = current.size() - sameElements;
        info = "" + infoAboutNewAdded + " Was added elemets";
        listInfo.add(info);
    }

    public void showChangedElement(java.util.List<Store.User> previoues, java.util.List<Store.User> current) {
        String info;
        for (Store.User userPr : previoues) {
            for (Store.User userCurrent : current) {
                if (userPr.id == userCurrent.id & !userPr.name.equals(userCurrent.name)) {
                    changedElement++;
                    info = " " + userPr.id + " " + "id Was changed";
                    listInfo.add(info);
                }
            }
        }
        info = " " + changedElement + " " + " Elements was changed";
        listInfo.add(info);
    }

    public int getInfoAboutNewAdded() {
        return infoAboutNewAdded;
    }

    public int getInfoAbDeleletedElement() {
        return infoAbDeleletedElement;
    }

    public java.util.List<String> getListInfo() {
        return listInfo;
    }

    public int getChangedElement() {
        return changedElement;
    }
}


text:
package com.github.megachucky.kafka.streams.machinelearning;

import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * This is helper class to workaround for Failing stream tests in Windows
 * environment KAFKA-6647.
 *
 * @author Jukka Karvanen
 *
 *         The causing issue is https://issues.apache.org/jira/browse/KAFKA-6647
 *         Replacing EmbeddedKafkaCluster with TestEmbeddedKafkaCluster will
 *         catch and ignore the exception happening during the tear down of the
 *         test The exception does not have affect to functionality
 */

public class TestEmbeddedKafkaCluster extends EmbeddedKafkaCluster {
    private static final Logger log = LoggerFactory.getLogger(TestEmbeddedKafkaCluster.class);

    public TestEmbeddedKafkaCluster(int numBrokers) {
        super(numBrokers);
    }

    public TestEmbeddedKafkaCluster(int numBrokers, Properties brokerConfig) {
        super(numBrokers, brokerConfig);
    }

    public TestEmbeddedKafkaCluster(int numBrokers, Properties brokerConfig, long mockTimeMillisStart) {
        super(numBrokers, brokerConfig, mockTimeMillisStart);
    }

    public TestEmbeddedKafkaCluster(int numBrokers, Properties brokerConfig, long mockTimeMillisStart,
            long mockTimeNanoStart) {
        super(numBrokers, brokerConfig, mockTimeMillisStart, mockTimeNanoStart);
    }

    public void after() {
        try {
            super.after();
        } catch (RuntimeException e) {
            log.warn("Ignoring exception, test failing in Windows due this exception {}", e);
        }
    }
}


text:
class base { private n() {} }
class derived extends base { private n() {} }


text:
(function() {
    angular.module('detailsModule', []).controller('DetailsController', ['$scope', '$routeParams', '$log', '$location', function($scope, $routeParams, $log, $location) {

        // save reference to the controller
        var ctrl = this;

        // save search parameters
        ctrl.number = $routeParams.number;

        // function to be called when the page is loaded
        var elaborate = function() {

            // search index of array
            var index = undefined;
            for(var i = 0, rooms = $scope.rooms, len = rooms.length; i < len; i++) {
                if(rooms[i].number == ctrl.number) {
                    index = i;
                }
            }

            // check if the room number is valid
            if (index == undefined) {
                $location.path('error');
            } else {

                // make this room accessible from the html
                ctrl.room = $scope.rooms[index];
                ctrl.states = ctrl.room.states;

                // map -> room location
                var map_source = null;
                ctrl.heading = null;

                // load correct map
                if (ctrl.room.building === 1) {
                    if (ctrl.room.floor === -1) {
                        map_source="../img/mappe/Povo1PT.svg";
                        ctrl.heading="Povo1 - Piano Terra";
                    } else if (ctrl.room.floor === 0) {
                        map_source="../img/mappe/Povo1P1.svg";
                        ctrl.heading="Povo1 - Primo Piano";
                    }
                } else if (ctrl.room.building === 2) {
                    if (ctrl.room.floor === -1) {
                        map_source="../img/mappe/Povo2PT.svg";
                        ctrl.heading="Povo2 - Piano Terra";
                    } else if (ctrl.room.floor === 0) {
                        map_source="../img/mappe/Povo2P1.svg";
                        ctrl.heading="Povo2 - Primo Piano";
                    }
                }

                // load map
                if (map_source != null) {
                    var s = Snap("#map_detail");
                    Snap.load(map_source, onSVGLoaded) ;
                }

                // function to load a SVG
                function onSVGLoaded( data ){
                    var rectID= "#"+(ctrl.room.number).toLowerCase();
                    var rect = data.select(rectID);
                    rect.attr("fill", "#42A5F5");
                    s.append( data );
                }

            }
        }

        // wait for data to load
        if($scope.loading) {
            $log.debug("Data loadng...");

            $scope.$watch('loading', function(newValue, oldValue) {
                if(!newValue && oldValue) {
                    $log.info("Data loaded!");
                    elaborate();
                }
            });

        } else {
            $log.info("Data already loaded...");
            elaborate();
        }

    }]);

})();


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Xunit;

namespace System.Data.Tests
{
    public class DataRowExtensionsTests
    {
        [Fact]
        public void Field_String_NullRowThrows()
        {
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.Field<int>(null, "foo"));
        }

        [Fact]
        public void Field_String_NullColumnNameThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            AssertExtensions.Throws<ArgumentNullException>("name", () => DataRowExtensions.Field<int>(row, columnName: null));
        }

        [Fact]
        public void Field_Column_NullRowThrows()
        {
            DataColumn column = new DataColumn();
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.Field<int>(null, column));
        }

        [Fact]
        public void Field_Column_NullColumnThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            AssertExtensions.Throws<ArgumentNullException>("column", () => DataRowExtensions.Field<int>(row, column: null));
        }

        [Fact]
        public void Field_Index_NullRowThrows()
        {
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.Field<int>(null, 0));
        }

        [Fact]
        public void Field_Index_NegativeIndexThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            Assert.Throws<IndexOutOfRangeException>(() => DataRowExtensions.Field<int>(row, columnIndex: -1));
        }

        [Fact]
        public void Field_IndexVersion_NullRowThrows()
        {
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.Field<int>(null, columnIndex: 0, version: DataRowVersion.Default));
        }

        [Fact]
        public void Field_IndexVersion_NegativeIndexThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            Assert.Throws<IndexOutOfRangeException>(() => DataRowExtensions.Field<int>(row, columnIndex: -1, version: DataRowVersion.Default));
        }

        [Fact]
        public void Field_NameVersion_NullRowThrows()
        {
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.Field<int>(null, columnName: "foo", version: DataRowVersion.Default));
        }

        [Fact]
        public void Field_NameVersion_NullColumnNameThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            AssertExtensions.Throws<ArgumentNullException>("name", () => DataRowExtensions.Field<int>(row, columnName: null, version: DataRowVersion.Default));
        }

        [Fact]
        public void Field_ColumnVersion_NullRowThrows()
        {
            DataColumn column = new DataColumn();
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.Field<int>(null, column: column, version: DataRowVersion.Default));
        }

        [Fact]
        public void Field_ColumnVersion_NullColumnThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            AssertExtensions.Throws<ArgumentNullException>("column", () => DataRowExtensions.Field<int>(row, column: null, version: DataRowVersion.Default));
        }

        [Fact]
        public void SetField_IndexValue_NullRowThrows()
        {
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.SetField(null, columnIndex: 0, value: 0));
        }

        [Fact]
        public void SetField_IndexValue_NullColumnThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            Assert.Throws<IndexOutOfRangeException>(() => DataRowExtensions.SetField(row, columnIndex: -1, value: 0));
        }

        [Fact]
        public void SetField_IndexValue_NullValueReplacedByDBNull()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            table.Columns.Add(new DataColumn());

            DataRowExtensions.SetField<string>(row, columnIndex: 0, value: null);
            Assert.Equal(DBNull.Value, row[0]);
        }

        [Fact]
        public void SetField_NameValue_NullRowThrows()
        {
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.SetField(null, columnName: "foo", value: 0));
        }

        [Fact]
        public void SetField_NameValue_NullColumnNameThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            AssertExtensions.Throws<ArgumentNullException>("name", () => DataRowExtensions.SetField(row, columnName: null, value: 0));
        }

        [Fact]
        public void SetField_NameValue_NullValueReplacedByDBNull()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            table.Columns.Add(new DataColumn("foo"));

            DataRowExtensions.SetField<string>(row, columnName: "foo", value: null);
            Assert.Equal(DBNull.Value, row["foo"]);
        }

        [Fact]
        public void SetField_ColumnValue_NullRowThrows()
        {
            DataColumn column = new DataColumn();
            AssertExtensions.Throws<ArgumentNullException>("row", () => DataRowExtensions.SetField(null, column: column, value: 0));
        }

        [Fact]
        public void SetField_ColumnValue_NullColumnThrows()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            AssertExtensions.Throws<ArgumentNullException>("column", () => DataRowExtensions.SetField(row, column: null, value: 0));
        }

        [Fact]
        public void SetField_ColumnValue_NullValueReplacedByDBNull()
        {
            DataTable table = new DataTable("test");
            DataRow row = table.NewRow();
            DataColumn column = new DataColumn();
            table.Columns.Add(column);

            DataRowExtensions.SetField<string>(row, column: column, value: null);
            Assert.Equal(DBNull.Value, row[column]);
        }

    }
}


text:
My configuration file for [Newsboat](https://newsboat.org/), which is an
actively maintained fork of [Newsbeuter](https://www.newsbeuter.org/).

## Installation

* Copy `config` to `$HOME/.newsboat`.


text:
from milk.supervised import randomforest
import numpy as np

def test_rf():
    from milksets import wine
    features, labels = wine.load()
    features = features[labels < 2]
    labels = labels[labels < 2]
    learner = randomforest.rf_learner()
    model = learner.train(features[::5], labels[::5])
    test = [model.apply(f) for f in features]
    assert np.mean(labels == test) > .7


text:
package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/mxschmitt/golang-url-shortener/internal/handlers/auth"
	"github.com/mxschmitt/golang-url-shortener/internal/stores"
	"github.com/mxschmitt/golang-url-shortener/internal/util"
	"github.com/pkg/errors"
)

var (
	secret           []byte
	server           *httptest.Server
	closeServer      func() error
	testingClaimData = auth.JWTClaims{
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 24 * 365).Unix(),
		},
		"google",
		"id",
		"name",
		"picture",
	}
	tokenString string
)

func TestCreateBackend(t *testing.T) {
	secret = util.GetPrivateKey()
	if err := util.ReadInConfig(); err != nil {
		t.Fatalf("could not reload config file: %v", err)
	}
	store, err := stores.New()
	if err != nil {
		t.Fatalf("could not create store: %v", err)
	}
	DoNotPrivateKeyChecking = true
	handler, err := New(*store)
	if err != nil {
		t.Fatalf("could not create handler: %v", err)
	}
	server = httptest.NewServer(handler.engine)
	closeServer = func() error {
		server.Close()
		if err := handler.CloseStore(); err != nil {
			return errors.Wrap(err, "could not close store")
		}
		return nil
	}
}

func TestCreateNewJWT(t *testing.T) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, testingClaimData)
	var err error
	tokenString, err = token.SignedString(secret)
	if err != nil {
		t.Fatalf("could not sign token: %v", err)
	}
}

func TestForbiddenReqest(t *testing.T) {
	resp, err := http.Post(server.URL+"/api/v1/protected/create", "application/json", nil)
	if err != nil {
		t.Fatalf("could not execute get request: %v", err)
	}
	if resp.StatusCode != http.StatusForbidden {
		t.Fatalf("incorrect status code: %d; got: %d", resp.StatusCode, http.StatusForbidden)
	}
}

func TestInvalidToken(t *testing.T) {
	req, err := http.NewRequest("POST", server.URL+"/api/v1/protected/create", nil)
	if err != nil {
		t.Fatalf("could not create request %v", err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "incorrect one")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatalf("could not execute post request: %v", err)
	}
	if resp.StatusCode != http.StatusForbidden {
		t.Fatalf("incorrect status code: %d; got: %d", resp.StatusCode, http.StatusForbidden)
	}
}

func TestCheckToken(t *testing.T) {
	body, err := json.Marshal(map[string]string{
		"Token": tokenString,
	})
	if err != nil {
		t.Fatalf("could not post to the backend: %v", err)
	}
	resp, err := http.Post(server.URL+"/api/v1/auth/check", "application/json", bytes.NewBuffer(body))
	if err != nil {
		t.Fatalf("could not execute get request: %v", err)
	}
	var data gin.H
	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
		t.Fatalf("could not decode json: %v", err)
	}
	tt := []struct {
		name          string
		currentValue  string
		expectedValue string
	}{
		{
			name:          "ID",
			currentValue:  data["ID"].(string),
			expectedValue: testingClaimData.OAuthID,
		},
		{
			name:          "Name",
			currentValue:  data["Name"].(string),
			expectedValue: testingClaimData.OAuthName,
		},
		{
			name:          "Picture",
			currentValue:  data["Picture"].(string),
			expectedValue: testingClaimData.OAuthPicture,
		},
		{
			name:          "Provider",
			currentValue:  data["Provider"].(string),
			expectedValue: testingClaimData.OAuthProvider,
		},
	}
	for _, tc := range tt {
		t.Run(fmt.Sprintf("Checking: %s", tc.name), func(t *testing.T) {
			if tc.currentValue != tc.expectedValue {
				t.Fatalf("incorrect jwt value: %s; expected: %s", tc.expectedValue, tc.currentValue)
			}
		})
	}

}
func TestCloseBackend(t *testing.T) {
	if err := closeServer(); err != nil {
		t.Fatalf("could not close server: %v", err)
	}
}


text:
FROM centos:latest
MAINTAINER Verhagen "https://github.com/verhagen"

# Cache date (see https://github.com/docker/docker/issues/3313)
ENV LAST_UPDATED "17-01-2015 13:30"

#RUN apt-get update && apt-get upgrade -q -y && apt-get install aptitude -q -y && apt-get clean

RUN yum install -y bash-completion \
  tar \
  openssh-server \
  lsof \
  java-1.7.0-openjdk

#  supervisor \

# Parasoft Virtualize
# Copy the *.tar.gz; unpack the file; run the *.sh installer
RUN mkdir -p /opt
COPY parasoft_virtualize_9.8_linux_x86_64.tar.gz /opt/parasoft_virtualize_9.8_linux_x86_64.tar.gz
RUN cd /opt && tar -xzvf parasoft_virtualize_9.8_linux_x86_64.tar.gz
RUN chmod +x /opt/parasoft_virtualize_9.8_linux_x86_64_20141024.sh
RUN mkdir -p /opt/parasoft/virtualize/9.8
RUN cd /opt && echo -e '1\n\n\n' | /opt/parasoft_virtualize_9.8_linux_x86_64_20141024.sh
RUN rm /opt/parasoft_virtualize*

# Create Virtualize data directory
RUN mkdir -p /var/opt/virtualize

# Configure Supervisor it to run Virtualize
ADD virtualize.conf /etc/supervisor/conf.d/

# Make sure SSH and RDP are exposed to the outside world
EXPOSE 22

#CMD ["supervisord", "-n"]


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class SpectroscopyAcquisitionPhaseRows extends AbstractTag
{

    protected $Id = '0018,9095';

    protected $Name = 'SpectroscopyAcquisitionPhaseRows';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Spectroscopy Acquisition Phase Rows';

}


text:
require 'active_job/retry/exponential_options_validator'

module ActiveJob
  class Retry < Module
    class ExponentialBackoffStrategy < ConstantBackoffStrategy
      def initialize(options)
        ExponentialOptionsValidator.new(options).validate!
        @retry_limit          = options.fetch(:limit, 1)
        @fatal_exceptions     = options.fetch(:fatal_exceptions, [])
        @retryable_exceptions = options.fetch(:retryable_exceptions, nil)
      end

      def retry_delay(attempt, _exception)
        (attempt**4 + 15 + (rand(30) * (attempt + 1))).seconds
      end
    end
  end
end


text:
package gov.sandia.cognition.learning.algorithm.tree;

import gov.sandia.cognition.learning.algorithm.BatchLearner;
import gov.sandia.cognition.learning.function.categorization.Categorizer;
import gov.sandia.cognition.learning.data.InputOutputPair;
import java.util.Collection;

/**
 * The {@code DeciderLearner} interface defines the functionality of a learner
 * that can be used to learn a decision function inside a decision tree.
 *
 * @param   <InputType>
 *      The input type to learn a decision for.
 * @param   <OutputType>
 *      The output type to learn a decision for.
 * @param   <CategoryType>
 *      The category type that the decider will output.
 * @param   <DeciderType>
 *      The type of the decision function being learned.
 * @author  Justin Basilico
 * @since   2.0
 */
public interface DeciderLearner<InputType, OutputType, CategoryType, DeciderType extends Categorizer<? super InputType, ? extends CategoryType>>
    extends BatchLearner
        <Collection<? extends InputOutputPair<? extends InputType, OutputType>>,
         DeciderType>
{
}


text:
Para imprimir esta presentación haga click en el link siguiente y luego elija "Imprimir" en el menú de su navegador.

Imprimir la presentación

Puede crear una versión en formato PDF de la misma manera, pero eligiendo, en lugar de una impresora, las opciones "Imprimir hacia archivo" o "Grabar".


text:
package edu.harvard.canvas_data.parser;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import org.apache.commons.io.FileUtils;

import edu.harvard.data.client.DataConfigurationException;
import edu.harvard.data.client.DataSetInfo;
import edu.harvard.data.client.DataSetInfoFile;
import edu.harvard.data.client.DataSetInfoTable;
import edu.harvard.data.client.FormatLibrary;
import edu.harvard.data.client.canvas.api.CanvasApiClient;
import edu.harvard.data.client.canvas.api.CanvasDataArtifact;
import edu.harvard.data.client.canvas.api.CanvasDataDump;
import edu.harvard.data.client.canvas.api.CanvasDataFile;
import edu.harvard.data.client.canvas.api.UnexpectedApiResponseException;

public class DumpManager {

  private static final Logger log = Logger.getLogger("Canvas Data");

  private final Configuration config;

  public DumpManager(final Configuration config) {
    this.config = config;
  }

  public boolean needToSaveDump(final CanvasDataDump dump) throws IOException {
    final String dirName = String.format("%05d", dump.getSequence());
    final Path archiveDir = config.getCanvasDataArchiveDirectory().resolve(dirName);
    if (!Files.exists(archiveDir)) {
      log.info("Dump needs to be saved; directory " + archiveDir + " does not exist.");
      return true;
    }
    final Path dumpInfoFile = DumpInformation.getFile(getArchiveDumpDir(dump));
    if (!Files.exists(dumpInfoFile)) {
      log.info("Dump needs to be saved; dump info file " + dumpInfoFile + " does not exist.");
      return true;
    }
    final DumpInformation info = DumpInformation.read(dumpInfoFile);
    if (info.getDownloadComplete() == null) {
      log.info("Dump needs to be saved; previous download to " + archiveDir + " did not complete.");
      return true;
    }
    final Date downloadStart = info.getDownloadStart();
    // Re-download any dump that was updated less than an hour before it was
    // downloaded before.
    final Date conservativeStart = new Date(downloadStart.getTime() - (60 * 60 * 1000));
    if (conservativeStart.before(dump.getUpdatedAt())) {
      log.info("Dump needs to be saved; downloaded to " + archiveDir + " less than an hour after it was last updated.");
      return true;
    }
    log.info("Dump does not need to be saved; already exists at " + archiveDir + ".");
    return false;
  }

  public boolean isValidDumpDirectory(final Path path) {
    if (!Files.exists(path) || !Files.isDirectory(path)) {
      log.info(path + " is not a valid dump. Directory does not exist");
      return false;
    }
    final Path dumpInfoFile = DumpInformation.getFile(path);
    if (!Files.exists(dumpInfoFile)) {
      log.info(path + " is not a valid dump. No dump info file at " + dumpInfoFile);
      return false;
    }
    return true;
  }

  public void saveDumpToTempDirectory(final CanvasApiClient api, final CanvasDataDump dump)
      throws IOException, UnexpectedApiResponseException, DataConfigurationException {
    final Path dumpDir = getScratchDumpDir(dump);
    log.info("Saving dump " + dump.getDumpId() + " to " + dumpDir);
    saveDump(api, dumpDir, dump);
  }

  public void saveDump(final CanvasApiClient api, final Path directory, final CanvasDataDump dump)
      throws IOException, UnexpectedApiResponseException, DataConfigurationException {
    final Date downloadStart = new Date();
    final DataSetInfo dataSetInfo = new DataSetInfo(DataSetInfo.getFileName(directory));
    dataSetInfo.setFormat(FormatLibrary.Format.CanvasDataFlatFiles);
    Files.createDirectories(directory);
    final Map<String, CanvasDataArtifact> artifactsByTable = dump.getArtifactsByTable();
    final List<String> tables = new ArrayList<String>(artifactsByTable.keySet());
    for (final String table : tables) {
      int fileIndex = 0;
      final Path tableDir = directory.resolve(table);
      final CanvasDataArtifact artifact = artifactsByTable.get(table);
      log.info("Dumping " + table + " to " + tableDir);
      final DataSetInfoTable tableInfo = new DataSetInfoTable(table);
      dataSetInfo.addTable(artifact.getTableName(), tableInfo);
      final List<CanvasDataFile> files = artifact.getFiles();
      for (int i=0; i<files.size(); i++) {
        final CanvasDataFile file = files.get(i);
        final CanvasDataDump refreshedDump = api.getDump(dump.getDumpId());
        final CanvasDataArtifact refreshedArtifact = refreshedDump.getArtifactsByTable().get(table);
        final CanvasDataFile refreshedFile = refreshedArtifact.getFiles().get(i);
        if (!refreshedFile.getFilename().equals(file.getFilename())) {
          log.warning("Mismatch in file name for refreshed dump. Expected" + refreshedFile.getFilename() + ", got " + file.getFilename());
        }
        final String filename = artifact.getTableName() + "-" + String.format("%05d", fileIndex++) + ".gz";
        final DataSetInfoFile fileInfo = refreshedFile.download(tableDir.resolve(filename));
        tableInfo.addFileInfo(fileInfo);
      }
    }
    final Path dumpInfoFile = DumpInformation.getFile(getScratchDumpDir(dump));
    final Date downloadEnd = new Date();
    new DumpInformation(dump, downloadStart, downloadEnd).write(dumpInfoFile);
    dataSetInfo.write();
  }

  public void archiveDump(final Path fromDir, final Path toDir) throws IOException {
    log.info("Archiving " + fromDir + " to " + toDir);
    Files.createDirectories(toDir.getParent());
    if (Files.exists(toDir)) {
      log.info(toDir + " exists. Deleting it");
      FileUtils.deleteDirectory(toDir.toFile());
    }
    final Set<PosixFilePermission> readOnly = new HashSet<PosixFilePermission>();
    readOnly.add(PosixFilePermission.OWNER_READ);
    readOnly.add(PosixFilePermission.GROUP_READ);
    readOnly.add(PosixFilePermission.OTHERS_READ);
    try (DirectoryStream<Path> listing = Files.newDirectoryStream(fromDir)) {
      for (final Path table : listing) {
        if (Files.isDirectory(table)) {
          try (DirectoryStream<Path> tableListing = Files.newDirectoryStream(table)) {
            for (final Path dumpFile : Files.newDirectoryStream(table)) {
              Files.setPosixFilePermissions(dumpFile, readOnly);
            }
          }
        }
      }
    }
    Files.move(fromDir, toDir);
  }

  public Path getScratchDumpDir(final CanvasDataDump dump) {
    final String dirName = String.format("%05d", dump.getSequence());
    return config.getCanvasDataScratchDirectory().resolve(dirName);
  }

  public Path getArchiveDumpDir(final CanvasDataDump dump) {
    final String dirName = String.format("%05d", dump.getSequence());
    return config.getCanvasDataArchiveDirectory().resolve(dirName);
  }

}