text:
//
//  XYCalendar.m
//  DiaryForXY
//
//  Created by 曹雪莹 on 16/11/1.
//  Copyright © 2016年 韩元旭. All rights reserved.
//

#import "XYCalendar.h"
#import "XYCanlendarCell.h"
#import "XYCalendarModel.h"
#import "XYWeekdaysView.h"

@interface XYCalendar () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) NSDate			*date;
@property (nonatomic, strong) NSCalendar		*myCalendar;
@property (nonatomic, strong) XYWeekdaysView	*weekdayView;
@property (nonatomic, strong) UICollectionView	*collectionView;
@property (nonatomic, copy  ) NSMutableArray<XYCalendarModel *> *models;

@end

static NSInteger kDateNumber, kLineCount;
static NSString * const kCellIdentifier	= @"canlendarCell";

@implementation XYCalendar

#pragma mark - init

- (instancetype)initWithFrame:(CGRect)frame {

	if (self = [super initWithFrame:frame]) {

		//	渐变背景色
//		[self setupBackgroud];
		self.backgroundColor = [UIColor clearColor];

		[self setupWeekdayView];
		[self setupCollectionView];
	}
	return self;
}

- (void)setupBackgroud {

	CAGradientLayer *gradient	= [CAGradientLayer layer];
	gradient.frame				= self.bounds;
	gradient.locations			= @[@0.25, @1.0];
	gradient.startPoint			= CGPointMake(0, 0);
	gradient.endPoint			= CGPointMake(1.0, 1.0);
	gradient.colors				= @[(__bridge id)[UIColor colorWithHexString:@"39CA74"].CGColor, (__bridge id)[UIColor colorWithHexString:@"30AD63"].CGColor];
	[self.layer addSublayer:gradient];
}

- (void)setupWeekdayView {

	kLineCount			= [self numberOfLine];
	kDateNumber			= kLineCount * 7;
	self.weekdayView	= [[XYWeekdaysView alloc] initWithFrame:CGRectMake(20, 0, self.size.width - 40, XYCalenderHeight / (kLineCount+1))];
	[self addSubview:self.weekdayView];
}

- (void)setupCollectionView {

	UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
	layout.itemSize = CGSizeMake((XYScreenWidth-40) / 7, self.size.height / (kLineCount+1));
	layout.minimumLineSpacing		= 0;
	layout.minimumInteritemSpacing	= 0;

	self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(20, XYCalenderHeight / (kLineCount+1), self.weekdayView.size.width, XYCalenderHeight / (kLineCount+1) * kLineCount) collectionViewLayout:layout];
	self.collectionView.delegate		= self;
	self.collectionView.dataSource		= self;
	self.collectionView.backgroundColor = [UIColor clearColor];
	[self.collectionView registerClass:[XYCanlendarCell class] forCellWithReuseIdentifier:kCellIdentifier];

	[self addSubview:self.collectionView];
}

#pragma mark - UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

	return kDateNumber;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

	XYCanlendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
	cell.cellModel = self.models[indexPath.row];

	return cell;
}

#pragma mark - 方法
/**
 *  根据当前月获取有多少天
 */
- (NSUInteger)getNumberOfDays:(NSDate *)dayDate {

	NSRange range = [self.myCalendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:dayDate];

	return range.length;
}

/**
 *  确定输入日期所在月份的第一天
 */
- (NSDate *)firstDayOfCurrentMonth:(NSDate *)inputDate {

	NSDate *startDate = nil;
	BOOL ok = [self.myCalendar rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:inputDate];
	NSAssert1(ok, @"Failed to calculate the first day of the month based on %@", self);
	return startDate;
}

/**
 *  根据时间获取周几 - 星期日为1,星期六为7
 */
- (NSInteger)weekdayStringFromDate:(NSDate *)inputDate {

	NSDateComponents *theComponents = [self.myCalendar components:NSCalendarUnitWeekday fromDate:inputDate];

	//	theComponents.weekday - 星期日为1,星期六为7
	return theComponents.weekday;
}

/**
 获取年份
 */
