text:
using UnityEngine;
using System.Collections;

public class Monster : MonoBehaviour {

	public MonsterGUIManager monsterGUIManager;

	public GameObject monsterGameObject;
	private float idleSwitchDelay;

	public string name = "Monster";

	public Texture2D avatar;

	public int level = 5;

	public int health = 100;
	public int mana = 100;
	public int attack = 20;
	public int defense = 10;
	public int specialAttack = 15;
	public int specialDefense = 10;
	public int speed = 10;
	[Range(0,100)] public int criticalChance = 5;

	private int currentHealth;
	private int currentMana;
	private int currentAttack;
	private int currentDefense;
	private int currentSpecialAttack;
	private int currentSpecialDefense;
	private int currentSpeed;
	private int currentCriticalChance;

    private MonsterAnimator monsterAnimator;

	private AudioClip currentAudioClip;
	public AudioClip attackSFX;

	public Global.State state;

	public Skill[] skills;

	public Global.AttackType attackType;
	public GameObject projectile;
	private Monster currentTarget;
	private bool isMovingToTarget = false;

	private bool isAttacking = false;
	private float attackDelay;

	private Skill currentSkill;
	private bool isUsingSkill = false;
	private float specialAttackDelay;

	private Item currentItem;
	private bool isUsingItem = false;
	private float itemDelay;
	private float itemEffectObjectDelay;

	private CharacterController controller;

	private Vector3 initialPosition;
	private Quaternion initialRotation;
	public float moveToInitialPositionSpeed = 15.0F;
	private bool isMovingToInitialPosition = false;
	private float movingToInitialPositionDelay;

	public BattleManager battleManager;
	public BattleGUIManager battleGUIManager;

	void Start () {
        controller = transform.GetComponent<CharacterController>();
        monsterAnimator = GetComponent<MonsterAnimator>();

        currentHealth = calculateAttribute(health);
		currentMana = calculateAttribute(mana);
		currentAttack = calculateAttribute(attack);
   		currentDefense = calculateAttribute(defense);
    	currentSpecialAttack = calculateAttribute(specialAttack);
		currentSpecialDefense = calculateAttribute(specialDefense);
		currentSpeed = calculateAttribute(speed);
		currentCriticalChance = criticalChance;

		initialPosition = transform.position;
		initialRotation = transform.rotation;
	}

	void Update () {
		if(state == Global.State.Dead) return;

		if(isMovingToTarget) {
			if(Vector3.Distance(currentTarget.transform.position, transform.position) < 3 * transform.localScale.x) {
				isMovingToTarget = false;

				if(isAttacking) {
					attackDelay = monsterAnimator.Length("PhysicalAttack") - 0.6F + Time.time;

                    if(attackSFX != null) {
						currentAudioClip = attackSFX;
						Invoke("PlayAudioClip", monsterAnimator.Length("PhysicalAttack") - 0.6F);
					}

                    monsterAnimator.PlayQueued("PhysicalAttack", new string[] { "MoveBackward", "Idle" });
				} else {
					specialAttackDelay = monsterAnimator.Length("SpecialAttack") - 0.6F + Time.time;

                    monsterAnimator.PlayQueued("SpecialAttack", new string[] { "MoveBackward", "Idle" });
                }
			} else {
				MoveTo(currentTarget.transform.position);
			}
		}

		if(isAttacking && attackDelay < Time.time && !isMovingToTarget) {
			currentTarget.ReceiveDamage(currentAttack, 30);

			isAttacking = false;

			movingToInitialPositionDelay = Time.time + 1;
			isMovingToInitialPosition = true;
		}

		if(isUsingSkill && specialAttackDelay < Time.time && !isMovingToTarget) {
			if(currentSkill.effectObject != null) {
				InstantiateParticlesOver(currentSkill.numberOfTargets, currentSkill.effectObject, currentSkill.effectObjectPosition);
			}

			if(currentSkill.numberOfTargets == Global.NumberOfTargets.OneAlly || currentSkill.numberOfTargets == Global.NumberOfTargets.OneEnemy || currentSkill.numberOfTargets == Global.NumberOfTargets.Himself) {
				ApplySkillEffect(currentSkill, currentTarget);
			} else if(currentSkill.numberOfTargets == Global.NumberOfTargets.AllAlly) {
				foreach(Monster ally in battleManager.teamA) {
					ApplySkillEffect(currentSkill, ally);
				}
			} else if(currentSkill.numberOfTargets == Global.NumberOfTargets.AllEnemy) {
				foreach(Monster enemy in battleManager.teamB) {
					ApplySkillEffect(currentSkill, enemy);
				}
			} else if(currentSkill.numberOfTargets == Global.NumberOfTargets.All) {
				foreach(Monster ally in battleManager.teamA) {
					ApplySkillEffect(currentSkill, ally);
				}

				foreach(Monster enemy in battleManager.teamB) {
					ApplySkillEffect(currentSkill, enemy);
				}
			}

			currentMana -= currentSkill.manaCost;

			isUsingSkill = false;

			movingToInitialPositionDelay = Time.time + 1;
			isMovingToInitialPosition = true;
		}

        // Instantiate item effect particles
		if(isUsingItem && itemDelay < Time.time && itemEffectObjectDelay == 0) {
			if(currentItem.numberOfTargets == Global.NumberOfTargets.OneAlly || currentItem.numberOfTargets == Global.NumberOfTargets.Himself) {
				GameObject itemEffectObjectClone = Instantiate(currentItem.effectObject, currentTarget.GetPosition(currentItem.effectObjectPosition), currentTarget.transform.rotation) as GameObject;
			} else if(currentItem.numberOfTargets == Global.NumberOfTargets.AllAlly) {
				foreach(Monster ally in battleManager.teamA) {
					if(ally.state == Global.State.Dead) {
						if(currentItem.overDead) {
							GameObject itemEffectObjectClone = Instantiate(currentItem.effectObject, ally.GetPosition(currentItem.effectObjectPosition), ally.transform.rotation) as GameObject;
						}
					} else {
						GameObject itemEffectObjectClone = Instantiate(currentItem.effectObject, ally.GetPosition(currentItem.effectObjectPosition), ally.transform.rotation) as GameObject;
					}
				}
			}

			itemEffectObjectDelay = currentItem.effectObjectDuration-1f + Time.time;
		}

        // Apply item effects
		if(isUsingItem && itemDelay < Time.time && itemEffectObjectDelay < Time.time) {
			if(currentItem.numberOfTargets == Global.NumberOfTargets.OneAlly || currentItem.numberOfTargets == Global.NumberOfTargets.Himself) {
				currentTarget.ApplyItemEffect(currentItem);
			} else if(currentItem.numberOfTargets == Global.NumberOfTargets.AllAlly) {
				foreach(Monster ally in battleManager.teamA) {
					if(ally.state == Global.State.Dead) {
						if(currentItem.overDead) {
							ally.ApplyItemEffect(currentItem);
						}
					} else {
						ally.ApplyItemEffect(currentItem);
					}
				}
			}

			isUsingItem = false;
            // TODO: Remove item from player inventory, currently only marks the item as used
        }

        if(isMovingToInitialPosition && movingToInitialPositionDelay < Time.time) {
			if(Vector3.Distance(initialPosition, transform.position) < 0.5) {
				isMovingToInitialPosition = false;
			} else {
				MoveToInitialPosition();
			}
		}
	}

    // Attack action method
	public void Attack(Monster target) {
		// Rotate to target
		transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.transform.position - transform.position), 4 * Time.deltaTime);
		transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);

		if(attackType == Global.AttackType.Melee) {
			isMovingToTarget = true;
        } else {
			isMovingToTarget = false;

			if(projectile != null) {
				GameObject projectileClone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
				Projectile projectileCloneScript = (Projectile)projectileClone.GetComponent("Projectile");
				projectileCloneScript.target = target.transform;

				attackDelay = Vector3.Distance(target.transform.position, transform.position)/projectileCloneScript.speed + Time.time;
			} else {
				attackDelay = monsterAnimator.Length("SpecialAttack") -0.6F + Time.time;
			}

            monsterAnimator.PlayQueued("SpecialAttack");
		}

		isAttacking = true;
		currentTarget = target;
	}

	public void UseSkill(int skillNumber, Monster target) {
		currentSkill = skills[skillNumber];

		// Rotate to target
		transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.transform.position - transform.position), 4 * Time.deltaTime);
		transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);

		if(currentSkill.attackType == Global.AttackType.Melee) {
			isMovingToTarget = true;
        } else {
			isMovingToTarget = false;

			if(currentSkill.projectile != null) {
				GameObject projectileClone = Instantiate(currentSkill.projectile, transform.position, transform.rotation) as GameObject;
				Projectile projectileCloneScript = (Projectile)projectileClone.GetComponent("Projectile");
				projectileCloneScript.target = target.transform;

				specialAttackDelay = Vector3.Distance(target.transform.position, transform.position)/projectileCloneScript.speed + Time.time;
			} else {
				specialAttackDelay = monsterAnimator.Length("SpecialAttack") - 0.6F + Time.time;
			}

            monsterAnimator.PlayQueued("SpecialAttack");
        }

		isUsingSkill = true;
		currentTarget = target;
	}

	public void UseItem(string team, int itemNumber, Monster target = null) {
		Player player = battleManager.teamAPlayer;
		currentItem = player.items[itemNumber];

        monsterAnimator.PlayQueued("SpecialAttack");

		isUsingItem = true;
		itemDelay = monsterAnimator.Length("SpecialAttack") - 0.6F + Time.time;
		itemEffectObjectDelay = 0;

		if(target != null)
			currentTarget = target;
	}

	public void ReceiveDamage(int attackValue, int bonification) {
		int damage = calculateDamage(attackValue, bonification, currentDefense);

        ApplyDamage(damage);
    }

	public void ReceiveSpecialDamage(int attackValue, int bonification) {
		int damage = calculateDamage(attackValue, bonification, currentSpecialDefense);

        ApplyDamage(damage);
    }

    private void ApplyDamage(int damage) {
        if(currentHealth - damage > 0) {
            currentHealth -= damage;

            monsterAnimator.PlayQueued("TakeDamage");
        } else {
            currentHealth = 0;
            state = Global.State.Dead;

            monsterAnimator.PlayDead();
        }

        battleGUIManager.DisplayDamage(damage, GetTopPosition(), Color.white);
    }

	public void IncreaseAttribute(int value, Global.Attribute attribute) {
		switch(attribute) {
			case Global.Attribute.Health:
					if((currentHealth+value < GetMaximumHealth()))
						currentHealth+=value;
					else
						currentHealth = GetMaximumHealth();
					if(state == Global.State.Dead)
						state = Global.State.None;
				break;
			case Global.Attribute.Mana:
				if((currentMana+value < GetMaximumMana()))
						currentMana+=value;
					else
						currentMana = GetMaximumMana();
				break;
			case Global.Attribute.Attack: currentAttack+=value;
				break;
			case Global.Attribute.Defense: currentDefense+=value;
				break;
			case Global.Attribute.SpecialAttack: currentSpecialAttack+=value;
				break;
			case Global.Attribute.SpecialDefense: currentSpecialDefense+=value;
				break;
			case Global.Attribute.Speed: currentSpeed+=value;
				break;
			case Global.Attribute.CriticalChance: currentCriticalChance+=value;
				break;
		}

		battleGUIManager.DisplayDamage(value, GetTopPosition(), Color.green);
	}

	public void DecreaseAttribute(int value, Global.Attribute attribute) {
		switch(attribute) {
		case Global.Attribute.Health: currentHealth-=value;
			break;
		case Global.Attribute.Mana: currentMana-=value;
			break;
		case Global.Attribute.Attack: currentAttack-=value;
			break;
		case Global.Attribute.Defense: currentDefense-=value;
			break;
		case Global.Attribute.SpecialAttack: currentSpecialAttack-=value;
			break;
		case Global.Attribute.SpecialDefense: currentSpecialDefense-=value;
			break;
		case Global.Attribute.Speed: currentSpeed-=value;
			break;
		case Global.Attribute.CriticalChance: currentCriticalChance-=value;
			break;
		}
	}

	public void ApplySkillEffect(Skill skill, Monster target) {
		if(skill.effect == Global.Effect.Damage) {
			if(skill.bonificationAttribute == Global.Attribute.Attack)
				target.ReceiveDamage(currentAttack, skill.bonification);
			else if(skill.bonificationAttribute == Global.Attribute.SpecialAttack)
				target.ReceiveSpecialDamage(currentSpecialAttack, skill.bonification);
		} else if(skill.effect == Global.Effect.Increase) {
			if(skill.bonificationAttribute == Global.Attribute.Attack)
				target.IncreaseAttribute((int)((currentAttack+skill.bonification)*0.4), skill.targetAttribute);
			else if(skill.bonificationAttribute == Global.Attribute.SpecialAttack)
				target.IncreaseAttribute((int)((currentSpecialAttack+skill.bonification)*0.4), skill.targetAttribute);
		}
	}

	public void ApplyItemEffect(Item item) {
		if(item.effect == Global.Effect.Increase)
			this.IncreaseAttribute(item.value, item.targetAttribute);
		if(item.effect == Global.Effect.Decrease)
			this.DecreaseAttribute(item.value, item.targetAttribute);
	}

	public int calculateAttribute(int baseAttributeValue) {
		return (int) Mathf.Ceil(
			(((baseAttributeValue*2)*level)/100) + (level/1) + 10
		);
	}

	public int calculateDamage(int attackValue, int bonificationValue, int defenseValue) {
		float variation = Random.Range(85.0F, 100.0F);

		return (int) Mathf.Ceil(
			((((0.2F*level+1) * attackValue * bonificationValue)/ (25 * defenseValue)) + 2) * variation * 0.01F
		);
	}

	public int GetLevel() {
		return level;
	}

	public int GetCurrentHealth() {
		return currentHealth;
	}

	public int GetMaximumHealth() {
		return calculateAttribute(health);
	}

	public int GetCurrentMana() {
		return currentMana;
	}

	public int GetMaximumMana() {
		return calculateAttribute(mana);
	}

	public int GetAttack() {
		return currentAttack;
	}

	public int GetDefense() {
		return currentDefense;
	}

	public int GetSpecialAttack() {
		return currentSpecialAttack;
	}

	public int GetSpecialDefense() {
		return currentSpecialDefense;
	}

	public int GetSpeed() {
		return currentSpeed;
	}

	public bool IsAttacking() {
		return isAttacking;
	}

	public bool IsUsingSkill() {
		return isUsingSkill;
	}

	public bool IsUsingItem() {
		return isUsingItem;
	}

    public bool IsMovingToTarget() {
        return isMovingToTarget;
    }

    public bool IsMovingToInitialPosition() {
		return isMovingToInitialPosition;
	}

	public void MoveTo(Vector3 targetPosition) {
		if(transform.position != targetPosition) {
			Vector3 dir = targetPosition - transform.position;
			float dist = dir.magnitude;
			float move = 5 * transform.localScale.x * Time.deltaTime;

			if(dist > move) {
				controller.Move(dir.normalized * move);
			}
			else {
				controller.Move(dir);
			}

			// Rotate to target
			dir.y = 0;
			transform.forward = Vector3.Slerp(transform.forward, dir, Time.deltaTime * 2 * transform.localScale.x);
		}
	}

	public void MoveToInitialPosition() {
		Vector3 dir = initialPosition - transform.position;
		float dist = dir.magnitude;
		float move = moveToInitialPositionSpeed * transform.localScale.x * Time.deltaTime;

		if(dist > move) {
			controller.Move(dir.normalized * move);
		}
		else {
			controller.Move(dir);
		}

		transform.rotation = Quaternion.Slerp(transform.rotation, initialRotation, Time.time * 0.008F * transform.localScale.x);
	}

	public Vector3 GetTopPosition() {
		Vector3 monsterTopPosition = transform.position;
		Renderer monsterRenderer = GetComponentInChildren<Renderer>();
		monsterTopPosition.y += monsterRenderer.bounds.size.y;

		return monsterTopPosition;
	}

	public Vector3 GetCenterPosition() {
		Vector3 monsterTopPosition = transform.position;
		Renderer monsterRenderer = GetComponentInChildren<Renderer>();
		monsterTopPosition.y += monsterRenderer.bounds.size.y/2;

		return monsterTopPosition;
	}

	public Vector3 GetBottomPosition() {
		return transform.position;
	}

	public Vector3 GetPosition(Global.Position position) {
		if(position == Global.Position.Top) {
			return GetTopPosition();
		} else if(position == Global.Position.Center) {
			return GetCenterPosition();
		} else if(position == Global.Position.Bottom) {
			return GetBottomPosition();
		}

		return transform.position;
	}

	public void InstantiateParticlesOver(Global.NumberOfTargets numberOfTargets, GameObject particleObject, Global.Position position) {
		if(numberOfTargets == Global.NumberOfTargets.OneAlly || numberOfTargets == Global.NumberOfTargets.OneEnemy || numberOfTargets == Global.NumberOfTargets.Himself) {
			GameObject particleObjectClone = Instantiate(particleObject, currentTarget.GetPosition(position), currentTarget.transform.rotation) as GameObject;
		} else if(numberOfTargets == Global.NumberOfTargets.AllAlly) {
			foreach(Monster ally in battleManager.teamA) {
				GameObject particleObjectClone = Instantiate(particleObject, ally.GetPosition(position), ally.transform.rotation) as GameObject;
			}
		} else if(numberOfTargets == Global.NumberOfTargets.AllEnemy) {
			foreach(Monster enemy in battleManager.teamB) {
				GameObject particleObjectClone = Instantiate(particleObject, enemy.GetPosition(position), enemy.transform.rotation) as GameObject;
			}
		} else if(numberOfTargets == Global.NumberOfTargets.All) {
			foreach(Monster ally in battleManager.teamA) {
				GameObject particleObjectClone = Instantiate(particleObject, ally.GetPosition(position), ally.transform.rotation) as GameObject;
			}

			foreach(Monster enemy in battleManager.teamB) {
				GameObject particleObjectClone = Instantiate(particleObject, enemy.GetPosition(position), enemy.transform.rotation) as GameObject;
			}
		}
	}

	public void PlayAudioClip() {
		GetComponent<AudioSource>().PlayOneShot(currentAudioClip, 1f);
	}
}


text:
(function(d3, fc) {
    'use strict';

    fc.tool.measure = function() {

        var event = d3.dispatch('measuresource', 'measuretarget', 'measureclear'),
            xScale = d3.time.scale(),
            yScale = d3.scale.linear(),
            snap = function(x, y) {
                return fc.util.noSnap(xScale, yScale)(x, y);
            },
            decorate = fc.util.fn.noop,
            xLabel = d3.functor(''),
            yLabel = d3.functor(''),
            padding = d3.functor(2);

        var x = function(d) { return d.xInDomainUnits ? xScale(d.x) : d.x; },
            y = function(d) { return d.yInDomainUnits ? yScale(d.y) : d.y; };

        var dataJoin = fc.util.dataJoin()
            .selector('g.measure')
            .element('g')
            .attrs({'class': 'measure'});

        var measure = function(selection) {

            selection.each(function(data, index) {

                var container = d3.select(this)
                    .style('pointer-events', 'all')
                    .on('mouseenter.measure', mouseenter);

                var overlay = container.selectAll('rect')
                    .data([data]);

                overlay.enter()
                    .append('rect')
                    .style('visibility', 'hidden');

                container.select('rect')
                    .attr('x', xScale.range()[0])
                    .attr('y', yScale.range()[1])
                    .attr('width', xScale.range()[1])
                    .attr('height', yScale.range()[0]);

                var g = dataJoin(container, data);

                var enter = g.enter();
                enter.append('line')
                    .attr('class', 'tangent');
                enter.append('line')
                    .attr('class', 'horizontal');
                enter.append('line')
                    .attr('class', 'vertical');
                enter.append('text')
                    .attr('class', 'horizontal');
                enter.append('text')
                    .attr('class', 'vertical');

                g.select('line.tangent')
                    .attr('x1', function(d) { return x(d.source); })
                    .attr('y1', function(d) { return y(d.source); })
                    .attr('x2', function(d) { return x(d.target); })
                    .attr('y2', function(d) { return y(d.target); });

                g.select('line.horizontal')
                    .attr('x1', function(d) { return x(d.source); })
                    .attr('y1', function(d) { return y(d.source); })
                    .attr('x2', function(d) { return x(d.target); })
                    .attr('y2', function(d) { return y(d.source); })
                    .style('visibility', function(d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; });

                g.select('line.vertical')
                    .attr('x1', function(d) { return x(d.target); })
                    .attr('y1', function(d) { return y(d.target); })
                    .attr('x2', function(d) { return x(d.target); })
                    .attr('y2', function(d) { return y(d.source); })
                    .style('visibility', function(d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; });

                var paddingValue = padding.apply(this, arguments);

                g.select('text.horizontal')
                    .attr('x', function(d) { return x(d.source) + (x(d.target) - x(d.source)) / 2; })
                    .attr('y', function(d) { return y(d.source) - paddingValue; })
                    .style('visibility', function(d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; })
                    .text(xLabel);

                g.select('text.vertical')
                    .attr('x', function(d) { return x(d.target) + paddingValue; })
                    .attr('y', function(d) { return y(d.source) + (y(d.target) - y(d.source)) / 2; })
                    .style('visibility', function(d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; })
                    .text(yLabel);

                decorate(g, data, index);
            });
        };

        function updatePositions() {
            var container = d3.select(this);
            var datum = container.datum()[0];
            if (datum.state !== 'DONE') {
                var mouse = d3.mouse(this);
                var snapped = snap.apply(this, mouse);
                if (datum.state === 'SELECT_SOURCE') {
                    datum.source = datum.target = snapped;
                } else if (datum.state === 'SELECT_TARGET') {
                    datum.target = snapped;
                } else {
                    throw new Error('Unknown state ' + datum.state);
                }
            }
        }

        function mouseenter() {
            var container = d3.select(this)
                .on('click.measure', mouseclick)
                .on('mousemove.measure', mousemove)
                .on('mouseleave.measure', mouseleave);
            var data = container.datum();
            if (data[0] == null) {
                data.push({
                    state: 'SELECT_SOURCE'
                });
            }
            updatePositions.call(this);
            container.call(measure);
        }

        function mousemove() {
            var container = d3.select(this);
            updatePositions.call(this);
            container.call(measure);
        }

        function mouseleave() {
            var container = d3.select(this);
            var data = container.datum();
            if (data[0] != null && data[0].state === 'SELECT_SOURCE') {
                data.pop();
            }
            container.on('click.measure', null)
                .on('mousemove.measure', null)
                .on('mouseleave.measure', null);
        }

        function mouseclick() {
            var container = d3.select(this);
            var datum = container.datum()[0];
            switch (datum.state) {
                case 'SELECT_SOURCE':
                    updatePositions.call(this);
                    event.measuresource.apply(this, arguments);
                    datum.state = 'SELECT_TARGET';
                    break;
                case 'SELECT_TARGET':
                    updatePositions.call(this);
                    event.measuretarget.apply(this, arguments);
                    datum.state = 'DONE';
                    break;
                case 'DONE':
                    event.measureclear.apply(this, arguments);
                    datum.state = 'SELECT_SOURCE';
                    updatePositions.call(this);
                    break;
                default:
                    throw new Error('Unknown state ' + datum.state);
            }
            container.call(measure);
        }

        measure.xScale = function(x) {
            if (!arguments.length) {
                return xScale;
            }
            xScale = x;
            return measure;
        };
        measure.yScale = function(x) {
            if (!arguments.length) {
                return yScale;
            }
            yScale = x;
            return measure;
        };
        measure.snap = function(x) {
            if (!arguments.length) {
                return snap;
            }
            snap = x;
            return measure;
        };
        measure.decorate = function(x) {
            if (!arguments.length) {
                return decorate;
            }
            decorate = x;
            return measure;
        };
        measure.xLabel = function(x) {
            if (!arguments.length) {
                return xLabel;
            }
            xLabel = d3.functor(x);
            return measure;
        };
        measure.yLabel = function(x) {
            if (!arguments.length) {
                return yLabel;
            }
            yLabel = d3.functor(x);
            return measure;
        };
        measure.padding = function(x) {
            if (!arguments.length) {
                return padding;
            }
            padding = d3.functor(x);
            return measure;
        };

        d3.rebind(measure, event, 'on');

        return measure;
    };

}(d3, fc));