- (NSInteger)currentYear {

	NSDateComponents *components = [self.myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
	NSInteger year = [components year];
	return year;
}

/**
 获取月份
 */
- (NSInteger)currentMonth {

	NSDateComponents *components = [self.myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
	NSInteger month = [components month];
	return month;
}

/**
 获取日期
 */
- (NSInteger)currentDay {

	NSDateComponents *components = [self.myCalendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self.date];
	NSInteger day = [components day];
	return day;
}

/**
 *  计算本月日期应该显示几行
 */
- (NSInteger)numberOfLine {

	NSInteger line = 0;

	//	本月第一天
	NSDate *firstDay	= [self firstDayOfCurrentMonth:self.date];
	//	本月全部天数
	NSUInteger length	= [self getNumberOfDays:self.date];
	//	第一天为周几
	NSInteger index		= [self weekdayStringFromDate:firstDay];
	NSInteger count		= index - 1 + length;
	if (count <= 28) {

		line = 4;
	} else if (count > 28 && count <= 35) {

		line = 5;
	} else {

		line = 6;
	}

	return line;
}

#pragma mark ---

- (NSDate *)date {

	if (_date == nil) {

		NSDate *tmpDate		= [NSDate date];
		//	系统所在时区
		NSTimeZone *zone	= [NSTimeZone systemTimeZone];
		NSInteger interval	= [zone secondsFromGMTForDate:tmpDate];
		_date				= [tmpDate  dateByAddingTimeInterval: interval];
	}
	return _date;
}

- (NSCalendar *)myCalendar {

	if (_myCalendar == nil) {

		_myCalendar = [NSCalendar currentCalendar];
		[_myCalendar setTimeZone:[[NSTimeZone alloc] initWithName:@"UTC"]];
	}
	return _myCalendar;
}

- (NSMutableArray<XYCalendarModel *> *)models {

	if (!_models) {

		_models = [NSMutableArray arrayWithCapacity:kDateNumber];
		NSDate *firstDay	= [self firstDayOfCurrentMonth:self.date];
		NSUInteger length	= [self getNumberOfDays:self.date];
		NSInteger index		= [self weekdayStringFromDate:firstDay];
		NSInteger today		= [self currentDay];
		NSInteger i = 0, k = 1;

		//	初始化本月1号之前
		for (i = 0; i < index-1; i++) {

			XYCalendarModel *model = [XYCalendarModel new];
			model.date = @"";
			[_models addObject:model];
		}

		for (i = 0; i < length; i++) {

			XYCalendarModel *model = [XYCalendarModel new];
			model.date = [NSString stringWithFormat:@"%ld", (long)k];
			if (k == today) {
				model.isToday = YES;
				model.isWritten = YES;
			}
			[_models addObject:model];
			k++;
		}

		for (i = 0; i < kDateNumber - length - index + 1; i++) {

			XYCalendarModel *model = [XYCalendarModel new];
			model.date = @"";
			[_models addObject:model];
		}
	}
	return _models;
}

@end


text:
On Docker hub [ssh-hpn-x](https://registry.hub.docker.com/u/yantis/ssh-hpn-x/)
on Github [docker-ssh-hpn-x](https://github.com/yantis/docker-ssh-hpn-x)

[High Performance SSH/SCP - HPN-SSH](http://www.psc.edu/index.php/hpn-ssh) with X-Forwarding support.
OpenSSH_6.8p1-hpn14v5, OpenSSL 1.0.2a 19 Mar 2015

### Docker Images Structure
>[yantis/archlinux-tiny](https://github.com/yantis/docker-archlinux-tiny)
>>[yantis/archlinux-small](https://github.com/yantis/docker-archlinux-small)
>>>[yantis/archlinux-small-ssh-hpn](https://github.com/yantis/docker-archlinux-ssh-hpn)
>>>>[yantis/ssh-hpn-x](https://github.com/yantis/docker-ssh-hpn-x)
>>>>>[yantis/dynamic-video](https://github.com/yantis/docker-dynamic-video)
>>>>>>[yantis/virtualgl](https://github.com/yantis/docker-virtualgl)
>>>>>>>[yantis/wine](https://github.com/yantis/docker-wine)

This layer adds 33MB to the [archlinux-small-ssh-hpn]
(https://registry.hub.docker.com/u/yantis/archlinux-small-ssh-hpn/) layer. You would run it just like you would that one but this time include
a -X (or -Y if that doesn't work) when SSHing in.

```bash
ssh -Y docker@hostname -p 49158
```

Preinstalled with xterm, xeyes, and xcalc for testing.
You should be able to type any of those out of the box and it should work.

There are security implications associated with X-Forwarding.
It is advisable to read up on it. This is a good [post](https://padraic2112.wordpress.com/2007/07/09/bad-security-201-remote-x-sessions-over-ssh/)
If you absolutly trust the host you should be fine (ie: as an example I run X-forwarding on AWS where my IP is the only allowed IP in security group).

Here is a screenshot of wireshark launched on an AWS ec2 instance.
![](http://yantis-scripts.s3.amazonaws.com/screenshot_20150409-014946.jpg)

If you have AWS and If this is something you want to play with check out the [launch.sh](https://github.com/yantis/docker-ssh-hpn-x/blob/master/launch.sh)
script on github. It will create a new AWS ec2 instance, install docker and launch the container then log you in. It should work with the AWS free tier.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Lc\LcBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Lc\LcBundle\Entity\Hobby;
use Lc\LcBundle\Form\HobbyType;

/**
 * Hobby controller.
 *
 */
class HobbyController extends Controller
{

    /**
     * Lists all Hobby entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('LcLcBundle:Hobby')->findAll();

        return $this->render('LcLcBundle:Hobby:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Hobby entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Hobby();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('hobby_show', array('id' => $entity->getId())));
        }

        return $this->render('LcLcBundle:Hobby:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Hobby entity.
     *
     * @param Hobby $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Hobby $entity)
    {
        $form = $this->createForm(new HobbyType(), $entity, array(
            'action' => $this->generateUrl('hobby_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Hobby entity.
     *
     */
    public function newAction()
    {
        $entity = new Hobby();
        $form   = $this->createCreateForm($entity);

        return $this->render('LcLcBundle:Hobby:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Hobby entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('LcLcBundle:Hobby')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Hobby entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('LcLcBundle:Hobby:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Hobby entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('LcLcBundle:Hobby')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Hobby entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('LcLcBundle:Hobby:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Hobby entity.
    *
    * @param Hobby $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Hobby $entity)
    {
        $form = $this->createForm(new HobbyType(), $entity, array(
            'action' => $this->generateUrl('hobby_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Hobby entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('LcLcBundle:Hobby')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Hobby entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('hobby_edit', array('id' => $id)));
        }

        return $this->render('LcLcBundle:Hobby:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Hobby entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('LcLcBundle:Hobby')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Hobby entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('hobby'));
    }

    /**
     * Creates a form to delete a Hobby entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('hobby_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
absolute.js
===========

> Simple MVC framework created for [JaggeryJS](https://github.com/wso2/jaggery).

The objective of absolute.js is to handle front-end development work with simplicity and conventions inside jaggeryJS. So let's get to the facts quick.

### Simple Configuration
First we have to redirect all the requests from jaggery configuration file to a jag file.
**jaggery.conf**

	{
	    "welcomeFiles": ["index.jag"],
	    "urlMappings": [
	        {
	            "url": "/*",
	            "path": "/index.jag"
	        }
	    ],
	    "logLevel": "info"
	}
Inside the index.jag file we will setup absolute.js and give a configuration. Also note that defaults are handled inside absolute.js.

**index.jag**

	<%
	var mvc = require ('absolute.js').mvc;
	var mvcp = new mvc({
		SERVER_URL:"/publisher/"
	});
	mvcp.route(request);
	%>

Now absolute.js is ready for request processing.

### Conventions
Below is the folder structure of absolute.js -

	└── project directory
       ├── assets
       ├── controller
	      ├── app.js
	      ├── console.js
       ├── index.jag
       ├── jaggery.conf
       ├── modules
	      ├── handlebars.js
	      ├── absolute.js
       ├── pages
	      ├── 1-column.hbs
       ├── views
	      ├── console
	      	 ├── view.hbs
	      ├── partials
	      	 ├── header.hbs
	      	 ├── footer.hbs

The concept of mvc is simple. We have a model, a view and a controller. In our example app we haven't followed a model approach to data (Note: This is also very simple since JSON and database library bridge exists in jaggery).

#### A Request procedure
The request comes to the absolute.js module. If the requst URI is - `/publisher/console/list`

	*	`/publisher` is the context of the app
	*	`/console` is the controller
	*	`/list` is the view

Controllers are contained in the controller folder of the context application. The controller is created with the same name. Inside the controller it will have a function named after the view. absolute.js will execute this function and the return json object will be provided to the template engine.

**console.js**

	list = function(){
		return {name:"Chan", quote:"I was a king I had a gold throne"};
	}
	manager = function(){
		//response.sendRedirect('/publisher/console/list');
		return {name:"Chan", quote:"I was a king I had a gold throne"};
	}
	upload = function(){
		return {name:"Chan", quote:"I was a king I had a gold throne"};
	}

I am currently working on the layout and partials handling inside absolute.js.

Note:- Initial credit of the idea of building a simple mvc framework for jaggery goes to  [Dilan](https://twitter.com/chatu_dil "Dilan")


text:
require 'rails_helper'
require 'passage_updater'

describe PassageUpdater, type: :strategy do
  context "for a nil current user," do
    it "raises an ArgumentError" do
      expect{ PassageUpdater.new(nil) }.to raise_error( ArgumentError )
    end
  end
  #-- -------------------------------------------------------------------------
  #++

  context "for any valid user," do
    let(:current_user)  { User.all.sample }
    subject { PassageUpdater.new( current_user ) }

    it "is a valid (new) instance" do
      expect( subject ).to be_a( PassageUpdater )
    end

    it_behaves_like( "(the existance of a method)", [
      :process!,
    ] )
    #-- -----------------------------------------------------------------------
    #++

    describe "#process" do
      let(:destroyable_passage) { Passage.order(created_at: :asc).limit(100).sample }
      let(:passage)             { Passage.includes(:meeting_individual_result).joins(:meeting_individual_result).limit(100).sample }
      let(:min)                 { (0..1).to_a.sample }
      let(:sec)                 { (0..59).to_a.sample }
      let(:hun)                 { (0..59).to_a.sample }
      let(:reaction)            { (0..99).to_a.sample }
      let(:timing_text)         { "#{ min }'#{ sec }\"#{ hun }" }
      let(:reaction_text)       { "0\"#{ reaction }" }

      context "for a valid user w/ incomplete parameters (nil Passage ID & timing)," do
        it "returns nil" do
          expect( subject.process!( nil, nil ) ).to be nil
        end
      end

      context "for a valid user w/ valid parameters (full data, existing Passage)," do
        let(:result) do
# DEBUG
#          puts "\r\nBEFORE Passage: #{ passage.inspect }, timing_text: #{ timing_text }"
          subject.process!( passage, timing_text, passage.passage_type_id, passage.meeting_individual_result_id, reaction_text )
        end

        it "returns the created or updated row instance" do
# DEBUG
#          puts "\r\nresult: #{ result.inspect }, timing_text: #{ timing_text }"
          expect( result ).to be_a( Passage )
        end
        it "persists the specified values into the row specified" do
          # Timing will be converted to delta-timing depending on its value, so we check both values with an OR:
          expect( min ).to eq( result.minutes ).or eq( result.minutes_from_start )
          expect( sec ).to eq( result.seconds ).or eq( result.seconds_from_start )
          expect( hun ).to eq( result.hundreds ).or eq( result.hundreds_from_start )
          expect( result.reaction_time.to_f ).to eq( TimingParser.parse( reaction_text ).to_hundreds / 100.0 )
          expect( result.passage_type_id ).to eq( passage.passage_type_id )
          expect( result.meeting_individual_result_id ).to eq( passage.meeting_individual_result_id )
        end
      end

      context "for a valid user w/ valid parameters (full data, existing Passage but no MIR & MPRG)," do
        let(:passage_wrongdata) do
          FactoryBot.create(
            :passage,
            meeting_individual_result_id: nil,
            meeting_program_id: nil,
            swimmer_id: Swimmer.limit(100).sample.id,
            team_id: Team.limit(100).sample.id
          )
        end
        let(:result) do
# DEBUG
#          puts "\r\nBEFORE Passage: #{ passage_wrongdata.inspect }, timing_text: #{ timing_text }"
          subject.process!( passage_wrongdata, timing_text, passage_wrongdata.passage_type_id, passage_wrongdata.meeting_individual_result_id, reaction_text )
        end

        it "returns the created or updated row instance" do
# DEBUG
#          puts "\r\nresult: #{ result.inspect }, timing_text: #{ timing_text }"
          expect( result ).to be_a( Passage )
        end
        it "persists the specified values into the Passage row specified" do
          # Timing will be converted to delta-timing depending on its value, so we check both values with an OR:
          expect( min ).to eq( result.minutes ).or eq( result.minutes_from_start )
          expect( sec ).to eq( result.seconds ).or eq( result.seconds_from_start )
          expect( hun ).to eq( result.hundreds ).or eq( result.hundreds_from_start )
          expect( result.reaction_time.to_f ).to eq( TimingParser.parse( reaction_text ).to_hundreds / 100.0 )
          expect( result.passage_type_id ).to eq( passage_wrongdata.passage_type_id )
          expect( result.meeting_individual_result_id ).to be nil
        end
      end

      context "for a valid user w/ valid parameters for an existing Passage row  but no timings," do
        let( :result ) do
          subject.process!( destroyable_passage, nil )
        end

        it "returns true to signal the deletion of the row" do
          expect( result ).to be true
        end
      end
    end # (#process)
    #-- -----------------------------------------------------------------------
    #++
  end
  #-- -------------------------------------------------------------------------
  #++
end


text:
package org.kuali.rice.core.api.criteria;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import java.math.BigInteger;

/**
 * A CriteriaValue which stores date and time information in the form of a
 * {@link BigInteger} value.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
@XmlRootElement(name = CriteriaIntegerValue.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = CriteriaIntegerValue.Constants.TYPE_NAME)
public final class CriteriaIntegerValue implements CriteriaValue<BigInteger> {

    @XmlValue
    private BigInteger value;

    CriteriaIntegerValue() {
        this.value = null;
    }

    CriteriaIntegerValue(BigInteger value) {
    	validateValue(value);
        this.value = safeInstance(value);
    }

    CriteriaIntegerValue(Number value) {
    	validateValue(value);
    	this.value = BigInteger.valueOf(value.longValue());
    }

    private static void validateValue(Object value) {
    	if (value == null) {
    		throw new IllegalArgumentException("Value cannot be null.");
    	}
    }

    /**
     * Since BigInteger is not technically immutable we defensively copy when needed.
     *
     * <p>
     * See Effective Java 2nd ed. page 79 for details.
     * </p>
     *
     * @param val the big integer to check
     * @return the safe BigInteger
     */
    private static BigInteger safeInstance(BigInteger val) {
        if (val.getClass() != BigInteger.class) {
            return new BigInteger(val.toByteArray());
        }
        return val;
    }

    @Override
    public BigInteger getValue() {
        return value;
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(obj, this);
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    /**
     * Defines some internal constants used on this class.
     */
    static class Constants {
        final static String ROOT_ELEMENT_NAME = "integerValue";
        final static String TYPE_NAME = "CriteriaIntegerValueType";
    }

}


text:
import os
import platform
import urllib
from io import BytesIO
from os import chdir, getcwd
from shutil import rmtree
from tempfile import mkdtemp

import numpy as np
import pytest
import requests
from PIL import Image

import coremltools as ct
from coremltools.converters.mil.mil import types

tf = pytest.importorskip("tensorflow", minversion="2.1.0")

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

@pytest.fixture
def int32_input_model():
    x = tf.keras.Input(batch_input_shape=(10, 20), name="input", dtype=tf.int32)
    out = tf.add(x, tf.constant(5, dtype=tf.int32), name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def float32_input_model_add_op():
    x = tf.keras.Input(batch_input_shape=(10, 20), name="input", dtype=tf.float32)
    out = tf.add(x, tf.constant(5.5, dtype=tf.float32), name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def float32_input_model_relu_ops():
    x = tf.keras.Input(batch_input_shape=(10, 20), name="input", dtype=tf.float32)
    x1 = tf.keras.layers.ReLU()(x)
    out = tf.keras.layers.ReLU(name="output")(x1)
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def int64_input_model():
    x = tf.keras.Input(batch_input_shape=(10, 20), name="input", dtype=tf.int64)
    out = tf.add(x, tf.constant(5, dtype=tf.int64), name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def float32_two_input_model():
    x = tf.keras.Input(batch_input_shape=(10, 20), name="input1", dtype=tf.float32)
    y = tf.keras.Input(batch_input_shape=(10, 20), name="input2", dtype=tf.float32)
    out = tf.add(x, y, name="output")
    return tf.keras.Model(inputs=[x, y], outputs=out)

@pytest.fixture
def float32_two_output_model():
    x = tf.keras.Input(batch_input_shape=(10, 20), name="input", dtype=tf.float32)
    y = tf.nn.relu(x)
    out2 = tf.nn.relu6(x, name="output2")
    out1 = tf.nn.relu(y, name="output1")
    return tf.keras.Model(inputs=x, outputs=[out1, out2])

@pytest.fixture
def rank3_input_model():
    x = tf.keras.Input(batch_input_shape=(1, 10, 20), name="input", dtype=tf.float32)
    out = tf.add(x, tf.constant(5, dtype=tf.float32), name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def rank4_input_model():
    x = tf.keras.Input(batch_input_shape=(1, 10, 20, 3), name="input", dtype=tf.float32)
    out = tf.add(x, tf.constant(5, dtype=tf.float32), name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def rank4_input_model_with_channel_first_output():
    x = tf.keras.Input(batch_input_shape=(1, 10, 20, 3), name="input", dtype=tf.float32)
    y = tf.add(x, tf.constant(5, dtype=tf.float32))
    out = tf.transpose(y, perm=[0, 3, 1, 2], name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def rank4_grayscale_input_model():
    x = tf.keras.Input(batch_input_shape=(1, 10, 20, 1), name="input", dtype=tf.float32)
    out = tf.add(x, tf.constant(5, dtype=tf.float32), name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def rank4_grayscale_input_model_with_channel_first_output():
    x = tf.keras.Input(batch_input_shape=(1, 10, 20, 1), name="input", dtype=tf.float32)
    y = tf.add(x, tf.constant(5, dtype=tf.float32))
    out = tf.transpose(y, perm=[0, 3, 1, 2], name="output")
    return tf.keras.Model(inputs=x, outputs=out)

@pytest.fixture
def linear_model():
    # this model will test the fuse_matmul_weight_bias pass
    x = tf.keras.Input(batch_input_shape=(1, 10), name="input", dtype=tf.float32)
    y = tf.keras.layers.Dense(4)(x)
    y = tf.add(y, tf.constant([1, 2, 3, 4], shape=(4,), dtype=tf.float32))
    out = tf.nn.relu(y)
    return tf.keras.Model(inputs=x, outputs=out)

#################################################################################
# Note: all tests are also used as examples in https://coremltools.readme.io/docs
# as a reference.
# Whenever any of the following test fails, we should update API documentations
#################################################################################

class TestTensorFlow2ConverterExamples:
    def setup_class(self):
        self._cwd = getcwd()
        self._temp_dir = mkdtemp()
        # step into temp directory as working directory
        # to make the user-facing examples cleaner
        chdir(self._temp_dir)

        # create toy models for conversion examples
        # write a toy tf.keras HDF5 model
        tf_keras_model = tf.keras.Sequential(
            [
                tf.keras.layers.Flatten(input_shape=(28, 28)),
                tf.keras.layers.Dense(128, activation=tf.nn.relu),
                tf.keras.layers.Dense(10, activation=tf.nn.softmax),
            ]
        )
        tf_keras_model.save("./tf_keras_model.h5")

        # write a toy SavedModel directory
        tf_keras_model.save("./saved_model", save_format="tf")

    def teardown_class(self):
        chdir(self._cwd)
        if os.path.exists(self._temp_dir):
            rmtree(self._temp_dir)

    @staticmethod
    def test_convert_tf_keras_h5_file():
        if platform.machine() == "arm64":
            pytest.xfail("rdar://101162740 ([CI] [TF] The tf_keras_h5_file API testing is failing on M1 with new OS)")

        for file_extension in ("h5", "hdf5"):
            x = tf.keras.Input(shape=(32,), name="input")
            y = tf.keras.layers.Dense(16, activation="softmax")(x)
            keras_model = tf.keras.Model(x, y)
            temp_dir = mkdtemp()
            save_dir = str(temp_dir)
            path = os.path.join(save_dir, "tf_keras_model." + file_extension)
            keras_model.save(path)
            mlmodel = ct.convert(path)

            test_input = np.random.rand(2, 32)
            expected_val = keras_model(test_input)
            results = mlmodel.predict({"input": test_input})
            np.testing.assert_allclose(results["Identity"], expected_val, rtol=1e-4)

    @staticmethod
    def test_convert_tf_keras_model():
        x = tf.keras.Input(shape=(32,), name="input")
        y = tf.keras.layers.Dense(16, activation="softmax")(x)
        keras_model = tf.keras.Model(x, y)

        mlmodel = ct.convert(keras_model)

        test_input = np.random.rand(2, 32)
        expected_val = keras_model(test_input)
        results = mlmodel.predict({"input": test_input})
        np.testing.assert_allclose(results["Identity"], expected_val, rtol=1e-4)

    @staticmethod
    @pytest.mark.parametrize(
            "dtype", ['default', 'mil_type', 'np type'])
    def test_convert_tf_keras_applications_model(dtype):
        tf_keras_model = tf.keras.applications.MobileNet(
            weights="imagenet", input_shape=(224, 224, 3)
        )

        # inputs / outputs are optional, we can get from tf.keras model
        # this can be extremely helpful when we want to extract sub-graphs
        input_name = tf_keras_model.inputs[0].name.split(":")[0]

        if dtype == 'default':
            dtype = None
        elif dtype == 'mil_type':
            dtype = types.fp32
        else:
            dtype = np.float32

        mlmodel = ct.convert(
            tf_keras_model,
            inputs=[ct.TensorType(shape=(1, 224, 224, 3), dtype=dtype)],
        )
        mlmodel.save("./mobilenet.mlmodel")

    @staticmethod
    def test_convert_from_saved_model_dir():
        # SavedModel directory generated by TensorFlow 2.x
        mlmodel = ct.convert("./saved_model")
        mlmodel.save("./model.mlmodel")

    @staticmethod
    def test_keras_custom_layer_model():
        # testing : https://coremltools.readme.io/docs/tensorflow-2#conversion-from-user-defined-models

        class CustomDense(layers.Layer):
            def __init__(self, units=32):
                super(CustomDense, self).__init__()
                self.units = units

            def build(self, input_shape):
                self.w = self.add_weight(
                    shape=(input_shape[-1], self.units),
                    initializer="random_normal",
                    trainable=True,
                )
                self.b = self.add_weight(
                    shape=(self.units,), initializer="random_normal", trainable=True
                )

            def call(self, inputs):
                return tf.matmul(inputs, self.w) + self.b

        inputs = keras.Input((4,))
        outputs = CustomDense(10)(inputs)
        model = keras.Model(inputs, outputs)
        ct.convert(model)

    @staticmethod
    def test_concrete_function_conversion():
        # testing : https://coremltools.readme.io/docs/tensorflow-2#conversion-from-user-defined-models

        @tf.function(input_signature=[tf.TensorSpec(shape=(6,), dtype=tf.float32)])
        def gelu_tanh_activation(x):
            a = (np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))
            y = 0.5 * (1.0 + tf.tanh(a))
            return x * y

        conc_func = gelu_tanh_activation.get_concrete_function()
        mlmodel = ct.convert([conc_func])

    @staticmethod
    def test_convert_tf2_keras():
        x = tf.keras.Input(shape=(32,), name="input")
        y = tf.keras.layers.Dense(16, activation="softmax")(x)
        keras_model = tf.keras.Model(x, y)
        model = ct.convert(keras_model, convert_to='milinternal')
        assert isinstance(model, ct.converters.mil.Program)

class TestTF2FlexibleInput:
    # Test examples in https://coremltools.readme.io/docs/flexible-inputs
    @staticmethod
    @pytest.mark.parametrize("use_symbol", [True, False])
    def test_tf2keras_shared_range_dim(use_symbol):
        input_dim = 3
        # None denotes seq_len dimension
        x1 = tf.keras.Input(shape=(None,input_dim), name="seq1")
        x2 = tf.keras.Input(shape=(None,input_dim), name="seq2")
        y = x1 + x2
        keras_model = tf.keras.Model(inputs=[x1, x2], outputs=[y])

        # One RangeDim shared by two inputs
        if use_symbol:
            seq_len_dim = ct.RangeDim(symbol='seq_len')
        else:
            # symbol is optional
            seq_len_dim = ct.RangeDim()
        seq1_input = ct.TensorType(name="seq1", shape=(1, seq_len_dim, input_dim))
        seq2_input = ct.TensorType(name="seq2", shape=(1, seq_len_dim, input_dim))
        mlmodel = ct.convert(keras_model,
                inputs=[seq1_input, seq2_input])

        batch = 1
        seq_len = 5
        test_input_x1 = np.random.rand(batch, seq_len, input_dim).astype(np.float32)
        test_input_x2 = np.random.rand(batch, seq_len, input_dim).astype(np.float32)
        expected_val = keras_model([test_input_x1, test_input_x2])
        if ct.utils._is_macos():
            results = mlmodel.predict({
                "seq1": test_input_x1,
                "seq2": test_input_x2})
            np.testing.assert_allclose(results["Identity"], expected_val,
                rtol=1e-2, atol=1e-2)

    @staticmethod
    def test_tf2keras_incorrect_range_dim():
        input_dim = 3
        # None denotes seq_len dimension
        x1 = tf.keras.Input(shape=(None,input_dim), name="seq1")
        y = x1 + 1
        keras_model = tf.keras.Model(inputs=[x1], outputs=[y])

        # Incorrectly using -1 instead of ct.RangeDim
        # One RangeDim shared by two inputs
        with pytest.raises(ValueError,
            match=r"Can\'t convert to CoreML shaping"):
            seq1_input = ct.TensorType(name="seq1", shape=(1, -1, input_dim))
            mlmodel = ct.convert(keras_model, inputs=[seq1_input])

    @staticmethod
    @pytest.mark.parametrize("use_symbol", [True, False])
    def test_tf2keras_outofbound_range_dim(use_symbol):
        input_dim = 3
        # None denotes seq_len dimension
        x = tf.keras.Input(shape=(None,input_dim), name="seq")
        y = x * 2
        keras_model = tf.keras.Model(inputs=[x], outputs=[y])

        if use_symbol:
            seq_len_dim = ct.RangeDim(symbol='sequence_len', lower_bound=3,
                    upper_bound=5)
        else:
            seq_len_dim = ct.RangeDim(lower_bound=3, upper_bound=5)
        seq_input = ct.TensorType(name="seq", shape=(1, seq_len_dim, input_dim))
        mlmodel = ct.convert(keras_model, inputs=[seq_input])

        # seq_len is within bound
        batch = 1
        seq_len = 3
        test_input_x = np.random.rand(batch, seq_len, input_dim).astype(np.float32)
        expected_val = keras_model([test_input_x])
        if ct.utils._is_macos():
            results = mlmodel.predict({"seq": test_input_x})
            np.testing.assert_allclose(results["Identity"], expected_val,
                rtol=1e-4, atol=1e-3)

            # seq_len below/above lower_bound/upper_bound
            with pytest.raises(RuntimeError,
                    match=r"Size \(2\) of dimension \(1\) is not in allowed range \(3\.\.5\)"):
                seq_len = 2
                test_input_x = np.random.rand(batch, seq_len,
                        input_dim).astype(np.float32)
                results = mlmodel.predict({"seq": test_input_x})

            with pytest.raises(RuntimeError,
                    match=r"Size \(6\) of dimension \(1\) is not in allowed range \(3\.\.5\)"):
                seq_len = 6
                test_input_x = np.random.rand(batch, seq_len,
                        input_dim).astype(np.float32)
                results = mlmodel.predict({"seq": test_input_x})

    @staticmethod
    def test_tf2_image_enumerated_shapes():
        keras_model = tf.keras.applications.MobileNetV2(
            input_shape=(None, None, 3,),
            classes=1000,
            include_top=False,
        )
        input_shapes = ct.EnumeratedShapes(shapes=[(1, 192, 192, 3), (1, 224, 224, 3)])
        image_input = ct.ImageType(shape=input_shapes,
                                   bias=[-1,-1,-1], scale=1/127)
        model = ct.convert(keras_model, inputs=[image_input])
        assert model is not None
        spec = model.get_spec()
        assert len(spec.description.input[0].type.imageType.enumeratedSizes.sizes) == 2

    @staticmethod
    def test_tf2keras_enumerated_shapes():
        input_shape = (28, 28, 3)
        # None denotes seq_len dimension
        x = tf.keras.Input(shape=input_shape, name="input")
        C_out = 2
        kHkW = 3
        y = tf.keras.layers.Conv2D(C_out, kHkW, activation='relu',
                input_shape=input_shape)(x)
        keras_model = tf.keras.Model(inputs=[x], outputs=[y])

        # One RangeDim shared by two inputs
        shapes = [(1, 28, 28, 3), (1, 56, 56, 3)]
        enumerated_shapes = ct.EnumeratedShapes(shapes=shapes)
        tensor_input = ct.TensorType(name="input", shape=enumerated_shapes)
        mlmodel = ct.convert(keras_model, inputs=[tensor_input])

        # Test (1, 28, 28, 3) shape
        test_input_x = np.random.rand(*shapes[0]).astype(np.float32)
        expected_val = keras_model([test_input_x])
        if ct.utils._is_macos():
            results = mlmodel.predict({
                "input": test_input_x})
            # rdar://101303143 ([CI] test_tf2keras_enumerated_shapes is getting some stochastic numerical issues on intel machines)
            # The tolerance is set a little bit big here. Need to investigate this issue if possible and lower the threshold down.
            np.testing.assert_allclose(results["Identity"],
                    expected_val, atol=1e-2, rtol=3)

            # Test (1, 56, 56, 3) shape (can't verify numerical parity with Keras
            # which doesn't support enumerated shape)
            test_input_x = np.random.rand(*shapes[1]).astype(np.float32)
            results = mlmodel.predict({
                "input": test_input_x})

            # Test with a wrong shape
            with pytest.raises(RuntimeError,
                    match=r"MultiArray Shape \(1 x 29 x 29 x 3\) was not in enumerated set of allowed shapes"):
                test_input_x = np.random.rand(1, 29, 29, 3).astype(np.float32)
                results = mlmodel.predict({
                    "input": test_input_x})

    @staticmethod
    def test_tf2keras_optional_input():
        input_dim = 3
        # None denotes seq_len dimension
        x1 = tf.keras.Input(shape=(None,input_dim), name="optional_input")
        x2 = tf.keras.Input(shape=(None,input_dim), name="required_input")
        y = x1 + x2
        keras_model = tf.keras.Model(inputs=[x1, x2], outputs=[y])

        seq_len_dim = ct.RangeDim()
        default_value = np.ones((1, 2, input_dim)).astype(np.float32)
        optional_input = ct.TensorType(
            name="optional_input",
            shape=(1, seq_len_dim, input_dim),
            default_value=default_value,
          )
        required_input = ct.TensorType(
            name="required_input",
            shape=(1, seq_len_dim, input_dim),
          )
        mlmodel = ct.convert(keras_model,
                inputs=[optional_input, required_input])

        batch = 1
        seq_len = 2
        test_input_x2 = np.random.rand(batch, seq_len, input_dim).astype(np.float32)
        expected_val = keras_model([default_value, test_input_x2])
        if ct.utils._is_macos():
            results = mlmodel.predict({"required_input": test_input_x2})
            np.testing.assert_allclose(results["Identity"], expected_val, rtol=1e-2)


text:
package main

import (
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
)

var db *sql.DB

func init() {
	var err error
	db, err = sql.Open("postgres", "postgres://postgres:@localhost:5432/postgres?sslmode=disable")
	if err != nil {
		fmt.Println(err)
		return
	}
}

func main() {
	rows, err := db.Query("SELECT id, name, address FROM public.address")
	if err != nil {
		fmt.Println(err)
		return
	}
	for rows.Next() {
		var name, address, id string
		err = rows.Scan(&id, &name, &address)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(id, name, address)
	}
}


text:
package measurement

import (
	"fmt"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/perf-tests/clusterloader2/api"
	"k8s.io/perf-tests/clusterloader2/pkg/errors"
)

// Execute executes a measurement, which can be a single measurement or a wrapper for multiple measurements.
// It throws an error if both identifier and Instances has been supplied in the config.
func Execute(mm Manager, m *api.Measurement) error {
	if len(m.Instances) != 0 && m.Identifier != "" {
		return fmt.Errorf("only one of instances or identifier must be supplied. Measurement method - %s, identifier - %s, instances - %v", m.Identifier, m.Method, m.Instances)
	}
	if m.Identifier != "" {
		return mm.Execute(m.Method, m.Identifier, m.Params)
	}
	return executeWrapperMeasurement(mm, m)
}

func executeWrapperMeasurement(mm Manager, m *api.Measurement) error {
	var wg wait.Group
	errList := errors.NewErrorList()
	for i := range m.Instances {
		identifier := m.Instances[i].Identifier
		measurementInstanceParams := m.Instances[i].Params
		// clone the measurement params
		measurementParams := make(map[string]interface{})
		for k, v := range m.Params {
			measurementParams[k] = v
		}
		// add/overwrite the measurement params with wrapper measurement params
		for paramsKey := range measurementInstanceParams {
			measurementParams[paramsKey] = measurementInstanceParams[paramsKey]
		}
		wg.Start(func() {
			if err := mm.Execute(m.Method, identifier, measurementParams); err != nil {
				errList.Append(fmt.Errorf("measurement call %s - %s error: %v", m.Method, identifier, err))
			}
		})
	}
	wg.Wait()
	if errList.IsEmpty() {
		return nil
	}
	return errList
}


text:
<?php

namespace Store\Bundle\BackendBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table
*/
class User extends BaseUser
{
    /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="Address" , mappedBy="user")
     */
    protected $address;

    /**
     * @ORM\OneToMany(targetEntity="Cart" , mappedBy="user")
     */
    protected $cart;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param mixed $address
     */
    public function setAddress($address)
    {
        $this->address = $address;
    }

    /**
     * @return mixed
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * @param mixed $cart
     */
    public function setCart($cart)
    {
        $this->cart = $cart;
    }

    /**
     * @return mixed
     */
    public function getCart()
    {
        return $this->cart;
    }

}


text:
define([], function() {
  "use strict";

  var init = function(text) {
    console.log("Search", text);
  };

  return {
    init: init
  };
});


text:
namespace Simple.Web
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using Cors;
    using Http;

    public class PublicFolder : IEquatable<PublicFolder>
    {
        private readonly Regex _rewrite;
        private readonly string _alias;
        private readonly string _path;
        private readonly CacheOptions _cacheOptions;
        private readonly IList<IAccessControlEntry> _accessControl;

        public PublicFolder(string path) : this(path, path)
        {
        }

        public PublicFolder(string path, params AccessControlEntry[] accessControl) : this(path, path, null, accessControl)
        {

        }

        public PublicFolder(string path, CacheOptions cacheOptions) : this(path, path, cacheOptions)
        {
        }

        public PublicFolder(string path, string alias) : this(path, alias, (CacheOptions)null)
        {
        }

        public PublicFolder(string path, string alias, params AccessControlEntry[] accessControl) : this(path, alias, null, accessControl)
        {
        }

        public PublicFolder(string path, string alias, CacheOptions cacheOptions, params AccessControlEntry[] accessControl)
        {
            if (path == null) throw new ArgumentNullException("path");
            if (alias == null) throw new ArgumentNullException("alias");
            _path = path;
            _alias = alias;
            _cacheOptions = cacheOptions;
            if (!path.Equals(alias, StringComparison.OrdinalIgnoreCase))
            {
                _rewrite = new Regex("^" + Regex.Escape(alias), RegexOptions.IgnoreCase);
            }
            if (accessControl != null)
            {
                _accessControl = accessControl;
            }
        }

        public string Path
        {
            get { return _path; }
        }

        public string Alias
        {
            get { return _alias; }
        }

        public CacheOptions CacheOptions
        {
            get { return _cacheOptions; }
        }

        public IList<IAccessControlEntry> AccessControl
        {
            get { return _accessControl; }
        }

        public string RewriteAliasToPath(string absolutePath)
        {
            return _rewrite == null ? absolutePath : _rewrite.Replace(absolutePath, _path);
        }

        public bool Equals(PublicFolder other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return string.Equals(_path, other._path) && string.Equals(_alias, other._alias);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;
            return Equals((PublicFolder) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (_path.GetHashCode()*397) ^ _alias.GetHashCode();
            }
        }

        public static bool operator ==(PublicFolder left, PublicFolder right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(PublicFolder left, PublicFolder right)
        {
            return !Equals(left, right);
        }

        public static implicit operator PublicFolder(string path)
        {
            return new PublicFolder(path);
        }
    }
}


text:
#include "gm/gm.h"
#include "include/core/SkBlendMode.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkMatrix.h"
#include "include/core/SkPoint.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkString.h"
#include "include/gpu/GrRecordingContext.h"
#include "include/private/GrTypesPriv.h"
#include "src/core/SkCanvasPriv.h"
#include "src/gpu/GrBuffer.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrDirectContextPriv.h"
#include "src/gpu/GrGeometryProcessor.h"
#include "src/gpu/GrGpuBuffer.h"
#include "src/gpu/GrMemoryPool.h"
#include "src/gpu/GrOpFlushState.h"
#include "src/gpu/GrOpsRenderPass.h"
#include "src/gpu/GrPipeline.h"
#include "src/gpu/GrProcessor.h"
#include "src/gpu/GrProcessorSet.h"
#include "src/gpu/GrProgramInfo.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrResourceProvider.h"
#include "src/gpu/GrShaderCaps.h"
#include "src/gpu/GrShaderVar.h"
#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
#include "src/gpu/glsl/GrGLSLProgramDataManager.h"
#include "src/gpu/glsl/GrGLSLUniformHandler.h"
#include "src/gpu/glsl/GrGLSLVarying.h"
#include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h"
#include "src/gpu/ops/GrDrawOp.h"
#include "src/gpu/ops/GrOp.h"
#include "src/gpu/v1/SurfaceDrawContext_v1.h"
#include "tools/gpu/ProxyUtils.h"

#include <memory>
#include <utility>

class GrAppliedClip;

/**
 * This test ensures that fwidth() works properly on GPU configs by drawing a squircle.
 */
namespace {

static constexpr GrGeometryProcessor::Attribute gVertex =
        {"bboxcoord", kFloat2_GrVertexAttribType, SkSLType::kFloat2};

////////////////////////////////////////////////////////////////////////////////////////////////////
// SkSL code.

class FwidthSquircleTestProcessor : public GrGeometryProcessor {
public:
    static GrGeometryProcessor* Make(SkArenaAlloc* arena, const SkMatrix& viewMatrix) {
        return arena->make([&](void* ptr) {
            return new (ptr) FwidthSquircleTestProcessor(viewMatrix);
        });
    }

    const char* name() const override { return "FwidthSquircleTestProcessor"; }

    void addToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const final {}

    std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;

private:
    FwidthSquircleTestProcessor(const SkMatrix& viewMatrix)
            : GrGeometryProcessor(kFwidthSquircleTestProcessor_ClassID)
            , fViewMatrix(viewMatrix) {
        this->setVertexAttributesWithImplicitOffsets(&gVertex, 1);
    }

    const SkMatrix fViewMatrix;

    using INHERITED = GrGeometryProcessor;
};

std::unique_ptr<GrGeometryProcessor::ProgramImpl> FwidthSquircleTestProcessor::makeProgramImpl(
        const GrShaderCaps&) const {
    class Impl : public ProgramImpl {
    public:
        void setData(const GrGLSLProgramDataManager& pdman,
                     const GrShaderCaps&,
                     const GrGeometryProcessor& geomProc) override {
            const auto& proc = geomProc.cast<FwidthSquircleTestProcessor>();
            pdman.setSkMatrix(fViewMatrixHandle, proc.fViewMatrix);
        }

    private:
        void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
            const auto& proc = args.fGeomProc.cast<FwidthSquircleTestProcessor>();

            auto* uniforms = args.fUniformHandler;
            fViewMatrixHandle = uniforms->addUniform(nullptr,
                                                     kVertex_GrShaderFlag,
                                                     SkSLType::kFloat3x3,
                                                     "viewmatrix");

            auto* varyings = args.fVaryingHandler;
            varyings->emitAttributes(proc);

            GrGLSLVarying squircleCoord(SkSLType::kFloat2);
            varyings->addVarying("bboxcoord", &squircleCoord);

            auto* v = args.fVertBuilder;
            v->codeAppendf("float2x2 R = float2x2(cos(.05), sin(.05), -sin(.05), cos(.05));");

            v->codeAppendf("%s = bboxcoord * 1.25;", squircleCoord.vsOut());
            v->codeAppendf("float3 vertexpos = float3(bboxcoord * 100 * R + 100, 1);");
            v->codeAppendf("vertexpos = %s * vertexpos;",
                           uniforms->getUniformCStr(fViewMatrixHandle));
            gpArgs->fPositionVar.set(SkSLType::kFloat3, "vertexpos");

            auto* f = args.fFragBuilder;
            f->codeAppendf("float golden_ratio = 1.61803398875;");
            f->codeAppendf("float pi = 3.141592653589793;");
            f->codeAppendf("float x = abs(%s.x), y = abs(%s.y);",
                           squircleCoord.fsIn(), squircleCoord.fsIn());

            // Squircle function!
            f->codeAppendf("float fn = half(pow(x, golden_ratio*pi) + "
                           "pow(y, golden_ratio*pi) - 1);");
            f->codeAppendf("float fnwidth = fwidth(fn);");
            f->codeAppendf("fnwidth += 1e-10;");  // Guard against divide-by-zero.
            f->codeAppendf("half coverage = clamp(half(.5 - fn/fnwidth), 0, 1);");

            f->codeAppendf("half4 %s = half4(.51, .42, .71, 1) * .89;", args.fOutputColor);
            f->codeAppendf("half4 %s = half4(coverage);", args.fOutputCoverage);
        }

        UniformHandle fViewMatrixHandle;
    };

    return std::make_unique<Impl>();
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Draw Op.

class FwidthSquircleTestOp : public GrDrawOp {
public:
    DEFINE_OP_CLASS_ID

    static GrOp::Owner Make(GrRecordingContext* ctx, const SkMatrix& viewMatrix) {
        return GrOp::Make<FwidthSquircleTestOp>(ctx, viewMatrix);
    }

private:
    FwidthSquircleTestOp(const SkMatrix& viewMatrix)
            : GrDrawOp(ClassID())
            , fViewMatrix(viewMatrix) {
        this->setBounds(SkRect::MakeIWH(kWidth, kHeight), HasAABloat::kNo, IsHairline::kNo);
    }

    const char* name() const override { return "FwidthSquircleTestOp"; }
    FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
    GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*, GrClampType) override {
        return GrProcessorSet::EmptySetAnalysis();
    }

    GrProgramInfo* createProgramInfo(const GrCaps* caps,
                                     SkArenaAlloc* arena,
                                     const GrSurfaceProxyView& writeView,
                                     bool usesMSAASurface,
                                     GrAppliedClip&& appliedClip,
                                     const GrDstProxyView& dstProxyView,
                                     GrXferBarrierFlags renderPassXferBarriers,
                                     GrLoadOp colorLoadOp) const {
        GrGeometryProcessor* geomProc = FwidthSquircleTestProcessor::Make(arena, fViewMatrix);

        return sk_gpu_test::CreateProgramInfo(caps, arena, writeView, usesMSAASurface,
                                              std::move(appliedClip), dstProxyView,
                                              geomProc, SkBlendMode::kSrcOver,
                                              GrPrimitiveType::kTriangleStrip,
                                              renderPassXferBarriers, colorLoadOp);
    }

    GrProgramInfo* createProgramInfo(GrOpFlushState* flushState) const {
        return this->createProgramInfo(&flushState->caps(),
                                       flushState->allocator(),
                                       flushState->writeView(),
                                       flushState->usesMSAASurface(),
                                       flushState->detachAppliedClip(),
                                       flushState->dstProxyView(),
                                       flushState->renderPassBarriers(),
                                       flushState->colorLoadOp());
    }

    void onPrePrepare(GrRecordingContext* context,
                      const GrSurfaceProxyView& writeView,
                      GrAppliedClip* clip,
                      const GrDstProxyView& dstProxyView,
                      GrXferBarrierFlags renderPassXferBarriers,
                      GrLoadOp colorLoadOp) final {
        SkArenaAlloc* arena = context->priv().recordTimeAllocator();

        // DMSAA is not supported on DDL.
        bool usesMSAASurface = writeView.asRenderTargetProxy()->numSamples() > 1;

        // This is equivalent to a GrOpFlushState::detachAppliedClip
        GrAppliedClip appliedClip = clip ? std::move(*clip) : GrAppliedClip::Disabled();

        fProgramInfo = this->createProgramInfo(context->priv().caps(), arena, writeView,
                                               usesMSAASurface, std::move(appliedClip),
                                               dstProxyView, renderPassXferBarriers, colorLoadOp);

        context->priv().recordProgramInfo(fProgramInfo);
    }

    void onPrepare(GrOpFlushState* flushState) final {
        SkPoint vertices[4] = {
            {-1, -1},
            {+1, -1},
            {-1, +1},
            {+1, +1},
        };
        fVertexBuffer = flushState->resourceProvider()->createBuffer(
                sizeof(vertices), GrGpuBufferType::kVertex, kStatic_GrAccessPattern, vertices);
    }

    void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) final {
        if (!fVertexBuffer) {
            return;
        }

        if (!fProgramInfo) {
            fProgramInfo = this->createProgramInfo(flushState);
        }

        flushState->bindPipeline(*fProgramInfo, SkRect::MakeIWH(kWidth, kHeight));
        flushState->bindBuffers(nullptr, nullptr, std::move(fVertexBuffer));
        flushState->draw(4, 0);

    }

    static const int kWidth = 200;
    static const int kHeight = 200;

    sk_sp<GrBuffer> fVertexBuffer;
    const SkMatrix  fViewMatrix;

    // The program info (and both the GrPipeline and GrGeometryProcessor it relies on), when
    // allocated, are allocated in either the ddl-record-time or flush-time arena. It is the
    // arena's job to free up their memory so we just have a bare programInfo pointer here. We
    // don't even store the GrPipeline and GrGeometryProcessor pointers here bc they are
    // guaranteed to have the same lifetime as the program info.
    GrProgramInfo*  fProgramInfo = nullptr;

    friend class ::GrOp; // for ctor

    using INHERITED = GrDrawOp;
};

} // namespace

////////////////////////////////////////////////////////////////////////////////////////////////////
// Test.

namespace skiagm {

DEF_SIMPLE_GPU_GM_CAN_FAIL(fwidth_squircle, rContext, canvas, errorMsg, 200, 200) {
    if (!rContext->priv().caps()->shaderCaps()->shaderDerivativeSupport()) {
        *errorMsg = "Shader derivatives not supported.";
        return DrawResult::kSkip;
    }

    auto sdc = SkCanvasPriv::TopDeviceSurfaceDrawContext(canvas);
    if (!sdc) {
        *errorMsg = GM::kErrorMsg_DrawSkippedGpuOnly;
        return DrawResult::kSkip;
    }

    // Draw the test directly to the frame buffer.
    canvas->clear(SK_ColorWHITE);
    sdc->addDrawOp(FwidthSquircleTestOp::Make(rContext, canvas->getTotalMatrix()));
    return skiagm::DrawResult::kOk;
}

}  // namespace skiagm


text: export * from './gh-app.module';


text:
#ifndef APACHE_HTRACE_TEST_TEST_CONFIG_H
#define APACHE_HTRACE_TEST_TEST_CONFIG_H

// The absolute path to the htrace binary, for use in unit tests.
#cmakedefine HTRACE_ABSPATH "@HTRACE_ABSPATH@"

// The absolute path to the htraced binary, for use in unit tests.
#cmakedefine HTRACED_ABSPATH "@HTRACED_ABSPATH@"

#endif


text: import 'antd/lib/breadcrumb/style/css';


text:
package it.unibz.krdb.obda.protege4.gui.component;

import it.unibz.krdb.obda.model.Predicate;
import it.unibz.krdb.obda.model.impl.OBDAVocabulary;
import it.unibz.krdb.obda.protege4.gui.IconLoader;

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

public class DataTypeComboBox extends JComboBox {

	private static final long serialVersionUID = 1L;

	private static final Predicate[] SUPPORTED_DATATYPES = getQuestDataTypePredicates();

	public DataTypeComboBox() {
		super(SUPPORTED_DATATYPES);
		setRenderer(new DataTypeRenderer());
		setPreferredSize(new Dimension(130, 23));
		setSelectedIndex(-1);
	}

	private static Predicate[] getQuestDataTypePredicates() {
		int length = OBDAVocabulary.QUEST_DATATYPE_PREDICATES.length + 1;
		Predicate[] dataTypes = new Predicate[length];
		dataTypes[0] = null;
		System.arraycopy(OBDAVocabulary.QUEST_DATATYPE_PREDICATES, 0, dataTypes, 1, OBDAVocabulary.QUEST_DATATYPE_PREDICATES.length);
		return dataTypes;
	}

	class DataTypeRenderer extends BasicComboBoxRenderer {

		private static final long serialVersionUID = 1L;

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
			super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

			if (value == null) {
				setText("<Undefined data type>");
				setIcon(null);
			} else {
				if (value instanceof Predicate) {
					Predicate item = (Predicate) value;
					String name = item.toString();
					if (name.contains(OBDAVocabulary.NS_XSD)) {
						name = name.replace(OBDAVocabulary.NS_XSD, "xsd:");
					} else if (name.contains(OBDAVocabulary.NS_RDFS)) {
						name = name.replace(OBDAVocabulary.NS_RDFS, "rdfs:");
					}
					setText(name);
					setIcon(IconLoader.getImageIcon("images/datarange.png"));
				}
			}
			return this;
		}
	}
}


text:
using namespace hect;

FrameBuffer::FrameBuffer()
{
}

FrameBuffer::FrameBuffer(unsigned width, unsigned height) :
    RenderTarget(width, height)
{
}

void FrameBuffer::bind(Renderer& renderer)
{
    renderer.set_target(*this);
}

void FrameBuffer::attach(FrameBufferSlot slot, Texture2& texture)
{
    ensure_slot_empty(slot);

    if (texture.width() != width() || texture.height() != height())
    {
        throw InvalidOperation("Cannot attach texture to a frame buffer of a different size");
    }
    else if (slot == FrameBufferSlot::Depth)
    {
        PixelFormat pixel_format = texture.pixel_format();
        if (pixel_format.cardinality() != 1)
        {
            throw InvalidOperation("Cannot attach multi-channel texture to the depth slot of a frame buffer");
        }
    }

    if (is_uploaded())
    {
        renderer().destroy_frame_buffer(*this);
    }

    _attachments.push_back(FrameBufferAttachment(slot, texture));
}

void FrameBuffer::attach(FrameBufferSlot slot, Texture3& texture)
{
    ensure_slot_empty(slot);

    if (texture.width() != width() || texture.height() != height())
    {
        throw InvalidOperation("Cannot attach texture to a frame buffer of a different size");
    }
    else if (slot == FrameBufferSlot::Depth)
    {
        throw InvalidOperation("Cannot attach 3-dimensional texture to the depth slot of a frame buffer");
    }

    if (is_uploaded())
    {
        renderer().destroy_frame_buffer(*this);
    }

    _attachments.push_back(FrameBufferAttachment(slot, texture));
}

void FrameBuffer::attach(FrameBufferSlot slot, CubeSide side, TextureCube& texture)
{
    ensure_slot_empty(slot);

    if (texture.width() != width() || texture.height() != height())
    {
        throw InvalidOperation("Cannot attach texture to a frame buffer of a different size");
    }
    else if (slot == FrameBufferSlot::Depth)
    {
        throw InvalidOperation("Cannot attach cubic texture to the depth slot of a frame buffer");
    }

    if (is_uploaded())
    {
        renderer().destroy_frame_buffer(*this);
    }

    _attachments.push_back(FrameBufferAttachment(slot, side, texture));
}

FrameBuffer::AttachmentSequence FrameBuffer::attachments()
{
    return _attachments;
}

void FrameBuffer::ensure_slot_empty(FrameBufferSlot slot)
{
    bool empty = true;

    // Check if any other attachments are attached to this slot
    for (const FrameBufferAttachment& attachment : _attachments)
    {
        if (attachment.slot() == slot)
        {
            empty = false;
        }
    }

    if (!empty)
    {
        throw InvalidOperation(format("Frame buffer slot '%s' is not empty", Enum::to_string(slot).data()));
    }
}


text:
"""Simple wrapper around passlib that allows for lazy initilization."""
from passlib.context import CryptContext

class Passlib(object):
    """Passlib wrapper class that allows for lazy initilization.

    The part about the lazy initilization is important for using Flask with
    application factorties.
    """

    def init_app(self, app):
        """Lazy initializer which takes an `app` and sets up the internal context."""
        self.pwd_context = CryptContext(
            schemes=app.config['PASSLIB_SCHEMES'],
        )


text:
package fr.ethilvan.launcher.util;

import java.io.File;

public enum OS {

    WINDOWS {

        @Override
        protected String[] identifiers() {
            return new String[] { "win" };
        }

        @Override
        public File getDataDir() {
            String appData = System.getenv("APPDATA");
            if (appData != null) {
                return new File(appData);
            } else {
                return Util.getHomeDirectory();
            }
        }
    },

    MAC_OS_X {
        @Override
        protected String[] identifiers() {
            return new String[] { "mac" };
        }
    },

    LINUX {
        @Override
        protected String[] identifiers() {
            return new String[] { "linux", "unix" };
        }
    },

    SOLARIS {
        @Override
        protected String[] identifiers() {
            return new String[] { "solaris", "sunos" };
        }
    },

    UNKNOWN;

    public static OS get() {
        String osName = System.getProperty("os.name").toLowerCase();
        for (OS os : values()) {
            for (String identifier : os.identifiers()) {
                if (osName.contains(identifier)) {
                    return os;
                }
            }
        }

        return UNKNOWN;
    }

    protected String[] identifiers() {
        return new String[0];
    }

    public File getDataDir() {
        return Util.getHomeDirectory();
    }
}


text:
layout: post
microblog: true
date: 2016-07-31 13:58 +0300
guid: http://desparoz.micro.blog/2016/07/31/t759704812694888450.html
---
Great talk & photo exhibition about the Voices from the Coast by @LensaNusantara_ at @CasaLunaUbud. Important msg [t.co/jIkJYa9Gq...](https://t.co/jIkJYa9Gqd)


text:
<?php
/**
 * Created by PhpStorm.
 * User: xqq
 * Date: 15-11-22
 * Time: 下午8:19
 */
class CollIntroduceAction extends Action{
    public function no1(){
        $this->display();
    }
    public function no2(){
        $this->display();
    }
    public function no3(){
        $this->display();
    }
    public function no4(){
        $this->display();
    }
    public function no5(){
        $this->display();
    }
    public function no6(){
        $this->display();
    }
    public function no7(){
        $this->display();
    }
    public function no8(){
        $this->display();
    }
    public function no9(){
        $this->display();
    }
    public function no10(){
        $this->display();
    }
    public function no11(){
        $this->display();
    }
    public function no12(){
        $this->display();
    }
    public function no13(){
        $this->display();
    }
    public function no14(){
        $this->display();
    }
    public function no15(){
        $this->display();
    }
    public function no16(){
        $this->display();
    }
    public function no17(){
        $this->display();
    }
    public function no18(){
        $this->display();
    }
    public function no19(){
        $this->display();
    }
    public function no20(){
        $this->display();
    }
    public function no21(){
        $this->display();
    }
}
?>


text:
import subprocess
import unittest
import time
import psutil
import os

import signal

class TestStringMethods(unittest.TestCase):
    def setup_processes(self, cmd="single-beat python echo.py", cnt=3):
        self.processes = [subprocess.Popen(cmd, shell=True) for i in range(0, cnt)]

    def get_all_children(self):
        children = []
        for p in self.processes:
            try:
                parent = psutil.Process(p.pid)
            except psutil.NoSuchProcess:
                continue
            children += parent.children(recursive=True)
        return children

    def get_active_subprocess(self):
        for p in self.processes:
            try:
                parent = psutil.Process(p.pid)
            except psutil.NoSuchProcess:
                continue
            if parent.children(recursive=True):
                return p

    def wait_and_try_again(self, fn, max_seconds=5):
        cnt = 0
        while cnt < max_seconds:
            result = fn()
            if result:
                return result
            time.sleep(1)
            cnt += 1
        raise Exception(f"Couldn't complete {fn} in a timely fashion")

    def test_single_instance(self):
        """
        only one instance of the child should be running
        """
        self.setup_processes()
        # check we only one echo.py running
        children = self.wait_and_try_again(self.get_all_children, 5)
        self.assertEqual(len(children), 1, "we have more than one child")
        # send kill to the child, see if someone else spawns
        os.kill(children[0].pid, signal.SIGTERM)
        new_children = self.wait_and_try_again(self.get_all_children, 30)
        self.assertGreater(len(children), 0, "couldn't spawn new child in 30 seconds")
        self.assertEqual(len(children), 1, "we have more than one child")
        self.assertNotEqual(
            children[0].pid,
            new_children[0].pid,
            "couldn't kill child - pid should've changed",
        )

    def test_exit_code(self):
        self.setup_processes("single-beat python echo-exit-code.py", cnt=1)
        # check we only one echo.py running
        children = self.wait_and_try_again(self.get_all_children, 5)
        self.assertEqual(len(children), 1, "we have more than one child")
        sp = self.get_active_subprocess()
        exit_code = self.wait_and_try_again(lambda: sp.poll(), 5)
        self.assertEqual(exit_code, 3)

    def tearDown(self):
        for p in self.processes:
            try:
                p.terminate()
                p.wait(10)
            except Exception as e:
                import traceback

                traceback.print_exc()

if __name__ == "__main__":
    unittest.main()


text:
<?php

 namespace Lazer\Classes\Helpers;

use Lazer\Classes\LazerException;

if( ! defined('BASEPATH')) exit('No direct script access allowed');

 class File implements FileInterface {

     /**
      * File name
      * @var string
      */
     protected $name;

     /**
      * File type (data|config)
      * @var string
      */
     protected $type;

     public static function table($name)
     {
         $file = new File;
         $file->name = $name;

         return $file;
     }

     public final function setType($type)
     {
         $this->type = $type;
     }

     public final function getPath()
     {
         if (!empty($this->type))
         {
             return $this->data_path(LAZER_DATA_PATH).$this->name.'.'.$this->type.'.json';
         }
         else
         {
             throw new LazerException('You must specify the type of file in class: '.__);
         }
     }

     public final function get($assoc = false)
     {
         return json_decode(file_get_contents($this->getPath()), $assoc);
     }

     public final function put($data)
     {
         return file_put_contents($this->getPath(), json_encode($data));
     }

     public final function exists()
     {
         return file_exists($this->getPath());
     }

     public final function remove()
     {
         $type = ucfirst($this->type);
         if ($this->exists())
         {
             if (unlink($this->getPath()))
                 return TRUE;

             throw new LazerException($type.': Deleting failed');
         }

         throw new LazerException($type.': File does not exists');
     }

     function data_path($path='')
     {
         $dataPath = ( $path != '' ) ? DOCPATH . 'files' . DIRECTORY_SEPARATOR . '.' . $path . DIRECTORY_SEPARATOR : DOCPATH . 'files' . DIRECTORY_SEPARATOR . '.data' . DIRECTORY_SEPARATOR;

         if( ! file_exists($dataPath) )
         {
             if ( mkdir($dataPath, 0777, TRUE) ) {
                 /**
                 // Create index.html template
                 if( fopen($dataPath . 'index.html', 'w') )
                 {
                 $indexHTML = fopen($dataPath . 'index.html', 'w');

                 $indexHTMLcontent = "<title>403 Forbidden</title>
Directory access is forbidden.
";
                 fwrite($indexHTML, $indexHTMLcontent);

                 fclose($indexHTML);
                 }
                 else {
                 log_message('ERROR', 'Could not open file.');
                 }
                  **/
                 // Create .htaccess for block direct access to *.json files
                 if( ! file_exists($dataPath . '.htaccess') ) {
                     $htaccessFile = fopen($dataPath . '.htaccess', 'w');

                     fwrite($htaccessFile, "<Files '*.json'>\r\n");
                     fwrite($htaccessFile, "Order Allow,Deny\r\n");
                     fwrite($htaccessFile, "Deny from all\r\n");
                     fwrite($htaccessFile, "</Files>\r\n");

                     fclose($htaccessFile);
                 }
                 else {
                     log_message('ERROR', 'Could not open file.');
                 }
             }
             else {
                 log_message('ERROR', 'Failed to create ' . $dataPath . ' folder');
             }
         }

         // log_message('ERROR', '#dataPath :: ' . $dataPath);

         return $dataPath;
     }
 }


text:
package main

import (
	"image/color"
	"log"

	"github.com/EngoEngine/ecs"
	"github.com/EngoEngine/engo"
	"github.com/EngoEngine/engo/common"
	"github.com/EngoEngine/engo/math"
)

type Guy struct {
	ecs.BasicEntity
	common.RenderComponent
	common.SpaceComponent
}

type DefaultScene struct{}

func (game *DefaultScene) Preload() {
	err := engo.Files.Load("icon.png")
	if err != nil {
		log.Println(err)
	}
}

func (game *DefaultScene) Setup(u engo.Updater) {
	w, _ := u.(*ecs.World)

	common.SetBackground(color.White)

	w.AddSystem(&RotationSystem{})
	w.AddSystem(&common.RenderSystem{})

	// Retrieve a texture
	texture, err := common.LoadedSprite("icon.png")
	if err != nil {
		log.Println(err)
	}

	// Create an entity
	guy := Guy{BasicEntity: ecs.NewBasic()}

	// Initialize the components, set scale to 8x
	guy.RenderComponent = common.RenderComponent{
		Drawable: texture,
		Scale:    engo.Point{8, 8},
	}
	guy.SpaceComponent = common.SpaceComponent{
		Position: engo.Point{200, 200},
		Width:    texture.Width() * guy.RenderComponent.Scale.X,
		Height:   texture.Height() * guy.RenderComponent.Scale.Y,
	}

	// Add it to appropriate systems
	for _, system := range w.Systems() {
		switch sys := system.(type) {
		case *common.RenderSystem:
			sys.Add(&guy.BasicEntity, &guy.RenderComponent, &guy.SpaceComponent)
		case *RotationSystem:
			sys.Add(&guy.BasicEntity, &guy.SpaceComponent)
		}
	}
}

type rotationEntity struct {
	*ecs.BasicEntity
	*common.SpaceComponent
}

type RotationSystem struct {
	entities []rotationEntity
}

func (r *RotationSystem) Add(basic *ecs.BasicEntity, space *common.SpaceComponent) {
	r.entities = append(r.entities, rotationEntity{basic, space})
}

func (r *RotationSystem) Remove(basic ecs.BasicEntity) {
	delete := -1
	for index, e := range r.entities {
		if e.BasicEntity.ID() == basic.ID() {
			delete = index
			break
		}
	}
	if delete >= 0 {
		r.entities = append(r.entities[:delete], r.entities[delete+1:]...)
	}
}

func (r *RotationSystem) Update(dt float32) {
	// speed in radians per second
	var speed float32 = math.Pi
	// speed in degrees per second
	var speedDegrees float32 = speed * 180 / math.Pi

	for _, e := range r.entities {
		e.SpaceComponent.Rotation += speedDegrees * dt
		e.SpaceComponent.Rotation = math.Mod(e.SpaceComponent.Rotation, 360)
	}
}

func (*DefaultScene) Type() string { return "GameWorld" }

func main() {
	opts := engo.RunOptions{
		Title:  "Rotation Demo",
		Width:  1024,
		Height: 640,
	}
	engo.Run(opts, &DefaultScene{})
}


text:
namespace blink {

struct NGBfcOffset;

// Adjusts {@code offset} to the clearance line.
CORE_EXPORT bool AdjustToClearance(LayoutUnit clearance_offset,
                                   NGBfcOffset* offset);

// Calculate and set the available inline fallback size for orthogonal flow
// children. This size will be used if it's not resolvable via other means [1].
//
// TODO(mstensho): The spec [1] says to use the size of the nearest scrollport
// as constraint, if that's smaller than the initial containing block, but we
// haven't implemented that yet; we always just use the initial containing
// block size.
//
// [1] https://www.w3.org/TR/css-writing-modes-3/#orthogonal-auto
void SetOrthogonalFallbackInlineSize(const ComputedStyle& parent_style,
                                     const NGLayoutInputNode child,
                                     NGConstraintSpaceBuilder* builder);

inline void SetOrthogonalFallbackInlineSizeIfNeeded(
    const ComputedStyle& parent_style,
    const NGLayoutInputNode child,
    NGConstraintSpaceBuilder* builder) {
  if (LIKELY(IsParallelWritingMode(parent_style.GetWritingMode(),
                                   child.Style().GetWritingMode())))
    return;
  SetOrthogonalFallbackInlineSize(parent_style, child, builder);
}

// Only to be called if the child is in a writing-mode parallel with its
// container. Return true if an auto inline-size means that the child should be
// stretched (rather than being shrink-to-fit).
bool ShouldBlockContainerChildStretchAutoInlineSize(const NGLayoutInputNode&);

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_SPACE_UTILS_H_


text:
namespace app_list {
class AppListViewDelegate;

class APP_LIST_PRESENTER_EXPORT AppListViewDelegateFactory {
 public:
  virtual ~AppListViewDelegateFactory();

  // This does not pass ownership of the delegate.
  virtual app_list::AppListViewDelegate* GetDelegate() = 0;
};

}  // namespace app_list

#endif  // UI_APP_LIST_PRESENTER_APP_LIST_VIEW_DELEGATE_FACTORY_H_


text:
<editor>
    <help>/commander/pages/@PLUGIN_NAME@/@PLUGIN_KEY@_help?s=Administration&ss=Plugins#CreateRole</help>
    <formElement>
        <type>entry</type>
        Knife Path:
        <value>/usr/bin/knife</value>
        <property>knife_path</property>
        <required>1</required>
        <documentation>Provide the path to the knife executable e.g /usr/bin/knife (This is the default value). (Required) </documentation>
    </formElement>
    <formElement>
        <type>entry</type>
        Role Name:
        <value></value>
        <property>role_name</property>
        <required>1</required>
        <documentation>Provide the name of the role to create. (Required)</documentation>
    </formElement>
    <formElement>
        <type>entry</type>
        Attribute:
        <value></value>
        <property>attribute</property>
        <required>0</required>
        <documentation>The attribute (or attributes) to show.</documentation>
    </formElement>
    <formElement>
        <type>entry</type>
        Result Property:
        <value>/myJob/result</value>
        <property>result_property</property>
        <required>1</required>
        <documentation>The property details in which result will be stored. Enter a valid property path[myJobStep, myJob, myProcedure,          myProject]. </documentation>
    </formElement>
    <formElement>
        <type>entry</type>
        Additional options:
        <value></value>
        <property>additional_options</property>
        <required>0</required>
        <documentation>Additional options if any.</documentation>
    </formElement>
</editor>


text:
<?php

namespace Mautic\SmsBundle\Form\Type;

use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Class SmsSendType
 *
 * @package Mautic\FormBundle\Form\Type
 */
class SmsSendType extends AbstractType
{
    /**
     * @var RouterInterface
     */
    protected $router;

    /**
     * @param RouterInterface $router
     */
    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('sms', 'sms_list', array(
            'label'       => 'mautic.sms.send.selectsmss',
            'label_attr'  => array('class' => 'control-label'),
            'attr'        => array(
                'class'   => 'form-control',
                'tooltip' => 'mautic.sms.choose.smss',
                'onchange'=> 'Mautic.disabledSmsAction()'
            ),
            'multiple'    => false,
            'constraints' => array(
                new NotBlank(
                    array('message' => 'mautic.sms.choosesms.notblank')
                )
            )
        ));

        if (! empty($options['update_select'])) {
            $windowUrl = $this->router->generate('mautic_sms_action', array(
                'objectAction' => 'new',
                'contentOnly'  => 1,
                'updateSelect' => $options['update_select']
            ));

            $builder->add('newSmsButton', 'button', array(
                'attr'  => array(
                    'class'   => 'btn btn-primary btn-nospin',
                    'onclick' => 'Mautic.loadNewSmsWindow({
                        "windowUrl": "' . $windowUrl . '"
                    })',
                    'icon'    => 'fa fa-plus'
                ),
                'label' => 'mautic.sms.send.new.sms'
            ));

            $sms = $options['data']['sms'];

            // create button edit sms
            $windowUrlEdit = $this->router->generate('mautic_sms_action', array(
                'objectAction' => 'edit',
                'objectId'     => 'smsId',
                'contentOnly'  => 1,
                'updateSelect' => $options['update_select']
            ));

            $builder->add('editSmsButton', 'button', array(
                'attr'  => array(
                    'class'     => 'btn btn-primary btn-nospin',
                    'onclick'   => 'Mautic.loadNewSmsWindow(Mautic.standardSmsUrl({"windowUrl": "' . $windowUrlEdit . '"}))',
                    'disabled'  => !isset($sms),
                    'icon'      => 'fa fa-edit'
                ),
                'label' => 'mautic.sms.send.edit.sms'
            ));
        }
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setOptional(array('update_select'));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return "smssend_list";
    }
}


text:
package net.dev123.mblog.sina;

import static net.dev123.commons.util.ParseUtil.getBoolean;
import static net.dev123.commons.util.ParseUtil.getRawString;
import static net.dev123.commons.util.ParseUtil.getUnescapedString;
import net.dev123.exception.ExceptionCode;
import net.dev123.exception.LibException;
import net.dev123.mblog.entity.Relationship;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * SinaRelationshipAdaptor
 *
 * @version
 * @author 马庆升
 * @time 2010-8-31 上午01:36:37
 */
public class SinaRelationshipAdaptor {

	/**
	 * 从JSON字符串创建Relationship对象
	 *
	 * @param responseString
	 *            JSON字符串
	 * @return Relationship对象
	 * @throws LibException
	 */
	public static Relationship createRelationship(String responseString) throws LibException {
		try {
			JSONObject json = new JSONObject(responseString);
			return createRelationship(json);
		} catch (JSONException e) {
			throw new LibException(ExceptionCode.JSON_PARSE_ERROR);
		}
	}

	/**
	 * 从JSON对象创建Relationship对象,包级别访问控制
	 *
	 * @param json
	 *            JSON对象
	 * @return Relationship对象
	 * @throws LibException
	 */
	static Relationship createRelationship(JSONObject json) throws LibException {
		try {
			Relationship relationship = new Relationship();
			JSONObject sourceJson = json.getJSONObject("source");
			JSONObject targetJson = json.getJSONObject("target");
			relationship.setSourceUserId(getRawString("id", sourceJson));
			relationship.setTargetUserId(getRawString("id", targetJson));
			relationship.setSourceScreenName(getUnescapedString("screen_name", sourceJson));
			relationship.setTargetScreenName(getUnescapedString("screen_name", targetJson));
			relationship.setFollowing(getBoolean("following", sourceJson));
			relationship.setFollowed(getBoolean("followed_by", sourceJson));
			relationship.setSourceNotificationsEnabled(getBoolean("notifications_enabled", sourceJson));
			return relationship;
		} catch (JSONException e) {
			throw new LibException(ExceptionCode.JSON_PARSE_ERROR);
		}
	}

}


text:
import Transform from '@ember-data/serializer/transform';

export default Transform.extend({
  deserialize(serialized) {
    return serialized;
  },

  serialize(deserialized) {
    return deserialized;
  }
});


text:
package com.hankcs.lucene;

import com.hankcs.hanlp.corpus.tag.Nature;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.seg.common.wrapper.SegmentWrapper;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.util.AttributeFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.text.BreakIterator;
import java.util.Locale;
import java.util.Set;

/**
 * Tokenizer,抄袭ansj的
 */
public class HanLPTokenizer extends Tokenizer {

    /**
     * used for breaking the text into sentences
     */
    private static final BreakIterator sentenceProto = BreakIterator.getSentenceInstance(Locale.ROOT);

    // 当前词
    private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
    // 偏移量
    private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
    // 距离
    private final PositionIncrementAttribute positionAttr = addAttribute(PositionIncrementAttribute.class);
    // 词性
    private TypeAttribute typeAtt = addAttribute(TypeAttribute.class);

    protected SegmentWrapper segment;
    private Set<String> filter;
    private boolean enablePorterStemming;
    private final PorterStemmer stemmer = new PorterStemmer();

    /**
     * Creates a new HanLPTokenizer
     */
    public HanLPTokenizer(Segment segment, Set<String> filter, boolean enablePorterStemming, Reader reader) {
        super(DEFAULT_TOKEN_ATTRIBUTE_FACTORY, reader);

        this.segment = new SegmentWrapper(new BufferedReader(input), segment);
        this.filter = filter;
        this.enablePorterStemming = enablePorterStemming;
    }

    /**
     * Creates a new HanLPTokenizer, supplying the AttributeFactory
     *
     * @param segment              HanLP中的某个分词器
     * @param filter               停用词
     * @param enablePorterStemming 英文原型转换
     */
    public HanLPTokenizer(Segment segment, Set<String> filter, boolean enablePorterStemming, AttributeFactory factory, Reader reader) {
        super(factory, reader);

        this.segment = new SegmentWrapper(new BufferedReader(input), segment);
        this.filter = filter;
        this.enablePorterStemming = enablePorterStemming;
    }

    @Override
    final public boolean incrementToken() throws IOException {
        clearAttributes();
        int position = 0;
        Term term;
        boolean un_increased = true;
        do {
            term = segment.next();
            if (term == null) {
                break;
            }
            if (enablePorterStemming && term.nature == Nature.nx) {
                term.word = stemmer.stem(term.word);
            }

            if (filter != null && filter.contains(term.word)) {
                continue;
            } else {
                ++position;
                un_increased = false;
            }
        }
        while (un_increased);

        if (term != null) {
            positionAttr.setPositionIncrement(position);
            termAtt.setEmpty().append(term.word);
            offsetAtt.setOffset(term.offset, term.offset + term.word.length());
            typeAtt.setType(term.nature == null ? "null" : term.nature.toString());
            return true;
        } else {
            return false;
        }
    }

    /**
     * 必须重载的方法,否则在批量索引文件时将会导致文件索引失败
     */
    @Override
    public void reset() throws IOException {
        super.reset();
        segment.reset(new BufferedReader(this.input));
    }

}


text:
module SimpleCaptchaReloaded
  class Data < ActiveRecord::Base

    def self.generate_captcha_id(old_key: nil)
      SimpleCaptchaReloaded::Data.clear unless Rails.env.test?
      if old_key
        SimpleCaptchaReloaded::Data.where(key: old_key).delete_all
      end
      key, value = SimpleCaptchaReloaded::Config.generate_challenge
      SimpleCaptchaReloaded::Data.create!(key: key, value: value)
      key
    end

    def self.valid_captcha?(key,value)
      element = find_by_key(key)
      value && element && element.valid_captcha?(value)
    end

    def valid_captcha?(other)
      other.present? and value == other.strip.downcase
    end

    def self.clear
      SimpleCaptchaReloaded::Data.where('created_at < ?', 1.hour.ago).delete_all
    end

  end
end