redpajama_set_name: RedPajamaGithub


text:
package org.polyforms.repository.jpa.executor;

import javax.persistence.Query;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.polyforms.repository.jpa.QueryBuilder;
import org.polyforms.repository.jpa.QueryBuilder.QueryType;
import org.polyforms.repository.jpa.QueryParameterBinder;
import org.polyforms.repository.spi.EntityClassResolver;

public class CountByTest {
    private QueryExecutor executor;

    @Before
    public void setUp() {
        executor = new CountBy(EasyMock.createMock(EntityClassResolver.class), EasyMock.createMock(QueryBuilder.class),
                EasyMock.createMock(QueryParameterBinder.class));
    }

    @Test
    public void get() {
        final Query query = EasyMock.createMock(Query.class);
        query.getSingleResult();
        EasyMock.expectLastCall().andReturn(2L);
        EasyMock.replay(query);

        Assert.assertSame(2L, executor.getResult(null, query));
        EasyMock.verify(query);
    }

    @Test
    public void getQueryType() {
        Assert.assertSame(QueryType.COUNT, executor.getQueryType());
    }
}


text:
namespace cc {
namespace {

class TiledLayerImplTest : public testing::Test {
 public:
  TiledLayerImplTest() : host_impl_(&proxy_) {}

  // Create a default tiled layer with textures for all tiles and a default
  // visibility of the entire layer size.
  scoped_ptr<TiledLayerImpl> CreateLayer(
      gfx::Size tile_size,
      gfx::Size layer_size,
      LayerTilingData::BorderTexelOption border_texels) {
    scoped_ptr<TiledLayerImpl> layer =
        TiledLayerImpl::Create(host_impl_.active_tree(), 1);
    scoped_ptr<LayerTilingData> tiler =
        LayerTilingData::Create(tile_size, border_texels);
    tiler->SetBounds(layer_size);
    layer->SetTilingData(*tiler);
    layer->set_skips_draw(false);
    layer->draw_properties().visible_content_rect =
        gfx::Rect(gfx::Point(), layer_size);
    layer->draw_properties().opacity = 1;
    layer->SetBounds(layer_size);
    layer->SetContentBounds(layer_size);
    layer->CreateRenderSurface();
    layer->draw_properties().render_target = layer.get();

    ResourceProvider::ResourceId resource_id = 1;
    for (int i = 0; i < tiler->num_tiles_x(); ++i) {
      for (int j = 0; j < tiler->num_tiles_y(); ++j) {
        layer->PushTileProperties(
            i, j, resource_id++, gfx::Rect(0, 0, 1, 1), false);
      }
    }

    return layer.Pass();
  }

  void GetQuads(QuadList* quads,
                SharedQuadStateList* shared_states,
                gfx::Size tile_size,
                gfx::Size layer_size,
                LayerTilingData::BorderTexelOption border_texel_option,
                gfx::Rect visible_content_rect) {
    scoped_ptr<TiledLayerImpl> layer =
        CreateLayer(tile_size, layer_size, border_texel_option);
    layer->draw_properties().visible_content_rect = visible_content_rect;
    layer->SetBounds(layer_size);

    MockQuadCuller quad_culler(quads, shared_states);
    AppendQuadsData data;
    layer->AppendQuads(&quad_culler, &data);
  }

 protected:
  FakeImplProxy proxy_;
  FakeLayerTreeHostImpl host_impl_;
};

TEST_F(TiledLayerImplTest, EmptyQuadList) {
  gfx::Size tile_size(90, 90);
  int num_tiles_x = 8;
  int num_tiles_y = 4;
  gfx::Size layer_size(tile_size.width() * num_tiles_x,
                       tile_size.height() * num_tiles_y);

  // Verify default layer does creates quads
  {
    scoped_ptr<TiledLayerImpl> layer =
        CreateLayer(tile_size, layer_size, LayerTilingData::NO_BORDER_TEXELS);
    MockQuadCuller quad_culler;
    AppendQuadsData data;
    layer->AppendQuads(&quad_culler, &data);
    unsigned num_tiles = num_tiles_x * num_tiles_y;
    EXPECT_EQ(quad_culler.quad_list().size(), num_tiles);
  }

  // Layer with empty visible layer rect produces no quads
  {
    scoped_ptr<TiledLayerImpl> layer =
        CreateLayer(tile_size, layer_size, LayerTilingData::NO_BORDER_TEXELS);
    layer->draw_properties().visible_content_rect = gfx::Rect();

    MockQuadCuller quad_culler;
    AppendQuadsData data;
    layer->AppendQuads(&quad_culler, &data);
    EXPECT_EQ(quad_culler.quad_list().size(), 0u);
  }

  // Layer with non-intersecting visible layer rect produces no quads
  {
    scoped_ptr<TiledLayerImpl> layer =
        CreateLayer(tile_size, layer_size, LayerTilingData::NO_BORDER_TEXELS);

    gfx::Rect outsideBounds(gfx::Point(-100, -100), gfx::Size(50, 50));
    layer->draw_properties().visible_content_rect = outsideBounds;

    MockQuadCuller quad_culler;
    AppendQuadsData data;
    layer->AppendQuads(&quad_culler, &data);
    EXPECT_EQ(quad_culler.quad_list().size(), 0u);
  }

  // Layer with skips draw produces no quads
  {
    scoped_ptr<TiledLayerImpl> layer =
        CreateLayer(tile_size, layer_size, LayerTilingData::NO_BORDER_TEXELS);
    layer->set_skips_draw(true);

    MockQuadCuller quad_culler;
    AppendQuadsData data;
    layer->AppendQuads(&quad_culler, &data);
    EXPECT_EQ(quad_culler.quad_list().size(), 0u);
  }
}

TEST_F(TiledLayerImplTest, Checkerboarding) {
  gfx::Size tile_size(10, 10);
  int num_tiles_x = 2;
  int num_tiles_y = 2;
  gfx::Size layer_size(tile_size.width() * num_tiles_x,
                       tile_size.height() * num_tiles_y);

  scoped_ptr<TiledLayerImpl> layer =
      CreateLayer(tile_size, layer_size, LayerTilingData::NO_BORDER_TEXELS);

  // No checkerboarding
  {
    MockQuadCuller quad_culler;
    AppendQuadsData data;
    layer->AppendQuads(&quad_culler, &data);
    EXPECT_EQ(quad_culler.quad_list().size(), 4u);
    EXPECT_EQ(0u, data.numMissingTiles);

    for (size_t i = 0; i < quad_culler.quad_list().size(); ++i)
      EXPECT_EQ(quad_culler.quad_list()[i]->material, DrawQuad::TILED_CONTENT);
  }

  for (int i = 0; i < num_tiles_x; ++i)
    for (int j = 0; j < num_tiles_y; ++j)
      layer->PushTileProperties(i, j, 0, gfx::Rect(), false);

  // All checkerboarding
  {
    MockQuadCuller quad_culler;
    AppendQuadsData data;
    layer->AppendQuads(&quad_culler, &data);
    EXPECT_LT(0u, data.numMissingTiles);
    EXPECT_EQ(quad_culler.quad_list().size(), 4u);
    for (size_t i = 0; i < quad_culler.quad_list().size(); ++i)
      EXPECT_NE(quad_culler.quad_list()[i]->material, DrawQuad::TILED_CONTENT);
  }
}

// Test with both border texels and without.
#define WITH_AND_WITHOUT_BORDER_TEST(text_fixture_name)                        \
  TEST_F(TiledLayerImplBorderTest, text_fixture_name##NoBorders) {             \
    text_fixture_name(LayerTilingData::NO_BORDER_TEXELS);                      \
  }                                                                            \
  TEST_F(TiledLayerImplBorderTest, text_fixture_name##HasBorders) {            \
    text_fixture_name(LayerTilingData::HAS_BORDER_TEXELS);                     \
  }

class TiledLayerImplBorderTest : public TiledLayerImplTest {
 public:
  void CoverageVisibleRectOnTileBoundaries(
      LayerTilingData::BorderTexelOption borders) {
    gfx::Size layer_size(1000, 1000);
    QuadList quads;
    SharedQuadStateList shared_states;
    GetQuads(&quads,
             &shared_states,
             gfx::Size(100, 100),
             layer_size,
             borders,
             gfx::Rect(gfx::Point(), layer_size));
    LayerTestCommon::VerifyQuadsExactlyCoverRect(
        quads, gfx::Rect(gfx::Point(), layer_size));
  }

  void CoverageVisibleRectIntersectsTiles(
      LayerTilingData::BorderTexelOption borders) {
    // This rect intersects the middle 3x3 of the 5x5 tiles.
    gfx::Point top_left(65, 73);
    gfx::Point bottom_right(182, 198);
    gfx::Rect visible_content_rect = gfx::BoundingRect(top_left, bottom_right);

    gfx::Size layer_size(250, 250);
    QuadList quads;
    SharedQuadStateList shared_states;
    GetQuads(&quads,
             &shared_states,
             gfx::Size(50, 50),
             gfx::Size(250, 250),
             LayerTilingData::NO_BORDER_TEXELS,
             visible_content_rect);
    LayerTestCommon::VerifyQuadsExactlyCoverRect(quads, visible_content_rect);
  }

  void CoverageVisibleRectIntersectsBounds(
      LayerTilingData::BorderTexelOption borders) {
    gfx::Size layer_size(220, 210);
    gfx::Rect visible_content_rect(layer_size);
    QuadList quads;
    SharedQuadStateList shared_states;
    GetQuads(&quads,
             &shared_states,
             gfx::Size(100, 100),
             layer_size,
             LayerTilingData::NO_BORDER_TEXELS,
             visible_content_rect);
    LayerTestCommon::VerifyQuadsExactlyCoverRect(quads, visible_content_rect);
  }
};
WITH_AND_WITHOUT_BORDER_TEST(CoverageVisibleRectOnTileBoundaries);

WITH_AND_WITHOUT_BORDER_TEST(CoverageVisibleRectIntersectsTiles);

WITH_AND_WITHOUT_BORDER_TEST(CoverageVisibleRectIntersectsBounds);

TEST_F(TiledLayerImplTest, TextureInfoForLayerNoBorders) {
  gfx::Size tile_size(50, 50);
  gfx::Size layer_size(250, 250);
  QuadList quads;
  SharedQuadStateList shared_states;
  GetQuads(&quads,
           &shared_states,
           tile_size,
           layer_size,
           LayerTilingData::NO_BORDER_TEXELS,
           gfx::Rect(gfx::Point(), layer_size));

  for (size_t i = 0; i < quads.size(); ++i) {
    const TileDrawQuad* quad = TileDrawQuad::MaterialCast(quads[i]);

    EXPECT_NE(0u, quad->resource_id) << LayerTestCommon::quad_string << i;
    EXPECT_EQ(gfx::RectF(gfx::PointF(), tile_size), quad->tex_coord_rect)
        << LayerTestCommon::quad_string << i;
    EXPECT_EQ(tile_size, quad->texture_size) << LayerTestCommon::quad_string
                                             << i;
    EXPECT_EQ(gfx::Rect(0, 0, 1, 1), quad->opaque_rect)
        << LayerTestCommon::quad_string << i;
  }
}

}  // namespace
}  // namespace cc


text:
// Copyright 2010 Konrad Twardowski
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.makagiga.commons.swing;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseEvent;
import java.beans.Beans;
import java.net.URI;
import java.util.Objects;
import javax.swing.Action;
import javax.swing.TransferHandler;

import org.makagiga.commons.Globals;
import org.makagiga.commons.MApplication;
import org.makagiga.commons.MColor;
import org.makagiga.commons.Net;
import org.makagiga.commons.TK;
import org.makagiga.commons.UI;
import org.makagiga.commons.WTFError;
import org.makagiga.commons.fx.Blend;
import org.makagiga.commons.html.HTMLSelection;
import org.makagiga.commons.sb.SecureOpen;
import org.makagiga.commons.security.MAccessController;
import org.makagiga.commons.swing.event.MMouseAdapter;

/**
 * @since 3.8.3, 4.0 (org.makagiga.commons.swing package)
 *
 * @mg.warning
 * {@link #getText()} may not work as you expected.
 * Use {@link #getURI()} to get the actual URI value.
 */
public class MLinkButton extends MButton implements SecureOpen {

	// public

	/**
	 * @since 4.8
	 */
	public enum LinkColorStyle {

		DEFAULT,
		INHERIT,

		/**
		 * @since 4.10
		 */
		SIMPLE

	}

	// private

	private boolean dragEnabled;
	private boolean secureOpen;
	private boolean showLinkActions = true;
	private Color linkColor;
	private Color linkHoverColor;
	private LinkColorStyle linkColorStyle;
	private String uriAsString = Net.ABOUT_BLANK.toString();
	private String title;
	private URI _uri = Net.ABOUT_BLANK;

	// public

	public MLinkButton() {
		// HACK: disable; too small default drag threshold (2px) on Windows
		// starts drag operation instead of regular click.
		// dragEnabled = Kiosk.actionDragDrop.get();

		setContentAreaFilled(false);
		setCursor(Cursor.HAND_CURSOR);
		setHorizontalAlignment(LEADING);
		setOpaque(false);
		setRequestFocusEnabled(false);
		setStyle("margin: 2; padding: 0");

		new StaticDragHandler(this);
		UI.onKeyPressed(this, e -> {
			if (UI.isPopupTrigger(e))
				showLinkMenu();
		} );
		addMouseListener(new StaticMouseHandler());

		if (Beans.isDesignTime())
			setText(MLinkAction.simplifyURI(uriAsString));
	}

	/**
	 * @since 4.10
	 */
	public MLinkButton(final Action action) {
		this();
		setAction(action);
	}

	public MLinkButton(final URI uri) {
		this();
		setURIAndText(uri);
	}

	public MLinkButton(final URI uri, final String text) {
		this();
		setURI(uri);
		setText(text);
	}

	@Override
	public void addNotify() {
		super.addNotify();
		// get color from parent
		updateLinkColor(false);
	}

	/**
	 * Opens the current URI.
	 *
	 * @since 3.0
	 */
	public void doOpen() {
		if (!isBlankURI()) {
			// mark as visited
			setVisited(true);
			try {
				MApplication.openURI(getURI(), this);
			}
			catch (IllegalArgumentException exception) {
				MMessage.error(UI.windowFor(this), exception);
			}
		}
	}

	/**
	 * @since 3.8.7
	 */
	public Color getHoverLinkColor() {
		if (getLinkColorStyle() == LinkColorStyle.SIMPLE)
			return UI.getForeground(this);

		if (isVisited())
			return MColor.getVisitedLinkForeground(getParentBackground());

		if (linkHoverColor != null)
			return linkHoverColor;

		return MColor.getHoverLinkForeground(getParentBackground());
	}

	/**
	 * @since 3.8.7
	 */
	public void setHoverLinkColor(final Color value) { linkHoverColor = value; }

	/**
	 * @since 3.8.6
	 */
	public Color getLinkColor() {
		if (isVisited())
			return MColor.getVisitedLinkForeground(getParentBackground());

		// user color
		if (linkColor != null)
			return linkColor;

		switch (getLinkColorStyle()) {
			case DEFAULT: return MColor.getLinkForeground(getParentBackground());
			case INHERIT:
				Container parent = getParent();

				return (parent == null) ? Color.BLACK : UI.getForeground(parent);
			case SIMPLE: return UI.getForeground(this);
			default: throw new WTFError(getLinkColorStyle());
		}
	}

	/**
	 * @since 3.8.6
	 */
	public void setLinkColor(final Color value) {
		if (!Objects.equals(value, linkColor)) {
			linkColor = value;
			updateLinkColor(true);
		}
	}

	/**
	 * @since 4.8
	 */
	public LinkColorStyle getLinkColorStyle() {
		return TK.get(linkColorStyle, LinkColorStyle.DEFAULT);
	}

	/**
	 * @since 4.8
	 */
	public void setLinkColorStyle(final LinkColorStyle value) {
		Objects.requireNonNull(value);

		if (value != linkColorStyle) {
			linkColorStyle = value;
			updateLinkColor(true);
		}
	}

	public boolean getShowLinkActions() { return showLinkActions; }

	public void setShowLinkActions(final boolean value) { showLinkActions = value; }

	/**
	 * @since 2.0
	 */
	public String getTitle() { return title; }

	/**
	 * @since 2.0
	 */
	public void setTitle(final String value) { title = value; }

	/**
	 * @since 4.0
	 */
	public URI getURI() { return _uri; }

	/**
	 * @since 4.0
	 */
	public void setURI(final String value) {
		setURI((value == null) ? Net.ABOUT_BLANK : Net.fixURI(value));
	}

	/**
	 * @since 4.0
	 */
	public void setURI(final URI value) {
		if (!Objects.equals(getURI(), value)) {
			_uri = (value == null) ? Net.ABOUT_BLANK : value;
			uriAsString = _uri.toString();
			setToolTipText(UI.getLinkToolTipText(uriAsString));
			updateLinkColor(true);
		}
	}

	/**
	 * @since 4.0
	 */
	public void setURIAndText(final URI value) {
		setURI(value);
		String s = TK.centerSqueeze(MLinkAction.simplifyURI(uriAsString), 128);
		if (UI.isRetro())
			setText("<" + s + ">");
		else
			setText(s);
	}

	/**
	 * @since 4.0
	 */
	public boolean isBlankURI() {
		return (_uri == null) || _uri.equals(Net.ABOUT_BLANK);
	}

	/**
	 * @since 2.0
	 */
	public boolean isDragEnabled() { return dragEnabled; }

	/**
	 * @since 2.0
	 */
	public void setDragEnabled(final boolean value) { dragEnabled = value; }

	/**
	 * @mg.default {@code false} since 3.8.6
	 *
	 * @since 2.0
	 */
	@Override
	public boolean isSecureOpen() { return secureOpen; }

	/**
	 * @since 2.0
	 */
	@Override
	public void setSecureOpen(final boolean value) { secureOpen = value; }

	/**
	 * @since 2.0
	 */
	public boolean isVisited() {
		if (isBlankURI())
			return false;

		return MAccessController.doPrivileged(() -> Globals.isLinkVisited(uriAsString));
	}

	/**
	 * @since 2.0
	 */
	public void setVisited(final boolean value) {
		if (value != isVisited()) {
			MAccessController.doPrivileged(() -> {
				Globals.setLinkVisited(uriAsString, value);

				return null;
			} );
			updateLinkColor(true);
		}
	}

	public void showLinkMenu() {
		if (isBlankURI())
			return;

		MMenu menu = new MMenu();
		Globals.updateLinkMenu(
			menu,
			getURI(),
			showLinkActions,
			TK.get(title, getText())
		);
		if (!menu.isEmpty())
			menu.showPopup(this);
	}

	@Override
	public void updateUI() {
		setUI(UI.getSimpleButtonUI());
		updateLinkColor(false);
	}

	// protected

	/**
	 * Overriden to handle action or mouse click event.
	 * By default this method opens the current URL in a web browser.
	 */
	@Override
	protected void onClick() {
		doOpen();
	}

	// private

	private Color getParentBackground() {
		Component parent = getParent();

		// HACK: fix link foreground color for dark toolbar backgrounds
		if (
			UI.isSubstance() &&
			(parent != null) &&
			(
				(UI.getAncestorOfClass(MToolBar.class, this) != null) ||
				(UI.getAncestorOfClass(MMenuBar.class, this) != null)
			) &&
			Boolean.getBoolean("org.makagiga.plugins.substance.Plugin.isDarkToolBarBackground")
		) {
			return Color.BLACK;
		}

		return (parent == null) ? getBackground() : parent.getBackground();
	}

	private void updateLinkColor(final boolean stopAnimation) {
		if (stopAnimation)
			Blend.stopAnimation(this);
		setForeground(getLinkColor());
	}

	// private classes

	private static final class StaticDragHandler extends MMouseAdapter.Drag {

		// protected

		@Override
		protected boolean canDrag(final MouseEvent e) {
			MLinkButton c = (MLinkButton)e.getSource();

			return c.dragEnabled && !c.isBlankURI();
		}

		@Override
		protected Image createDragImage(final MouseEvent e) {
			MLinkButton c = (MLinkButton)e.getSource();

			return MComponent.createScreenshot(c, null);
		}

		@Override
		protected Transferable createTransferable(final MouseEvent e) {
			MLinkButton c = (MLinkButton)e.getSource();

			if (c.isBlankURI())
				return null;

			return HTMLSelection.fromURI(c.uriAsString);
		}

		// private

		private StaticDragHandler(final MLinkButton button) {
// TODO: 2.0: uri-list
// TODO: 2.6: LINK
			super(button, TransferHandler.COPY);
		}

	}

	private static final class StaticMouseHandler extends MMouseAdapter {

		// public

		public StaticMouseHandler() { }

		@Override
		public void mouseEntered(final MouseEvent e) {
			MLinkButton c = (MLinkButton)e.getSource();
			if (c.isEnabled()) {
				if (UI.isRetro()) {
					c.setForeground(c.getHoverLinkColor());
				}
				else {
					c.setStyle("text-decoration: underline");
					Blend.animateForeground(c, c.getLinkColor(), c.getHoverLinkColor());
				}
			}
		}

		@Override
		public void mouseExited(final MouseEvent e) {
			MLinkButton c = (MLinkButton)e.getSource();
			if (c.isEnabled()) {
				if (UI.isRetro()) {
					c.setForeground(c.getLinkColor());
				}
				else {
					c.setStyle("text-decoration: none");
					Blend.animateForeground(c, c.getHoverLinkColor(), c.getLinkColor());
				}
			}
		}

		@Override
		public void popupTrigger(final MouseEvent e) {
			MLinkButton c = (MLinkButton)e.getSource();
			c.showLinkMenu();
		}

	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exporting a C API</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="index.html" title="GObject Reference Manual">
<link rel="up" href="chapter-intro.html" title="Background">
<link rel="prev" href="chapter-intro.html" title="Background">
<link rel="next" href="chapter-gtype.html" title="The GLib Dynamic Type System">
<meta name="generator" content="GTK-Doc V1.14 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GObject Reference Manual

Exporting a C API

      C APIs are defined by a set of functions and global variables which are usually exported from a
      binary. C functions have an arbitrary number of arguments and one return value. Each function is thus
      uniquely identified by the function name and the set of C types which describe the function arguments
      and return value. The global variables exported by the API are similarly identified by their name and
      their type.

      A C API is thus merely defined by a set of names to which a set of types are associated. If you know the
      function calling convention and the mapping of the C types to the machine types used by the platform you
      are on, you can resolve the name of each function to find where the code associated to this function
      is located in memory, and then construct a valid argument list for the function. Finally, all you have to
      do is trigger a call to the target C function with the argument list.

      For the sake of discussion, here is a sample C function and the associated 32 bit x86
      assembly code generated by GCC on my Linux box:

static void function_foo (int foo)
{}

int main (int argc, char *argv[])
{

        function_foo (10);

        return 0;
}

push   $0xa
call   0x80482f4 <function_foo>

      The assembly code shown above is pretty straightforward: the first instruction pushes
      the hexadecimal value 0xa (decimal value 10) as a 32-bit integer on the stack and calls
      function_foo. As you can see, C function calls are implemented by
      gcc by native function calls (this is probably the fastest implementation possible).

      Now, let's say we want to call the C function function_foo from
      a Python program. To do this, the Python interpreter needs to:

Find where the function is located. This probably means finding the binary generated by the C compiler
        which exports this function.

Load the code of the function in executable memory.

Convert the Python parameters to C-compatible parameters before calling
        the function.

Call the function with the right calling convention.

Convert the return values of the C function to Python-compatible
        variables to return them to the Python code.

      The process described above is pretty complex and there are a lot of ways to make it entirely automatic
      and transparent to C and Python programmers:

The first solution is to write by hand a lot of glue code, once for each function exported or imported,
        which does the Python-to-C parameter conversion and the C-to-Python return value conversion. This glue code is then
        linked with the interpreter which allows Python programs to call Python functions which delegate work to
        C functions.

Another, nicer solution is to automatically generate the glue code, once for each function exported or
        imported, with a special compiler which
        reads the original function signature.

The solution used by GLib is to use the GType library which holds at runtime a description of
        all the objects manipulated by the programmer. This so-called dynamic type
        [1]
        library is then used by special generic glue code to automatically convert function parameters and
        function calling conventions between different runtime domains.

      The greatest advantage of the solution implemented by GType is that the glue code sitting at the runtime domain
      boundaries is written once: the figure below states this more clearly.

Figure 1.

      Currently, there exist at least Python and Perl generic glue code which makes it possible to use
      C objects written with GType directly in Python or Perl, with a minimum amount of work: there
      is no need to generate huge amounts of glue code either automatically or by hand.

      Although that goal was arguably laudable, its pursuit has had a major influence on
      the whole GType/GObject library. C programmers are likely to be puzzled at the complexity
      of the features exposed in the following chapters if they forget that the GType/GObject library
      was not only designed to offer OO-like features to C programmers but also transparent
      cross-language interoperability.

[1]
            There are numerous different implementations of dynamic type systems: all C++
            compilers have one, Java and .NET have one too. A dynamic type system allows you
            to get information about every instantiated object at runtime. It can be implemented
            by a process-specific database: every new object created registers the characteristics
            of its associated type in the type system. It can also be implemented by introspection
            interfaces. The common point between all these different type systems and implementations
            is that they all allow you to query for object metadata at runtime.

          Generated by GTK-Doc V1.14


text:
package rapidandroidsdk.sdk.payment.eway.com.rxjavasample;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lobaria pulmonaria var. isidiosa Zahlbr.

### Remarks
null


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './urlUpload.scss';
import WhiteExit from '../img/whiteExit.png';
import WhiteExit2x from '../img/whiteExit@2x.png';
import WhiteExit3x from '../img/whiteExit@3x.png';
import Complete from '../img/complete.png';
import Complete2x from '../img/complete@2x.png';
import Complete3x from '../img/complete@3x.png';

const propTypes = {
  back: PropTypes.func.isRequired,
  thumbURL: PropTypes.string.isRequired
};

class URLSuccess extends Component {
  render() {
    const { back, thumbURL } = this.props;
    // const { } = this.state;
    const youtubeThumbnail = {
      backgroundImage: `url(${thumbURL})`
    };
    return (

              <img
                src={ WhiteExit }
                srcSet={ `${WhiteExit2x} 2x,${WhiteExit3x} 3x` }
                className="whiteExitIcon"
                alt="옵션 선택 취소" />

            <img
              src={ Complete }
              srcSet={ `${Complete2x} 2x,${Complete3x} 3x` }
              className="completeIcon"
              alt="업로드 완료 아이콘" />

              해당 URL은 안전합니다.

              성공적으로 영상이 첨부되었습니다.

    );
  }
}

URLSuccess.propTypes = propTypes;

export default URLSuccess;


text:
package Buddha::BadFixture3;

use strict;
use warnings;
use base qw(Test::FITesque::Fixture);

sub tai : Test : Plan(0) {
  return 'tai';
}

1;


text:
+++
pre = "<b>3.4.3. </b>"
title = "Principle"
weight = 3
chapter = true
+++

## Navigation

This chapter mainly introduces the principles of the distributed transactions:

* 2PC transaction-XA
* Seata BASE transaction


text:
layout: page
title: Charm Flex Corporation Party
date: 2016-05-24
author: Denise Greer
tags: weekly links, java
status: published
summary: In mattis tortor ac lacus.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 09/04/2017
  endDate: 09/08/2017
  ctyhocn: MOBAPHX
  groupCode: CFCP
published: true
---
Etiam iaculis nibh a auctor facilisis. Nam gravida placerat quam. Praesent a nisl in purus egestas faucibus eu sed lectus. Nunc a sapien a nisl pulvinar cursus ut eu est. Cras nec nunc sit amet arcu suscipit tincidunt. Vivamus ut gravida odio. Nullam eget ipsum finibus, rhoncus ipsum et, imperdiet nibh. Ut vel metus tellus.

* Ut efficitur magna vitae purus pulvinar, non bibendum leo efficitur
* Fusce pellentesque erat sed arcu vehicula, ut scelerisque dolor accumsan.

Maecenas finibus metus purus, nec varius ex maximus vel. Pellentesque pulvinar pellentesque ipsum et aliquet. Fusce ut aliquet enim. Sed id nisl urna. Phasellus ac nunc gravida, accumsan sem ut, vehicula justo. Morbi molestie cursus orci dignissim tincidunt. Etiam eros eros, dictum vitae neque et, consequat suscipit purus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce non purus id mauris malesuada ultrices ut ac libero. Pellentesque sollicitudin vulputate urna nec rhoncus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;


text:
package griffon.pivot.support.adapters;

import griffon.core.CallableWithArgs;

/**
 * @author Andres Almiray
 * @since 2.0.0
 */
public class ColorChooserButtonSelectionAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.ColorChooserButtonSelectionListener {
    private CallableWithArgs<Void> selectedColorChanged;

    public CallableWithArgs<Void> getSelectedColorChanged() {
        return this.selectedColorChanged;
    }

    public void setSelectedColorChanged(CallableWithArgs<Void> selectedColorChanged) {
        this.selectedColorChanged = selectedColorChanged;
    }

    public void selectedColorChanged(org.apache.pivot.wtk.ColorChooserButton arg0, java.awt.Color arg1) {
        if (selectedColorChanged != null) {
            selectedColorChanged.call(arg0, arg1);
        }
    }

}


text:
package org.hcjf.utils;

import org.hcjf.layers.Layers;
import org.hcjf.layers.locale.LocaleLayerInterface;
import org.hcjf.properties.SystemProperties;

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

/**
 * Message manager
 * @author javaito
 *
 */
public class Messages {

    private final Map<String, String> defaultMessages;

    protected Messages() {
        defaultMessages = new HashMap<>();

        //Publishing default layers
        Layers.publishLayer(SystemProperties.getClass(SystemProperties.HCJF_DEFAULT_LOCALE_LAYER_IMPLEMENTATION));
    }

    /**
     * Returnt he message associated to the error code.
     * @param messageCode Message code.
     * @param params Parameters to complete the message.
     * @return Message complete and translated.
     */
    protected String getInternalMessage(String messageCode, Object... params) {
        String result = defaultMessages.get(messageCode);

        if(result == null) {
            result = messageCode;
        } else {
            result = Layers.get(LocaleLayerInterface.class,
                    SystemProperties.get(SystemProperties.HCJF_DEFAULT_LOCALE_LAYER_IMPLEMENTATION_NAME)).translate(result);
        }

        return String.format(result, params);
    }

    /**
     * Add the default value associated to error code.
     * @param errorCode Error code.
     * @param defaultMessage Default message.
     */
    protected void addInternalDefault(String errorCode, String defaultMessage) {
        defaultMessages.put(errorCode, defaultMessage);
    }

}


text: import './unreadMessages';


text:
<?php

namespace Code4\Platform\Components\Search;

class Search
{
    protected $providers;

    public function __construct() {
        $config = \Config::get('search');
        $this->providers = $config['registeredProviders'];
    }

    /**
     * @param $providers
     */
    public function setProviders($providers) {
        $this->providers = (array) $providers;
    }

    public function makeSearch($str) {
        $result = "";
        foreach($this->providers as $provider) {
            $o = new $provider;
            if ($o instanceof SearchInterface) {
                $itemResults = $o->search($str);
                $icon = $o->searchIcon();
                if (!count($itemResults)) { continue; }

               $result .= view('platform::components.search.searchResult', compact('itemResults','icon'));
            }
        }
        return $result;
    }
}


text:
/**
 *
 * Emerald (kbi/elude @2012-2016)
 *
 */
#include "shared.h"
#include "ral/ral_context.h"
#include "ral/ral_shader.h"
#include "shaders/shaders_fragment_saturate.h"
#include "system/system_assertions.h"
#include "system/system_hashed_ansi_string.h"
#include "system/system_log.h"
#include <sstream>

/* Internal variables */
const char* saturate_fragment_shader_body =
    "#version 430 core\n"
    "\n"
    "in vec2 uv;\n"
    "\n"
    "uniform sampler2D in_texture;\n"
    "uniform float     strength;\n"
    "\n"
    "out vec4 color;\n"
    "\n"
    "void main()\n"
    "{\n"
    "    vec4  in_texel = texture(in_texture, uv);\n"
    "    float avg      = (in_texel.x + in_texel.y + in_texel.z) / 3.0;\n"
    "\n"
    "    color = vec4(avg + strength * (in_texel.rgb - avg), 1.0);\n"
    "}\n";

/** Internal type definition */
typedef struct
{
    ral_context context;
    ral_shader  shader;

    REFCOUNT_INSERT_VARIABLES
} _shaders_fragment_saturate;

/** Reference counter impl */
REFCOUNT_INSERT_IMPLEMENTATION(shaders_fragment_saturate,
                               shaders_fragment_saturate,
                              _shaders_fragment_saturate);

/** Function called back when reference counter drops to zero. Releases the shader object.
 *
 *  @param ptr Pointer to _shaders_fragment_saturate instance.
 **/
PRIVATE void _shaders_fragment_saturate_release(void* ptr)
{
    _shaders_fragment_saturate* data_ptr = reinterpret_cast<_shaders_fragment_saturate*>(ptr);

    if (data_ptr->shader != nullptr)
    {
        ral_context_delete_objects(data_ptr->context,
                                   RAL_CONTEXT_OBJECT_TYPE_SHADER,
                                   1, /* n_objects */
                                   reinterpret_cast<void* const*>(&data_ptr->shader) );

        data_ptr->shader = nullptr;
    }
}

/** Please see header for specification */
PUBLIC EMERALD_API shaders_fragment_saturate shaders_fragment_saturate_create(ral_context               context,
                                                                              system_hashed_ansi_string name)
{
    _shaders_fragment_saturate* result_object_ptr = nullptr;
    ral_shader                  shader            = nullptr;

    /* Create the shader */
    system_hashed_ansi_string shader_body       (system_hashed_ansi_string_create(saturate_fragment_shader_body) );
    ral_shader_create_info    shader_create_info(name,
                                                 RAL_SHADER_TYPE_FRAGMENT);

    if (!ral_context_create_shaders(context,
                                    1, /* n_create_info_items */
                                   &shader_create_info,
                                   &shader) )
    {
        ASSERT_DEBUG_SYNC(false,
                          "Could not create a RAL shader instance");

        goto end;
    }

    ral_shader_set_property(shader,
                            RAL_SHADER_PROPERTY_GLSL_BODY,
                           &shader_body);

    /* Everything went okay. Instantiate the object */
    result_object_ptr = new (std::nothrow) _shaders_fragment_saturate;

    ASSERT_DEBUG_SYNC(result_object_ptr != nullptr,
                      "Out of memory while instantiating _shaders_fragment_saturate object.");

    if (result_object_ptr == nullptr)
    {
        goto end;
    }

    result_object_ptr->context = context;
    result_object_ptr->shader  = shader;

    /* Return the object */
    return (shaders_fragment_saturate) result_object_ptr;

end:
    if (shader != nullptr)
    {
        ral_context_delete_objects(context,
                                   RAL_CONTEXT_OBJECT_TYPE_SHADER,
                                   1, /* n_objects */
                                   reinterpret_cast<void* const*>(&shader) );

        shader = nullptr;
    }

    return nullptr;
}

/** Please see header for specification */
PUBLIC EMERALD_API ral_shader shaders_fragment_saturate_get_shader(shaders_fragment_saturate shader)
{
    return (((_shaders_fragment_saturate*)shader)->shader);
}


text:
package server

import (
	"github.com/kubernetes-sigs/service-catalog/cmd/cleaner/server"
	"github.com/kubernetes-sigs/service-catalog/pkg/hyperkube"
)

// NewCleaner creates a new hyperkube Server object that includes the
// description and flags of the Cleaner functionality.
func NewCleaner() *hyperkube.Server {
	opts := server.NewCleanerOptions()

	hks := hyperkube.Server{
		PrimaryName:     "cleaner",
		AlternativeName: "service-catalog-cleaner",
		SimpleUsage:     "cleaner",
		Long:            "The cleaner asserts all CRD will be removed before removing helm release, it also removes all finalizers from CRs",
		Run: func(_ *hyperkube.Server, args []string, stopCh <-chan struct{}) error {
			return server.RunCommand(opts)
		},
		RespectsStopCh: false,
	}
	opts.AddFlags(hks.Flags())

	return &hks
}


text:
CountDown::CountDown(const enum Resolution res)
{
    setResolution(res);
    stop();
}

void CountDown::setResolution(const enum Resolution res)
{
    _res = res;
    switch(_res)
    {
    case MICROS:
        _gettime = micros;
        break;
    case SECONDS:
        _gettime = seconds;
        break;
    case MILLIS:
    default:
        _gettime = millis;
        break;
    }
}

void CountDown::start(uint32_t ticks)
{
    _state = CountDown::RUNNING;
    _starttime = _gettime();
    _ticks = ticks;
}

unsigned long CountDown::remaining()
{
    calcRemaining();
    return _remaining;
}

void CountDown::stop()
{
    calcRemaining();
    _state = CountDown::STOPPED;
}

void CountDown::calcRemaining()
{
    if (_state == CountDown::RUNNING)
    {
        uint32_t t = _gettime() - _starttime;
        _remaining = _ticks > t? _ticks - t: 0;
        if (_remaining == 0)
        {
            _state = CountDown::STOPPED;
        }
    }
}
// END OF FILE


text:
// -----------------------------------------------------------------------------
//  Headers:
// -----------------------------------------------------------------------------

#import <Foundation/Foundation.h>
#include <sys/types.h>
#include <sys/event.h>
#import "UKFileWatcher.h"

// -----------------------------------------------------------------------------
//  Constants:
// -----------------------------------------------------------------------------

// Backwards compatibility constants. Don't rely on code commented out with these constants, because it may be deleted in a future version.
#ifndef UKKQUEUE_BACKWARDS_COMPATIBLE
#define UKKQUEUE_BACKWARDS_COMPATIBLE 0			// 1 to send old-style kqueue:receivedNotification:forFile: messages to objects that accept them.
#endif

#ifndef UKKQUEUE_SEND_STUPID_NOTIFICATIONS
#define UKKQUEUE_SEND_STUPID_NOTIFICATIONS 0	// 1 to send old-style notifications that have the path as the object and no userInfo dictionary.
#endif

#ifndef UKKQUEUE_OLD_SINGLETON_ACCESSOR_NAME
#define UKKQUEUE_OLD_SINGLETON_ACCESSOR_NAME 0	// 1 to allow use of sharedQueue instead of sharedFileWatcher.
#endif

#ifndef UKKQUEUE_OLD_NOTIFICATION_NAMES
#define UKKQUEUE_OLD_NOTIFICATION_NAMES 0		// 1 to allow use of old KQueue-style notification names instead of the new more generic ones in UKFileWatcher.
#endif

// Flags for notifyingAbout:
#define UKKQueueNotifyAboutRename					NOTE_RENAME		// Item was renamed.
#define UKKQueueNotifyAboutWrite					NOTE_WRITE		// Item contents changed (also folder contents changed).
#define UKKQueueNotifyAboutDelete					NOTE_DELETE		// item was removed.
#define UKKQueueNotifyAboutAttributeChange			NOTE_ATTRIB		// Item attributes changed.
#define UKKQueueNotifyAboutSizeIncrease				NOTE_EXTEND		// Item size increased.
#define UKKQueueNotifyAboutLinkCountChanged			NOTE_LINK		// Item's link count changed.
#define UKKQueueNotifyAboutAccessRevocation			NOTE_REVOKE		// Access to item was revoked.

// Notifications this sends:
//  (see UKFileWatcher)
// Old names: *deprecated*
#if UKKQUEUE_OLD_NOTIFICATION_NAMES
#define UKKQueueFileRenamedNotification				UKFileWatcherRenameNotification
#define UKKQueueFileWrittenToNotification			UKFileWatcherWriteNotification
#define UKKQueueFileDeletedNotification				UKFileWatcherDeleteNotification
#define UKKQueueFileAttributesChangedNotification   UKFileWatcherAttributeChangeNotification
#define UKKQueueFileSizeIncreasedNotification		UKFileWatcherSizeIncreaseNotification
#define UKKQueueFileLinkCountChangedNotification	UKFileWatcherLinkCountChangeNotification
#define UKKQueueFileAccessRevocationNotification	UKFileWatcherAccessRevocationNotification
#endif

// -----------------------------------------------------------------------------
//  UKKQueue:
// -----------------------------------------------------------------------------

@interface UKKQueue : NSObject <UKFileWatcher>
{
	NSInteger				queueFD;			// The actual queue ID (Unix file descriptor).
	NSMutableSet*   watchedPaths;		// List of NSStrings containing the paths we're watching.
	BOOL			keepThreadRunning;	// Termination criterion of our thread.
}

+(id)	sharedFileWatcher;      // Returns a singleton, a shared kqueue object Handy if you're subscribing to the notifications. Use this, or just create separate objects using alloc/init. Whatever floats your boat.

-(NSInteger)  queueFD;		// I know you unix geeks want this...

// High-level file watching: (use UKFileWatcher protocol methods instead, where possible!)
-(void) addPathToQueue: (NSString*)path;
-(void) addPathToQueue: (NSString*)path notifyingAbout: (u_int)fflags;
-(void) removePathFromQueue: (NSString*)path;

#if UKKQUEUE_OLD_SINGLETON_ACCESSOR_NAME
+(UKKQueue*)    sharedQueue;
#endif

// private:
-(void)		watcherThread: (id)sender;
-(void)		postNotification: (NSString*)nm forFile: (NSString*)fp; // Message-posting bottleneck.

@end

// -----------------------------------------------------------------------------
//  Methods delegates need to provide:
//      * DEPRECATED * use UKFileWatcher delegate methods instead!
// -----------------------------------------------------------------------------

@interface NSObject (UKKQueueDelegate)

-(void) kqueue: (UKKQueue*)kq receivedNotification: (NSString*)nm forFile: (NSString*)fpath;

@end


text:
Tournament Tool
===

What is it?
---

* A tournament management software for TOs - definitely for Android:Netrunner, but extendable (and will probably be extended early for X-Wing and MtG)
* An automatic pairing system for Swiss rounds and the cut to top X
* A mobile-friendly and showscreen-friendly ranking list and schedule view
* A little bit of an anonymized statistics view for TOs and interested parties

Deployment
---

The application is not prepared for deployment yet. Will probably be deployable on Heroku.

Development with Ruby, Rails
---

This application started out using Ruby 2.2 Preview 1 and Rails 4.2 Beta 1.

`.ruby-version` and `.ruby-gemset` point to reasonable values. So when you have RVM, just...

```sh
rvm install 2.2-preview1
cd <repository>
bundle install
```

...and you're ready to run with `rails s`. If you want to have IPv4 bindings (and thus be able to use QR codes locally), please use `rails s -b 0.0.0.0`.

Test Suite
---

RSpec in `/spec` and Cucumber in `/features`. Run either one with its binary, or the suite with `rake` (it's the default task).

Used Tools
---

In addition to the gems in the `Gemfile`:

* https://developer.android.com/design/style/typography.html
* http://www.fontsquirrel.com/
* https://github.com/MWDelaney/Netrunner-Icon-Font

ToDo
---

Lots of stuff - almost everything, in fact. Links:

* http://sourcey.com/rails-4-omniauth-using-devise-with-twitter-facebook-and-linkedin/ and https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
* https://github.com/zumbrunnen/betastore/commit/7fabe1e6917ecb7c05ce5df4fc212da1fc0ef087


text:
"use strict"

const assert = require("assert")
const fs = require("fs")
const validate = require("../")

assert(validate instanceof Function, "validate must be a function")

assert(validate("{}"), "empty object is valid JSON")
assert(validate("[]"), "empty array is valid JSON")
assert(validate("[1, 2, 3]"))
assert(validate('["hello", "world"]'))
assert(validate('{ "hello": "world" }'))
assert(validate('{ "hello": 4 }'))

assert.equal(validate("{ hello: 4 }", true), false, "is not valid JSON")
assert.equal(
    validate(
        fs.readFileSync(`${__dirname}/fixture/invalid.json`, "utf8"),
        true
    ),
    false,
    "is not valid JSON"
)
assert.equal(validate("lorem", true), false, "invalid JSON at position 0 must return false")


text:
import pygame
from . import *

class TitleScene(BaseScene):
    """
    You can access all items in RapidPieMovementGame by doing
    self.context.<item>
    """
    def __init__(self, context):
        BaseScene.__init__(self, context)
        self.context.screen.blit(self.context.title,(0,0))
        self.create_buttons()

    def handle_inputs(self, events):
        # Handle events
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                pos = pygame.mouse.get_pos()
                if self.start_box.collidepoint(pos):
                    self.context.set_intro()

                elif self.help_box.collidepoint(pos):
                    self.context.set_tutorial()

    def create_buttons(self):
        self.start_btn = pygame.Surface((436,104), pygame.SRCALPHA, 32)
        self.start_btn.convert_alpha()
        self.start_btn.blit(self.context.startbtn, (0,0))
        self.start_box = self.context.screen.blit(self.start_btn, (400,500))

        self.tut_btn = pygame.Surface((436,104), pygame.SRCALPHA, 32)
        self.tut_btn.convert_alpha()
        self.tut_btn.blit(self.context.howtobtn, (0,0))
        self.help_box = self.context.screen.blit(self.tut_btn, (400, 700))

    def render_scene(self):
        pygame.display.flip()


text:
package com.aotal.bitza;

//import io.prometheus.client.spring.boot.EnablePrometheusEndpoint;
//import io.prometheus.client.spring.boot.EnableSpringBootMetricsCollector;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//@EnablePrometheusEndpoint
//@EnableSpringBootMetricsCollector
public class BitzaApplication {

	public static void main(String[] args) {
		SpringApplication.run(BitzaApplication.class, args);
	}
}


text:
package by.expertsoft.contacts.classes;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import javax.servlet.ServletInputStream;

public class FileUpload {

    String fileName;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public FileUpload() {
    }

    public void fileUpload(String savePath,ServletInputStream in) throws IOException
    {
        byte[] line = new byte[128];
        int i = in.readLine(line, 0, 128);
        int boundaryLength = i - 2;
        String boundary = new String(line, 0, boundaryLength);

        while (i != -1) {

            String newLine = new String(line, 0, i);

            if (newLine.startsWith("Content-Disposition: form-data; name=\"")) {

                String s = new String(line, 0, i - 2);
                int pos = s.indexOf("filename=\"");

                if (pos != -1) {
                    String filepath = s.substring(pos + 10, s.length() - 1);
                    pos = filepath.lastIndexOf("\\");
                    if (pos != -1) {
                        this.fileName = filepath.substring(pos + 1);
                    } else {
                        this.fileName = filepath;
                    }
                }

                i = in.readLine(line, 0, 128);
                i = in.readLine(line, 0, 128);
                i = in.readLine(line, 0, 128);

                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                newLine = new String(line, 0, i);

                while (i != -1 && !newLine.startsWith(boundary)) {
                    buffer.write(line, 0, i);
                    i = in.readLine(line, 0, 128);
                    newLine = new String(line, 0, i);
                }

                try {
                    RandomAccessFile f = new RandomAccessFile(savePath + File.separator + this.fileName, "rw");
                    byte[] bytes = buffer.toByteArray();
                    f.write(bytes, 0, bytes.length - 2);
                    f.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }

            i = in.readLine(line, 0, 128);
        }
    }
}


text:
from unittest import TestCase
from app import Persona

class TestPersona(TestCase):
    def setUp(self):
        self.persona = Persona.Persona('Petra', 50)

    def test_es_mayor_edad(self):
        self.assertEqual(self.persona.es_mayor_edad(), "Mayor")


text:
using System.Runtime.Serialization;
using Umbraco.Cms.Core.Models.Entities;

namespace Umbraco.Cms.Core.Models;

/// <summary>
///     Represents a RelationType
/// </summary>
[Serializable]
[DataContract(IsReference = true)]
public class RelationType : EntityBase, IRelationTypeWithIsDependency
{
    private string _alias;
    private Guid? _childObjectType;
    private bool _isBidirectional;
    private bool _isDependency;
    private string _name;
    private Guid? _parentObjectType;

    public RelationType(string alias, string name)
        : this(name, alias, false, null, null, false)
    {
    }

        public RelationType(string? name, string? alias, bool isBidrectional, Guid? parentObjectType, Guid? childObjectType, bool isDependency){
        if (name == null)
        {
            throw new ArgumentNullException(nameof(name));
        }

        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException(
                "Value can't be empty or consist only of white-space characters.",
                nameof(name));
        }

        if (alias == null)
        {
            throw new ArgumentNullException(nameof(alias));
        }

        if (string.IsNullOrWhiteSpace(alias))
        {
            throw new ArgumentException(
                "Value can't be empty or consist only of white-space characters.",
                nameof(alias));
        }

        _name = name;
        _alias = alias;
        _isBidirectional = isBidrectional;
        _isDependency = isDependency;
        _parentObjectType = parentObjectType;
        _childObjectType = childObjectType;
    }

    /// <summary>
    ///     Gets or sets the Name of the RelationType
    /// </summary>
    [DataMember]
    public string? Name
    {
        get => _name;
        set => SetPropertyValueAndDetectChanges(value, ref _name!, nameof(Name));
    }

    /// <summary>
    ///     Gets or sets the Alias of the RelationType
    /// </summary>
    [DataMember]
    public string Alias
    {
        get => _alias;
        set => SetPropertyValueAndDetectChanges(value, ref _alias!, nameof(Alias));
    }

    /// <summary>
    ///     Gets or sets a boolean indicating whether the RelationType is Bidirectional (true) or Parent to Child (false)
    /// </summary>
    [DataMember]
    public bool IsBidirectional
    {
        get => _isBidirectional;
        set => SetPropertyValueAndDetectChanges(value, ref _isBidirectional, nameof(IsBidirectional));
    }

    /// <summary>
    ///     Gets or sets the Parents object type id
    /// </summary>
    /// <remarks>Corresponds to the NodeObjectType in the umbracoNode table</remarks>
    [DataMember]
    public Guid? ParentObjectType
    {
        get => _parentObjectType;
        set => SetPropertyValueAndDetectChanges(value, ref _parentObjectType, nameof(ParentObjectType));
    }

    /// <summary>
    ///     Gets or sets the Childs object type id
    /// </summary>
    /// <remarks>Corresponds to the NodeObjectType in the umbracoNode table</remarks>
    [DataMember]
    public Guid? ChildObjectType
    {
        get => _childObjectType;
        set => SetPropertyValueAndDetectChanges(value, ref _childObjectType, nameof(ChildObjectType));
    }

    public bool IsDependency
    {
        get => _isDependency;
        set => SetPropertyValueAndDetectChanges(value, ref _isDependency, nameof(IsDependency));
    }
}


text:
package controlP5;

/**
 * controlP5 is a processing gui library.
 *
 *  2007-2010 by Andreas Schlegel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA
 *
 * @author 		Andreas Schlegel (http://www.sojamo.de)
 * @modified	10/05/2010
 * @version		0.5.4
 *
 */

import processing.core.PApplet;
import java.awt.event.WindowEvent;
import java.awt.Frame;
import java.awt.Color;
import java.awt.event.WindowListener;
import java.awt.Insets;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.Component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;

/**
 * PAppletWIndow description.
 *
 *
 */

public class PAppletWindow extends PApplet implements WindowListener, ComponentListener {

	/**
	 *
	 */
	private static final long serialVersionUID = -1773456691122668251L;

	protected int width = 600;

	protected int height = 200;

	protected int x = 100;

	protected int y = 100;

	protected String _myName;

	protected String _myTitle;

	protected boolean isCoordinates = true;

	protected boolean isLoop = true;

	protected ControlWindow controlWindow;

	protected ControlP5 controlP5;

	public final static int NORMAL = 0;

	public final static int ECONOMIC = 1;

	protected int _myMode = NORMAL;

	protected String _myRenderer = "";

	protected int _myFrameRate = 15;

	/*
	 * (non-Javadoc)
	 */
	public PAppletWindow() {
		super();
	}

	/*
	 * (non-Javadoc)
	 */
	public PAppletWindow(final String theName, final int theWidth, final int theHeight) {
		this(theName, theWidth, theHeight, "", 15);
	}

	/*
	 * (non-Javadoc)
	 */
	public PAppletWindow(
			final String theName,
			final int theWidth,
			final int theHeight,
			final String theRenderer,
			final int theFrameRate) {
		super();
		_myName = theName;
		_myTitle = theName;
		width = theWidth;
		height = theHeight;
		_myFrameRate = theFrameRate;
		_myRenderer = theRenderer;
		launch();
	}

	/*
	 * (non-Javadoc)
	 */
	public PAppletWindow(final String theName, final int theX, final int theY, final int theWidth, final int theHeight) {
		this(theName, theX, theY, theWidth, theHeight, "", 15);
	}

	/*
	 * (non-Javadoc)
	 */
	public PAppletWindow(
			final String theName,
			final int theX,
			final int theY,
			final int theWidth,
			final int theHeight,
			final String theRenderer,
			final int theFrameRate) {
		super();
		_myName = theName;
		_myTitle = theName;
		width = theWidth;
		height = theHeight;
		x = theX;
		y = theY;
		_myFrameRate = theFrameRate;
		_myRenderer = theRenderer;
		launch();
	}

	/*
	 * (non-Javadoc)
	 */
	public void setParent(ControlP5 theControlP5) {
		controlP5 = theControlP5;
	}

	/*
	 * (non-Javadoc)
	 */
	public void pause() {
		controlWindow.isAutoDraw = false;
	}

	/*
	 * (non-Javadoc)
	 */
	public void play() {
		controlWindow.isAutoDraw = true;
	}

	/*
	 * (non-Javadoc)
	 */
	public String name() {
		return _myName;
	}

	/**
	 * show/hide the controller window.
	 *
	 * @param theValue
	 *          boolean
	 */
	protected void visible(boolean theValue) {
		// frame.setVisible(theValue);
		// frame.pack();
		if (theValue == true) {
			frame.show();
		} else {
			frame.hide();
		}
	}

	/**
	 * resize controller window.
	 *
	 * @param theValue
	 *          boolean
	 */
	protected void resizeable(boolean theValue) {
		frame.setResizable(theValue);
	}

	/*
	 * (non-Javadoc)
	 */
	public void setup() {
		try {
			Thread.sleep(100);
		} catch (Exception e) {
		}
		if (_myRenderer.length() == 0) {
			size(width, height);
		} else {
			size(width, height, _myRenderer);
			ControlP5.logger().finer("ControlWindow: using renderer " + _myRenderer);
		}
		try {
			Thread.sleep(100);
		} catch (Exception e) {

		}
		/*
		 * method framrate is called frameRate from processing version 0117 on.
		 * therefore check for backwards compatibility.
		 */
		String myFramerate = "frameRate";
		Method[] myMethods = this.getClass().getMethods();
		for (int i = 0; i < myMethods.length; i++) {
			if (myMethods[i].getName().toLowerCase().equals("framerate")) {
				myFramerate = myMethods[i].getName();
				break;
			}
		}

		try {
			Method m = this.getClass().getMethod(myFramerate, new Class[] { float.class });
			m.invoke(this, new Object[] { new Float(_myFrameRate) });
		} catch (NoSuchMethodException e) {
		} catch (IllegalAccessException e) {
		} catch (InvocationTargetException e) {
		}
	}

	protected void setControlWindow(ControlWindow theWindow) {
		controlWindow = theWindow;
	}

	@Override
	public void draw() {
	}

	public void setTitle(String theTitle) {
		_myTitle = theTitle;
		updateTitle();
	}

	protected void updateTitle() {
		String m = _myTitle;
		if (isCoordinates) {
			m += " x:" + x + " y:" + y + "   " + width + "x" + height;
		}
		frame.setTitle(m);
	}

	public String title() {
		return _myTitle;
	}

	public void showCoordinates() {
		isCoordinates = true;
		updateTitle();
	}

	public void hideCoordinates() {
		isCoordinates = false;
		updateTitle();
	}

	/*
	 * (non-Javadoc)
	 */
	public void windowActivated(WindowEvent e) {
		isLoop = true;
		loop();
		try {
			controlP5.deactivateControllers();
		} catch (NullPointerException nullPointer) {
		}
	}

	/*
	 * (non-Javadoc)
	 */
	public void keyPressed(KeyEvent theKeyEvent) {
		ControlP5.papplet.keyPressed(theKeyEvent);
		ControlP5.keyHandler.keyEvent(theKeyEvent, this.controlWindow, false);
	}

	/*
	 * (non-Javadoc)
	 */
	public void keyReleased(KeyEvent theKeyEvent) {
		ControlP5.papplet.keyReleased(theKeyEvent);
		ControlP5.keyHandler.keyEvent(theKeyEvent, this.controlWindow, false);
	}

	/*
	 * (non-Javadoc)
	 */
	public void keyTyped(KeyEvent theKeyEvent) {
		ControlP5.papplet.keyTyped(theKeyEvent);
		ControlP5.keyHandler.keyEvent(theKeyEvent, this.controlWindow, false);
	}

	/*
	 * (non-Javadoc)
	 */
	public void windowClosed(WindowEvent e) {
	}

	/*
	 * (non-Javadoc)
	 */
	public void windowClosing(WindowEvent e) {
		controlWindow.remove();
		controlWindow._myApplet.stop();
		dispose();
	}

	/*
	 * (non-Javadoc)
	 */
	public void windowDeactivated(WindowEvent e) {
		if (_myMode == ECONOMIC) {
			isLoop = false;
			noLoop();
		}
	}

	/*
	 * (non-Javadoc)
	 */
	public void windowDeiconified(WindowEvent e) {
	}

	/*
	 * (non-Javadoc)
	 */
	public void windowIconified(WindowEvent e) {
	}

	/*
	 * (non-Javadoc)
	 */
	public void windowOpened(WindowEvent e) {
	}

	/*
	 * (non-Javadoc)
	 */
	public void componentHidden(ComponentEvent e) {
	}

	/*
	 * (non-Javadoc)
	 */
	public void componentMoved(ComponentEvent e) {
		Component c = e.getComponent();
		x = c.getLocation().x;
		y = c.getLocation().y;
		updateTitle();
	}

	/*
	 * (non-Javadoc)
	 */
	public void componentResized(ComponentEvent e) {
		Component c = e.getComponent();
		// System.out.println("componentResized event from " +
		// c.getClass().getName() + "; new size: " + c.getSize().width
		// + ", " + c.getSize().height);
	}

	/*
	 * (non-Javadoc)
	 */
	public void componentShown(ComponentEvent e) {
		// System.out.println("componentShown event from " +
		// e.getComponent().getClass().getName());
	}

	/**
	 * set the rendering mode of the PAppletWindow which can either be
	 * ControlP5.ECONOMIC or ControlP5.NORMAL.
	 *
	 */
	public void setMode(int theValue) {
		if (theValue == ECONOMIC) {
			_myMode = ECONOMIC;
			return;
		}
		_myMode = NORMAL;
	}

	protected void dispose() {
		controlWindow._myApplet.stop();
		stop();
		removeAll();
		frame.removeAll();
		frame.dispose();
	}

	private void launch() {
		GraphicsDevice displayDevice = null;
		if (displayDevice == null) {
			GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
			displayDevice = environment.getDefaultScreenDevice();
		}

		frame = new Frame(displayDevice.getDefaultConfiguration());

		// remove the grow box by default
		// users who want it back can call frame.setResizable(true)
		frame.setResizable(false);
		init();

		frame.pack(); // get insets. get more.
		frame.setLocation(x, y);

		Insets insets = frame.getInsets();

		int windowW = Math.max(width, MIN_WINDOW_WIDTH) + insets.left + insets.right;
		int windowH = Math.max(height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom;

		frame.setSize(windowW, windowH);
		frame.setLayout(null);
		frame.add(this);
		frame.setBackground(Color.black);
		int usableWindowH = windowH - insets.top - insets.bottom;
		setBounds((windowW - width) / 2, insets.top + (usableWindowH - height) / 2, width, height);

		frame.addWindowListener(this);
		frame.addComponentListener(this);
		frame.setName(_myName);
		frame.setTitle(_myName + " x:" + x + " y:" + y + "   w:" + width + " h:" + height);
		frame.setVisible(true);
		requestFocus();
	}

}


text:
<?php
/**
 * Test for net::stubbles::console::stubConsoleOutputStream.
 *
 * @package     stubbles
 * @subpackage  console_test
 * @version     $Id: stubConsoleOutputStreamTestCase.php 2857 2011-01-10 13:43:39Z mikey $
 */
stubClassLoader::load('net::stubbles::console::stubConsoleOutputStream');
/**
 * Test for net::stubbles::console::stubConsoleOutputStream.
 *
 * @package     stubbles
 * @subpackage  console_test
 * @group       console
 */
class stubConsoleOutputStreamTestCase extends PHPUnit_Framework_TestCase
{
    /**
     * console output stream is always the same instance
     *
     * @test
     */
    public function sameOutInstance()
    {
        $out1 = stubConsoleOutputStream::forOut();
        $out2 = stubConsoleOutputStream::forOut();
        $this->assertSame($out1, $out2);
    }

    /**
     * console error stream is always the same instance
     *
     * @test
     */
    public function sameErrInstance()
    {
        $err1 = stubConsoleOutputStream::forError();
        $err2 = stubConsoleOutputStream::forError();
        $this->assertSame($err1, $err2);
    }
}
?>


text:
[Readme](https://github.com/pvolyntsev/diglot/blob/master/README.md)

####Минимальные требования####
- PHP 5.5+
- MySQL 5.0+
- [Composer](https://getcomposer.org/download/)
- php5-curl
- Java
- [ElasticSearch](https://github.com/elastic/elasticsearch/blob/master/README.textile)

##### Установить Elastic Search v 2.3.3 #####
```
wget https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/deb/elasticsearch/2.3.3/elasticsearch-2.3.3.deb -O /tmp/elasticsearch-2.3.3.deb
sudo dpkg -I /tmp/elasticsearch-2.3.3.deb
```

Настроить файл конфигурации, установить host 127.0.0.1 и порт 9200
```
nano /etc/elasticsearch/elasticsearch.yaml
```

##### Установить плагин русской морфологии для Elastic Search #####
Описание https://github.com/imotov/elasticsearch-analysis-morphology

Для Elastic Search v2.3.3 для Ubuntu
```
cd /usr/share/elasticsearch
sudo bin/plugin install http://dl.bintray.com/content/imotov/elasticsearch-plugins/org/elasticsearch/elasticsearch-analysis-morphology/2.3.3/elasticsearch-analysis-morphology-2.3.3.zip
sudo service elasticsearch restart
```

Настроить морфологию

```
curl -XDELETE 'http://localhost:9200/diglot' && echo
curl -XPUT 'http://localhost:9200/diglot' -d '{
    "settings": {
        "analysis": {
            "analyzer": {
                "my_analyzer": {
                    "type": "custom",
                    "tokenizer": "standard",
                    "filter": ["lowercase", "russian_morphology", "english_morphology", "my_stopwords"]
                }
            },
            "filter": {
                "my_stopwords": {
                    "type": "stop",
                    "stopwords": "а,без,более,бы,был,была,были,было,быть,в,вам,вас,весь,во,вот,все,всего,всех,вы,где,да,даже,для,до,его,ее,если,есть,еще,же,за,здесь,и,из,или,им,их,к,как,ко,когда,кто,ли,либо,мне,может,мы,на,надо,наш,не,него,нее,нет,ни,них,но,ну,о,об,однако,он,она,они,оно,от,очень,по,под,при,с,со,так,также,такой,там,те,тем,то,того,тоже,той,только,том,ты,у,уже,хотя,чего,чей,чем,что,чтобы,чье,чья,эта,эти,это,я,a,an,and,are,as,at,be,but,by,for,if,in,into,is,it,no,not,of,on,or,such,that,the,their,then,there,these,they,this,to,was,will,with"
                }
            }
        }
    }
}' && echo
curl -XPUT 'http://localhost:9200/diglot/type1/_mapping' -d '{
    "type1": {
        "_all" : {"analyzer" : "russian_morphology"},
        "properties" : {
            "title_translate" : { "type" : "string", "analyzer" : "russian_morphology" },
            "title_original" : { "type" : "string", "analyzer" : "russian_morphology" }
        }
    }
}' && echo
```

####Скопировать репозиторий####
```
cd /var/www
git clone https://github.com/pvolyntsev/diglot.git
cd diglot
composer global require "fxp/composer-asset-plugin:~1.1.4"
composer update
```

#### Создание БД ####
```
DROP DATABASE IF EXISTS `diglot`;
CREATE DATABASE IF NOT EXISTS `diglot` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
GRANT ALL PRIVILEGES ON diglot.* TO diglot_rw@localhost IDENTIFIED BY '123456';
```

#### Миграция таблиц ####
```
cd /var/www/diglot
php yii migrate/up --migrationPath=@vendor/budyaga/yii2-users/migrations
php yii migrate/up
```

#### Настройка CRON для импорта github ####
Открыть настройку заданий cron
```
crontab -e
```
Указать путь к проекту в своей структуре и необходимое время выполнения задачи
```
*/3 * * * * php /home/nikolay/projects/mentor/diglot/yii article/git
```


text:
//
//  JsonResouceRequest.h
//  xImage
//
//  Created by rockee on 13-5-21.
//
//

#import <Foundation/Foundation.h>

@interface JsonResouceRequest : NSObject
/*
 request: http url request for resource
 localPath: save web resource to local
 response: when received data, extract json data to load resource urls, it must not be nil.
 comletion: when it completed, tell caller result.
*/
+(void) jsonResouceRequest:(NSURLRequest*)request toLocal:(NSString*) localPath overwrite:(BOOL) overwrite response:(NSArray *(^)(NSURLResponse *urlResponse, NSData *responseData, NSError *err))response completion:(void(^)(BOOL done))completion;
+(NSArray*) jsonResouceLoad:(NSArray *)urls local:(NSString*) localPath handler:(id (^)(NSData* data)) handler;
@end


text:
import unittest
import paddle.fluid as fluid
import importlib

fluid.core._set_eager_deletion_mode(0.0, 1.0, True)

from test_bilinear_interp_op import *
from test_concat_op import *
from test_elementwise_add_op import *
from test_elementwise_sub_op import *
from test_fill_constant_batch_size_like_op import *
from test_fill_zeros_like2_op import *
from test_gather_op import *
from test_gaussian_random_batch_size_like_op import *
from test_linear_chain_crf_op import *
from test_lod_reset_op import *
from test_lookup_table_op import *
from test_mean_op import *
from test_nearest_interp_op import *
from test_pad2d_op import *
from test_scatter_op import *
from test_sequence_concat import *
from test_seq_conv import *
from test_seq_pool import *
from test_sequence_expand_as import *
from test_sequence_expand import *
from test_sequence_pad_op import *
from test_sequence_unpad_op import *
from test_sequence_scatter_op import *
from test_sequence_slice_op import *
from test_slice_op import *
from test_space_to_depth_op import *
from test_squared_l2_distance_op import *
from test_uniform_random_batch_size_like_op import *

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