code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
#include "ofxCv/Helpers.h"
#include "ofxCv/Utilities.h"
namespace ofxCv {
using namespace cv;
ofMatrix4x4 makeMatrix(Mat rotation, Mat translation) {
Mat rot3x3;
if(rotation.rows == 3 && rotation.cols == 3) {
rot3x3 = rotation;
} else {
Rodrigues(rotation, rot3x3);
}
double* rm = rot3x3.ptr<double>(0);
double* tm = translation.ptr<double>(0);
return ofMatrix4x4(rm[0], rm[3], rm[6], 0.0f,
rm[1], rm[4], rm[7], 0.0f,
rm[2], rm[5], rm[8], 0.0f,
tm[0], tm[1], tm[2], 1.0f);
}
void drawMat(Mat& mat, float x, float y) {
drawMat(mat, x, y, mat.cols, mat.rows);
}
// experimental special case of copying into ofTexture, which acts different
// might be able to rewrite this in terms of getDepth() but right now this
// function loses precision with CV_32F -> CV_8U
template <class S>
void copy(S& src, ofTexture& tex) {
Mat mat = toCv(src);
int glType;
Mat buffer;
if(mat.depth() != CV_8U) {
copy(mat, buffer, CV_8U);
} else {
buffer = mat;
}
if(mat.channels() == 1) {
glType = GL_LUMINANCE;
} else {
glType = GL_RGB;
}
int w = buffer.cols;
int h = buffer.rows;
tex.allocate(w, h, glType);
tex.loadData(buffer.ptr(), w, h, glType);
}
void drawMat(Mat& mat, float x, float y, float width, float height) {
if(mat.empty()) {
return;
}
ofTexture tex;
copy(mat, tex);
tex.draw(x, y, width, height);
}
void applyMatrix(const ofMatrix4x4& matrix) {
glMultMatrixf((GLfloat*) matrix.getPtr());
}
int forceOdd(int x) {
return (x / 2) * 2 + 1;
}
int findFirst(const Mat& arr, unsigned char target) {
for(unsigned int i = 0; i < arr.rows; i++) {
if(arr.at<unsigned char>(i) == target) {
return i;
}
}
return 0;
}
int findLast(const Mat& arr, unsigned char target) {
for(unsigned int i = arr.rows - 1; i >= 0; i--) {
if(arr.at<unsigned char>(i) == target) {
return i;
}
}
return 0;
}
float weightedAverageAngle(const vector<Vec4i>& lines) {
float angleSum = 0;
ofVec2f start, end;
float weights = 0;
for(unsigned int i = 0; i < lines.size(); i++) {
start.set(lines[i][0], lines[i][1]);
end.set(lines[i][2], lines[i][3]);
ofVec2f diff = end - start;
float length = diff.length();
float weight = length * length;
float angle = atan2f(diff.y, diff.x);
angleSum += angle * weight;
weights += weight;
}
return angleSum / weights;
}
vector<cv::Point2f> getConvexPolygon(const vector<cv::Point2f>& convexHull, int targetPoints) {
vector<cv::Point2f> result = convexHull;
static const unsigned int maxIterations = 16;
static const double infinity = numeric_limits<double>::infinity();
double minEpsilon = 0;
double maxEpsilon = infinity;
double curEpsilon = 16; // good initial guess
// unbounded binary search to simplify the convex hull until it's targetPoints
if(result.size() > (unsigned int) targetPoints) {
for(unsigned int i = 0; i < maxIterations; i++) {
approxPolyDP(Mat(convexHull), result, curEpsilon, true);
if(result.size() == targetPoints) {
break;
}
if(result.size() > targetPoints) {
minEpsilon = curEpsilon;
if(maxEpsilon == infinity) {
curEpsilon = curEpsilon * 2;
} else {
curEpsilon = (maxEpsilon + minEpsilon) / 2;
}
}
if(result.size() < targetPoints) {
maxEpsilon = curEpsilon;
curEpsilon = (maxEpsilon + minEpsilon) / 2;
}
}
}
return result;
}
void drawHighlightString(string text, ofPoint position, ofColor background, ofColor foreground) {
drawHighlightString(text, position.x, position.y, background, foreground);
}
void drawHighlightString(string text, int x, int y, ofColor background, ofColor foreground) {
vector<string> lines = ofSplitString(text, "\n");
int textLength = 0;
for(unsigned int i = 0; i < lines.size(); i++) {
// tabs are not rendered
int tabs = count(lines[i].begin(), lines[i].end(), '\t');
int curLength = lines[i].length() - tabs;
// after the first line, everything is indented with one space
if(i > 0) {
curLength++;
}
if(curLength > textLength) {
textLength = curLength;
}
}
int padding = 4;
int fontSize = 8;
float leading = 1.7;
int height = lines.size() * fontSize * leading - 1;
int width = textLength * fontSize;
#ifdef TARGET_OPENGLES
// This needs to be refactored to support OpenGLES
// Else it will work correctly
#else
glPushAttrib(GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
ofPushStyle();
ofSetColor(background);
ofFill();
ofRect(x, y, width + 2 * padding, height + 2 * padding);
ofSetColor(foreground);
ofNoFill();
ofPushMatrix();
ofTranslate(padding, padding);
ofDrawBitmapString(text, x + 1, y + fontSize + 2);
ofPopMatrix();
ofPopStyle();
glPopAttrib();
#endif
}
} | cran-io/ofxCv | libs/ofxCv/src/Helpers.cpp | C++ | mit | 4,884 |
<?php
namespace elinoix\shopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Client
*
* @ORM\Table(name="Client")
* @ORM\Entity
*/
class Client
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* @var string
*
* @ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* @var string
*
* @ORM\Column(name="adresse", type="string", length=255)
*/
private $adresse;
/**
* @var integer
*
* @ORM\Column(name="codePostal", type="integer")
*/
private $codePostal;
/**
* @var string
*
* @ORM\Column(name="ville", type="string", length=255)
*/
private $ville;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* @var \elinoix\shopBundle\Entity\Organisation
*
* @ORM\ManyToOne(targetEntity="elinoix\shopBundle\Entity\Organisation", inversedBy="features")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="organisation", referencedColumnName="id")
* })
*/
private $organisation;
/**
* @ORM\OneToMany(targetEntity="Commande", mappedBy="client")
*/
protected $commandes;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* @param string $nom
* @return Client
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* @param string $prenom
* @return Client
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* @return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set adresse
*
* @param string $adresse
* @return Client
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* @return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set codePostal
*
* @param integer $codePostal
* @return Client
*/
public function setCodePostal($codePostal)
{
$this->codePostal = $codePostal;
return $this;
}
/**
* Get codePostal
*
* @return integer
*/
public function getCodePostal()
{
return $this->codePostal;
}
/**
* Set ville
*
* @param string $ville
* @return Client
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* @return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set email
*
* @param string $email
* @return Client
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set organisation
*
* @param \elinoix\shopBundle\Entity\Organisation $organisation
* @return Client
*/
public function setOrganisation(\elinoix\shopBundle\Entity\Organisation $organisation = null)
{
$this->organisation = $organisation;
return $this;
}
/**
* Get organisation
*
* @return \elinoix\shopBundle\Entity\Organisation
*/
public function getOrganisation()
{
return $this->organisation;
}
/**
* Constructor
*/
public function __construct()
{
$this->commandes = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add commandes
*
* @param \elinoix\shopBundle\Entity\Commande $commandes
* @return Client
*/
public function addCommande(\elinoix\shopBundle\Entity\Commande $commandes)
{
$this->commandes[] = $commandes;
return $this;
}
/**
* Remove commandes
*
* @param \elinoix\shopBundle\Entity\Commande $commandes
*/
public function removeCommande(\elinoix\shopBundle\Entity\Commande $commandes)
{
$this->commandes->removeElement($commandes);
}
/**
* Get commandes
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCommandes()
{
return $this->commandes;
}
public function __toString() {
return $this->nom . ' ' . $this->prenom;
}
}
| risq/sf | src/elinoix/shopBundle/Entity/Client.php | PHP | mit | 5,142 |
<?php
namespace User\Form;
class User extends \Zend\Form\Form
{
/**
* @var \User\Model\User
*/
protected $userModel;
/**
*
* @param \User\Model\User $userModel
* @param array $options
*/
public function __construct(\User\Model\User $userModel, array $options = []) {
$defaults = [
'method' => 'post'
];
$this->userModel = $userModel;
$formOptions = array_replace_recursive($defaults, $options);
parent::__construct('user-form', $formOptions);
}
/**
*
*/
protected function createBaseForm() {
$inputFilter = $this->userModel->getInputFilter();
$fieldsDefinitions = $this->userModel->getFieldsDefinitions();
$this->setInputFilter($this->userModel->getInputFilter());
$this->bind($this->userModel);
foreach ($this->getInputFilter()->getInputs() as $input) {
$fieldName = $input->getName();
$fieldDefinition = $fieldsDefinitions[$fieldName];
//var_dump($fieldsDefinitions[$fieldName]);
$element = null;
switch (strtolower($fieldDefinition['type'])) {
case 'text':
$element = new \Zend\Form\Element\Text($fieldName);
break;
case 'select':
$element = new \Zend\Form\Element\Select($fieldName);
break;
case 'hidden':
default:
$element = new \Zend\Form\Element\Hidden($fieldName);
break;
// ...
}
$fieldId = isset($fieldDefinition['options']['id'])
? $fieldDefinition['options']['id']
: 'field-' . $fieldName;
$fieldClass = isset($fieldDefinition['options']['class'])
? $fieldDefinition['options']['class']
: 'formularz';
$fieldOptions = array_replace_recursive([
'column-size' => 'xs-9'
], $fieldDefinition['options']);
// walidacja
$validators = $input->getValidatorChain()->getValidators();
$data = isset($fieldDefinition['options']['data'])
? $fieldDefinition['options']['data']
: [];
foreach ($validators as $validator) {
$validatorObject = $validator['instance'];
switch (get_class($validatorObject)) {
case 'Zend\Validator\StringLength':
$messages = $validatorObject->getMessageTemplates();
$data['data-strlen-min'] = $validatorObject->getMin();
$data['data-strlen-max'] = $validatorObject->getMax();
$data['data-strlen-message-invalid'] = $messages['stringLengthInvalid'];
$data['data-strlen-message-too-short'] = $messages['stringLengthTooShort'];
$data['data-strlen-message-too-long'] = $messages['stringLengthTooLong'];
if (0 < $validatorObject->getMax()) {
$element->setAttributes([
'maxlength' => $validatorObject->getMax()
]);
}
break;
case 'Zend\Validator\Regex':
$messages = $validatorObject->getMessageTemplates();
$pattern = trim($validatorObject->getPattern(), '/');
$element->setAttributes([
'pattern' => $pattern
]);
$data['data-regex-pattern'] = $pattern;
$data['data-regex-message'] = $messages['regexNotMatch'];
break;
}
}
$element
->setAttributes(array_merge([
'class' => $fieldClass,
'id' => $fieldId,
], $data))
->setLabel($fieldDefinition['label'])
->setLabelAttributes([
'class' => 'col-xs-3',
'for' => $fieldId,
])
->setOptions($fieldOptions);
$this->add($element);
}
// uzupełniamy select opcjami - tablica klucz => wartość
$this->get('userStatus')->setValueOptions([
'active' => 'Aktywny',
'inactive' => 'Nieaktywny',
'deleted' => 'Usunięty',
'suspended' => 'Zawieszony',
]);
$saveButton = new \Zend\Form\Element\Submit('save');
$saveButton
->setLabel('Akcje')
->setValue('Zapisz')
->setAttributes([
'class' => 'btn btn-primary'
])
->setLabelAttributes([
'class' => 'col-xs-3',
'for' => 'field-userName',
])
->setOptions([
'column-size' => 'xs-9'
]);
$this->add($saveButton);
/*
można "ręcznie", każde pole osobno:
$userNameField = new \Zend\Form\Element\Text('userName');
$userNameField
->setAttributes([
'class' => '',
'id' => 'field-userName'
])
->setLabel('Imię użytkownika')
->setLabelAttributes([
'class' => 'col-xs-3',
'for' => 'field-userName',
])
->setOptions([
'column-size' => 'xs-9'
]);
$userSurnameField = new \Zend\Form\Element\Text('userSurname');
$userSurnameField
->setAttributes([
'class' => '',
'id' => 'field-userSurname'
])
->setLabel('Nazwisko użytkownika')
->setLabelAttributes([
'class' => 'col-xs-3',
'for' => 'field-userSurname',
])
->setOptions([
'column-size' => 'xs-9'
]);
*/
return $this;
}
/**
* formularz do tworzenia użytkownika
*/
public function asCreateForm() {
$this
->createBaseForm();
$this->get('save')
->setValue('Dodaj użytkownika');
return $this;
}
/**
* formularz do edycji użytkownika
*/
public function asEditForm() {
$this
->createBaseForm()
->populateValues($this->userModel);
return $this;
}
} | mzieba/zpp-zf2-crud | module/User/src/User/Form/User.php | PHP | mit | 6,834 |
param = dict(
useAIon=True,
verbose=False,
chargePreXlinkIons=[1, 3],
chargePostXlinkIons=[2, 5],
basepeakint = 100.0,
dynamicrange = 0.001,
missedsites = 2,
minlength = 4,
maxlength = 51,
modRes = '',
modMass = 0.0,
linkermass = 136.10005,
ms1tol = dict(measure='ppm', val=5),
ms2tol = dict(measure='da', val=0.01),
minmz = 200,
maxmz = 2000,
mode = 'conservative',
patternstring = '^[ACDEFGHIKLMNPQRSTVWY]*K[ACDEFGHIKLMNPQRSTVWY]+$',
fixedMod = [],
neutralloss=dict(
h2oLoss=dict(
mass=-18.010565,
aa=set('ACDEFGHIKLMNPQRSTVWY')),
nh3Loss=dict(
mass=-17.026549,
aa=set('ACDEFGHIKLMNPQRSTVWY')),
h2oGain=dict(
mass=18.010565,
aa=set('ACDEFGHIKLMNPQRSTVWY'))))
mass = dict(
A=71.037114,
R=156.101111,
N=114.042927,
D=115.026943,
C=103.009184,
E=129.042593,
Q=128.058578,
G=57.021464,
H=137.058912,
I=113.084064,
L=113.084064,
K=128.094963,
M=131.040485,
F=147.068414,
P=97.052764,
S=87.032028,
T=101.047678,
W=186.079313,
Y=163.063329,
V=99.068414,
Hatom=1.007825032,
Oatom=15.99491462,
neutronmass = 1.008701,
BIonRes=1.0078246,
AIonRes=-26.9870904,
YIonRes=19.0183888,
isotopeInc = [1.008701/4, 1.008701/3, 1.008701/2, 1.008701/1])
modification = dict(
position=[],
deltaMass=[])
for i in range(len(param['fixedMod'])):
aa = param['fixedMod'][i][0]
delta = param['fixedMod'][i][1]
mass[aa] += delta
| COL-IU/XLSearch | library/Parameter.py | Python | mit | 1,380 |
Notify = function(text, callback, close_callback, style) {
var time = '10000';
var $container = $('#notifications');
var icon = '<i class="fa fa-info-circle "></i>';
if (typeof style == 'undefined' ) style = 'warning'
var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>');
$('<a>',{
text: '×',
class: 'close',
style: 'padding-left: 10px;',
href: '#',
click: function(e){
e.preventDefault()
close_callback && close_callback()
remove_notice()
}
}).prependTo(html)
$container.prepend(html)
html.removeClass('hide').hide().fadeIn('slow')
function remove_notice() {
html.stop().fadeOut('slow').remove()
}
var timer = setInterval(remove_notice, time);
$(html).hover(function(){
clearInterval(timer);
}, function(){
timer = setInterval(remove_notice, time);
});
html.on('click', function () {
clearInterval(timer)
callback && callback()
remove_notice()
});
}
| nil1990/earth_nine_ecomm | assets/js/notify.js | JavaScript | mit | 966 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using QrF.Core.Admin.Dto;
using QrF.Core.Admin.Interfaces;
using Microsoft.AspNetCore.Hosting;
namespace QrF.Core.Admin.Controllers
{
/// <summary>
/// 用户管理
/// </summary>
[Route("AdminAPI/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserBusiness _business;
private readonly IHostingEnvironment _env;
public UserController(IUserBusiness business, IHostingEnvironment env)
{
_business = business;
_env = env ?? throw new ArgumentNullException(nameof(env));
}
/// <summary>
/// 查询分页列表
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpGet("GetPageList")]
public async Task<BasePageQueryOutput<QueryUserDto>> GetPageListAsync([FromQuery] QueryUsersInput input)
{
return await _business.GetPageList(input);
}
/// <summary>
/// 编辑用户信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost("Edit")]
public async Task<IActionResult> EditAsync([FromBody] UserDto input)
{
await _business.EditModel(input);
return Ok(new MsgResultDto { Success = true });
}
/// <summary>
/// 删除
/// </summary>
/// <returns></returns>
[HttpPost("Delete")]
public async Task<IActionResult> DeleteAsync([FromBody] DelInput input)
{
if (input == null || !input.KeyId.HasValue) throw new Exception("编号不存在");
await _business.DelModel(input.KeyId.Value);
return Ok(new MsgResultDto { Success = true });
}
[HttpPost("Upload")]
public async Task<IActionResult> Upload()
{
if (Request.Form.Files.Count < 1)
return Ok(false);
string fileName = Path.GetFileName(Request.Form.Files[0].FileName);
string extension = Path.GetExtension(fileName).ToLower();
var newName = $"{Guid.NewGuid().ToString("N")}{extension}";
var url = await SaveFileAsync(Request.Form.Files[0].OpenReadStream(), GenerateDictionary(), newName);
return Ok(new { Title = fileName, Url = Url.Content(url) });
}
private async Task<string> SaveFileAsync(Stream stream, string directory, string fileName)
{
string filePath = Path.Combine(MapPath(directory), fileName);
DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(filePath));
if (!dir.Exists)
{
dir.Create();
}
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
await stream.CopyToAsync(fileStream);
}
string webPath = string.Join("/", directory.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries));
return $"~/{webPath}/{fileName}";
}
private string GenerateDictionary()
{
return Path.Combine("Files");
}
private string MapPath(string path)
{
var dic = Path.Combine(path.TrimStart('~').Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries));
return Path.Combine(_env.WebRootPath, dic);
}
}
}
| ren8179/QrF.Core | src/apis/QrF.Core.Admin/Controllers/UserController.cs | C# | mit | 3,707 |
<?php
/**
* This class adds structure of 'pp_faq' table to 'propel' DatabaseMap object.
*
*
* This class was autogenerated by Propel 1.3.0-dev on:
*
* Mon Aug 9 02:03:44 2010
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package lib.model.map
*/
class FaqMapBuilder implements MapBuilder {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'lib.model.map.FaqMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap(FaqPeer::DATABASE_NAME);
$tMap = $this->dbMap->addTable(FaqPeer::TABLE_NAME);
$tMap->setPhpName('Faq');
$tMap->setClassname('Faq');
$tMap->setUseIdGenerator(true);
$tMap->addForeignKey('META_ID', 'MetaId', 'INTEGER', 'pp_meta', 'ID', false, null);
$tMap->addColumn('QUESTION', 'Question', 'VARCHAR', false, 1000);
$tMap->addColumn('ANSWER', 'Answer', 'VARCHAR', false, 1000);
$tMap->addColumn('ORD', 'Ord', 'VARCHAR', false, 255);
$tMap->addColumn('IS_ACTIVE', 'IsActive', 'BOOLEAN', true, null);
$tMap->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null);
$tMap->addPrimaryKey('ID', 'Id', 'INTEGER', true, null);
} // doBuild()
} // FaqMapBuilder
| serg-smirnoff/symfony-pposter | symfony/lib/model/map/FaqMapBuilder.php | PHP | mit | 2,043 |
import React from 'react';
import Link from 'gatsby-link';
import { BlogPostContent, BlogPostContainer, TagList } from '../utils/styles';
import { arrayReducer } from '../utils/helpers.js';
export default function TagsPage({
data
}) {
const { edges: posts } = data.allMarkdownRemark;
const categoryArray = arrayReducer(posts, 'category');
const categoryLinks = categoryArray.map((category, index) => {
return (
<li className="category-item" key={index}>
<Link className='category-list-link' to={`/categories/${category}`} key={index}>{category}</Link>
</li>
)
});
return (
<BlogPostContainer>
<BlogPostContent>
<h2>Categories</h2>
<TagList className='categories-list'>{categoryLinks}</TagList>
</BlogPostContent>
</BlogPostContainer>
);
}
export const query = graphql`
query CategoryPage {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
frontmatter {
category
}
}
}
}
}
`; | aberkow/gatsby-blog | src/pages/categories.js | JavaScript | mit | 1,085 |
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
ElasticoExample::Application.initialize!
| gneyal/ElasticoExample | config/environment.rb | Ruby | mit | 159 |
# frozen_string_literal: true
FactoryBot.define do
sequence(:course_assessment_assessment_name) { |n| "Assessment #{n}" }
sequence(:course_assessment_assessment_description) { |n| "Awesome description #{n}" }
factory :course_assessment_assessment, class: Course::Assessment, aliases: [:assessment],
parent: :course_lesson_plan_item do
transient do
question_count { 1 }
end
tab do
category = course.assessment_categories.first
category&.tabs&.first || build(:course_assessment_tab, course: course)
end
title { generate(:course_assessment_assessment_name) }
description { generate(:course_assessment_assessment_description) }
base_exp { 1000 }
autograded { false }
published { false }
tabbed_view { false }
delayed_grade_publication { false }
randomization { nil }
show_mcq_answer { true }
trait :delay_grade_publication do
delayed_grade_publication { true }
end
trait :view_password do
view_password { 'LOL' }
end
trait :not_started do
start_at { 1.day.from_now }
end
trait :with_mcq_question do
after(:build) do |assessment, evaluator|
evaluator.question_count.downto(1).each do |i|
question = build(:course_assessment_question_multiple_response, :multiple_choice)
assessment.question_assessments.build(question: question.acting_as, weight: i)
end
end
end
trait :with_mrq_question do
after(:build) do |assessment, evaluator|
evaluator.question_count.downto(1).each do |i|
question = build(:course_assessment_question_multiple_response)
assessment.question_assessments.build(question: question.acting_as, weight: i)
end
end
end
trait :with_programming_question do
after(:build) do |assessment, evaluator|
evaluator.question_count.downto(1).each do |i|
question = build(:course_assessment_question_programming, :auto_gradable, template_package: true)
assessment.question_assessments.build(question: question.acting_as, weight: i)
end
end
end
trait :with_programming_file_submission_question do
after(:build) do |assessment, evaluator|
evaluator.question_count.downto(1).each do |i|
question = build(:course_assessment_question_programming,
:auto_gradable, :multiple_file_submission)
assessment.question_assessments.build(question: question.acting_as, weight: i)
end
end
end
trait :with_text_response_question do
after(:build) do |assessment, evaluator|
evaluator.question_count.downto(1).each do |i|
question = build(:course_assessment_question_text_response, :allow_attachment)
assessment.question_assessments.build(question: question.acting_as, weight: i)
end
end
end
trait :with_file_upload_question do
after(:build) do |assessment, evaluator|
evaluator.question_count.downto(1).each do |i|
question = build(:course_assessment_question_text_response, :file_upload_question)
assessment.question_assessments.build(question: question.acting_as, weight: i)
end
end
end
trait :with_all_question_types do
with_mcq_question
with_mrq_question
with_programming_question
with_text_response_question
with_file_upload_question
# TODO: To add scribing question once it is completed
end
trait :published do
after(:build) do |assessment|
assessment.published = true
end
end
trait :published_with_mcq_question do
with_mcq_question
published
end
trait :published_with_mrq_question do
with_mrq_question
published
end
trait :published_with_text_response_question do
with_text_response_question
published
end
trait :published_with_programming_question do
with_programming_question
published
end
trait :published_with_file_upload_question do
with_file_upload_question
published
end
trait :published_with_all_question_types do
with_all_question_types
published
end
trait :autograded do
autograded { true }
end
trait :not_show_mcq_answer do
show_mcq_answer { false }
end
trait :with_attachments do
after(:build) do |assessment|
material = build(:material, folder: assessment.folder)
assessment.folder.materials << material
end
end
end
end
| cysjonathan/coursemology2 | spec/factories/course_assessment_assessments.rb | Ruby | mit | 4,618 |
<?php
namespace Rails\ActiveRecord\Associations;
use Rails\ServiceManager\ServiceLocatorAwareTrait;
class Associations
{
use ServiceLocatorAwareTrait;
protected static $associationsByClass = [];
/**
* @var Loader
*/
protected static $loader;
/**
* Associations name => options pairs.
*
* @var array
*/
protected $associations = [];
protected $className = [];
public static function forClass($className)
{
if (!isset(self::$associationsByClass[$className])) {
self::$associationsByClass[$className] = new self($className);
}
return self::$associationsByClass[$className];
}
public function __construct($className)
{
// $this->model = $model;
// $this->className = get_class($model);
$this->className = $className;
}
public function loader()
{
if (!self::$loader) {
self::$loader = new Loader();
}
return self::$loader;
}
/**
* Get all associations and their options.
*
* @return array
*/
public function associations()
{
if (!$this->associations) {
if ($this->getService('rails.config')['use_cache']) {
$this->associations = $this->getCachedData();
} else {
$this->associations = $this->getAssociationsData();
}
}
return $this->associations;
}
/**
* Return options for one association. If it doesn't exists,
* `false` is returned.
*
* @return array|false
*/
public function get($name)
{
if ($this->exists($name)) {
return $this->associations[$name];
}
return false;
}
/**
* Checks if an association exists.
*
* @return bool
*/
public function exists($name)
{
return array_key_exists($name, $this->associations());
}
public function load($record, $name)
{
if (!$this->exists($name)) {
throw new Exception\InvalidArgumentException(
sprintf("Trying to load unknown association %s", $name)
);
}
$options = $this->get($name);
return $this->loader()->load($record, $name, $options);
}
/**
* If any of the associations has a 'dependent' option, the
* before-destroy callback 'alterDependencies' should be called.
* That method will take care of executing the proper tasks with
* the dependencies according to the options set.
* Same with the 'autosave' option.
*
* # TODO: Move this info somewhere else?
* The children's 'autosave' option will override the parent's. For example, User has
* many posts with 'autosave' => true, and Post belongs to User with 'autosave' => false.
* Upon User save, although User set autosave => true for its association, since Post set
* autosave to false, the posts won't be automatically saved. This also clarifies that
* the 'autosave' option in a child doesn't mean that the parent will be autosaved, rather,
* it defines if the child itself will be saved on parent's save.
* If the children are set to be saved alongside its parent, and one of the fails to be saved,
* the parent will also stay unsaved.
*
// * If the children aren't set to be saved, their attributes, however, are 'reset':
*
// * <pre>
// * // User has many posts, autosave: false
// * $user = User::find(1);
// * $user->posts()[0]->title = 'Some new title'; // Set new title to first post
// * $user->name = 'Some new name'; // Edit user so it can be saved
// * $user->save(); // User saved successfuly
// * $user->posts()[0]->title = 'Old title'; // Posts attributes got reset
// * </pre>
*
* @return array
*/
public function callbacks()
{
$dependent = false;
$autosave = false;
$callbacks = [
'beforeDestroy' => [],
'beforeSave' => []
];
foreach ($this->associations() as $data) {
switch ($data['type']) {
case 'belongsTo':
case 'hasMany':
case 'hasOne':
if (
!empty($data['dependent']) &&
!$dependent
) {
$callbacks = [
'beforeDestroy' => [
'alterDependencies'
]
];
}
# Fallthrough
default:
if (
!empty($data['autosave']) &&
!$autosave
) {
$callbacks = [
'beforeSave' => [
'saveDependencies'
]
];
}
break;
}
if ($autosave && $dependent) {
break;
}
}
return array_filter($callbacks);
}
protected function getCachedData()
{
$key = 'rails.ar.' . $this->className . '.associations';
return $this->getService('rails.cache')->fetch($key, function() {
return $this->getAssociationsData();
});
}
protected function getAssociationsData()
{
$extractor = new Extractor();
return $extractor->getAssociations($this->className);
}
}
| railsphp/framework | src/Rails/ActiveRecord/Associations/Associations.php | PHP | mit | 5,766 |
/* -*- javascript -*- */
"use strict";
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';
import {LogManager} from 'aurelia-framework';
import {ConsoleAppender} from 'aurelia-logging-console';
import {customMatchers} from '../helpers';
describe('ui-icon', () => {
let component, logger;
beforeAll(() => {
jasmine.addMatchers( customMatchers );
logger = LogManager.getLogger( 'ui-icon-spec' );
});
beforeEach(() => {
component = StageComponent.withResources('src/elements/ui-icon');
});
afterEach(() => {
component.dispose();
});
describe( 'as a custom attribute', () => {
it( 'adds semantic classes when bound', done => {
component.
inView(`
<i ui-icon="name: cloud"></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'cloud', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'has a reasonable name default', done => {
component.
inView(`
<i ui-icon></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'help', 'circle', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a size class when one is set', done => {
component.
inView(`
<i ui-icon="name: cloud; size: huge"></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'huge', 'cloud', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a color class when one is set', done => {
component.
inView(`
<i ui-icon="name: user; color: red">Erase History</i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'red', 'user', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a disabled class when it is set', done => {
component.
inView(`
<i ui-icon="disabled: true">Eject!</i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'disabled', 'icon' );
}).
then( done ).
catch( done.fail );
});
});
describe( 'as a custom element', () => {
it( 'uses the icon name', done => {
component.
inView(`
<ui-icon name="cloud"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'cloud' );
}).
then( done ).
catch( done.fail );
});
it( 'support multiple names', done => {
component.
inView(`
<ui-icon name="circular inverted users"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'circular', 'inverted', 'users' );
}).
then( done ).
catch( done.fail );
});
it( 'has a reasonable default name', done => {
component.
inView(`
<ui-icon></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'help', 'circle' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a size class when one is set', done => {
component.
inView(`
<ui-icon size="huge"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'huge' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a color class when one is set', done => {
component.
inView(`
<ui-icon color="red"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'red' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a disabled class when it is set', done => {
component.
inView(`
<ui-icon disabled="true"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'disabled' );
}).
then( done ).
catch( done.fail );
});
});
});
| ged/aurelia-semantic-ui | test/unit/elements/ui-icon_spec.js | JavaScript | mit | 4,822 |
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
# 6367 km is the radius of the Earth
km = 6367 * c
return km
| anduslim/codex | codex_project/actors/haversine.py | Python | mit | 554 |
package com.github.messenger4j.send.message.template.receipt;
import static java.util.Optional.empty;
import java.net.URL;
import java.util.Optional;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;
/**
* @author Max Grabenhorst
* @since 1.0.0
*/
@ToString
@EqualsAndHashCode
public final class Item {
private final String title;
private final float price;
private final Optional<String> subtitle;
private final Optional<Integer> quantity;
private final Optional<String> currency;
private final Optional<URL> imageUrl;
private Item(
String title,
float price,
Optional<String> subtitle,
Optional<Integer> quantity,
Optional<String> currency,
Optional<URL> imageUrl) {
this.title = title;
this.price = price;
this.subtitle = subtitle;
this.quantity = quantity;
this.currency = currency;
this.imageUrl = imageUrl;
}
public static Item create(@NonNull String title, float price) {
return create(title, price, empty(), empty(), empty(), empty());
}
public static Item create(
@NonNull String title,
float price,
@NonNull Optional<String> subtitle,
@NonNull Optional<Integer> quantity,
@NonNull Optional<String> currency,
@NonNull Optional<URL> imageUrl) {
return new Item(title, price, subtitle, quantity, currency, imageUrl);
}
public String title() {
return title;
}
public float price() {
return price;
}
public Optional<String> subtitle() {
return subtitle;
}
public Optional<Integer> quantity() {
return quantity;
}
public Optional<String> currency() {
return currency;
}
public Optional<URL> imageUrl() {
return imageUrl;
}
}
| messenger4j/messenger4j | src/main/java/com/github/messenger4j/send/message/template/receipt/Item.java | Java | mit | 1,752 |
package com.halle.facade;
import java.util.List;
import javax.ejb.Local;
import com.halle.exception.ApplicationException;
import com.halle.model.Friend;
@Local
public interface FriendFacade {
void inviteByPhone(final String token, final String name, final String phoneFriend) throws ApplicationException;
List<Friend> findAllFriend(final String token, String status) throws ApplicationException;
}
| FelipeAvila/hallejava | HalleEJB/ejbModule/com/halle/facade/FriendFacade.java | Java | mit | 410 |
// Package peering implements the Azure ARM Peering service API version 2020-10-01.
//
// Peering Client
package peering
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
const (
// DefaultBaseURI is the default URI used for the service Peering
DefaultBaseURI = "https://management.azure.com"
)
// BaseClient is the base client for Peering.
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
// New creates an instance of the BaseClient client.
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with
// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
}
// CheckServiceProviderAvailability checks if the peering service provider is present within 1000 miles of customer's
// location
// Parameters:
// checkServiceProviderAvailabilityInput - the CheckServiceProviderAvailabilityInput indicating customer
// location and service provider.
func (client BaseClient) CheckServiceProviderAvailability(ctx context.Context, checkServiceProviderAvailabilityInput CheckServiceProviderAvailabilityInput) (result String, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CheckServiceProviderAvailability")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.CheckServiceProviderAvailabilityPreparer(ctx, checkServiceProviderAvailabilityInput)
if err != nil {
err = autorest.NewErrorWithError(err, "peering.BaseClient", "CheckServiceProviderAvailability", nil, "Failure preparing request")
return
}
resp, err := client.CheckServiceProviderAvailabilitySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "peering.BaseClient", "CheckServiceProviderAvailability", resp, "Failure sending request")
return
}
result, err = client.CheckServiceProviderAvailabilityResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "peering.BaseClient", "CheckServiceProviderAvailability", resp, "Failure responding to request")
return
}
return
}
// CheckServiceProviderAvailabilityPreparer prepares the CheckServiceProviderAvailability request.
func (client BaseClient) CheckServiceProviderAvailabilityPreparer(ctx context.Context, checkServiceProviderAvailabilityInput CheckServiceProviderAvailabilityInput) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-10-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Peering/CheckServiceProviderAvailability", pathParameters),
autorest.WithJSON(checkServiceProviderAvailabilityInput),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CheckServiceProviderAvailabilitySender sends the CheckServiceProviderAvailability request. The method will close the
// http.Response Body if it receives an error.
func (client BaseClient) CheckServiceProviderAvailabilitySender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CheckServiceProviderAvailabilityResponder handles the response to the CheckServiceProviderAvailability request. The method always
// closes the http.Response Body.
func (client BaseClient) CheckServiceProviderAvailabilityResponder(resp *http.Response) (result String, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result.Value),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| Azure/azure-sdk-for-go | services/peering/mgmt/2020-10-01/peering/client.go | GO | mit | 4,814 |
//
// This software is released under the 3-clause BSD license.
//
// Copyright (c) 2015, Xin Chen <txchen@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
/*******************************************************************************
* 1) MidiPlayer.js.
******************************************************************************/
/**
* MidiPlayer class. Used to play midi by javascript, without any plugin.
* Requires a HTML5 browser: firefox, chrome, safari, opera, IE10+.
*
* The other 5 js files are from [2][3], which is a demo of [1]:
* [1] http://matt.west.co.tt/music/jasmid-midi-synthesis-with-javascript-and-html5-audio/
* [2] http://jsspeccy.zxdemo.org/jasmid/
* [3] https://github.com/gasman/jasmid
*
* Modification is done to audio.js:
* - added function fireEventEnded().
* - added 'ended' event firing when generator.finished is true.
* - move 'context' outside function AudioPlayer, so in chrome it won't have this error
* when you loop the play:
* Failed to construct 'AudioContext': number of hardware contexts reached maximum (6)
*
* Github site: https://github.com/chenx/MidiPlayer
*
* @by: X. Chen
* @Create on: 4/1/2015
* @Last modified: 4/3/2015
*/
if (typeof (MidiPlayer) == 'undefined') {
/**
* Constructor of MidiPlayer class.
* @param midi MIDI file path.
* @param target Target html element that this MIDI player is attached to.
* @param loop Optinoal. Whether loop the play. Value is true/false, default is false.
* @param maxLoop Optional. max number of loops to play when loop is true.
* Negative or 0 means infinite. Default is 1.
* @param end_callback Optional. Callback function when MIDI ends.
* @author X. Chen. April 2015.
*/
var MidiPlayer = function(midi, target, loop, maxLoop, end_callback) {
this.midi = midi;
this.target = document.getElementById(target);
this.loop = (typeof (loop) == 'undefined') ? false : loop;
if (! loop) {
this.max_loop_ct = 1;
} else {
this.max_loop_ct = (typeof (maxLoop) == 'undefined') ? 1 : (maxLoop <= 0 ? 0 : maxLoop);
}
this.end_callback = (typeof (end_callback) == 'function') ? end_callback : null;
this.debug_div = null;
this.midiFile = null;
this.synth = null;
this.replayer = null;
this.audio = null;
this.ct = 0; // loop counter.
this.started = false; // state of play: started/stopped.
this.listener_added = false;
}
MidiPlayer.prototype.setDebugDiv = function(debug_div_id) {
this.debug_div = (typeof (debug_div_id) == 'undefined') ?
null : document.getElementById(debug_div_id);
}
MidiPlayer.prototype.debug = function(msg) {
if (this.debug_div) {
this.debug_div.innerHTML += msg + '<br/>';
}
}
MidiPlayer.prototype.stop = function() {
this.started = false;
this.ct = 0;
if (this.audio) {
this.audio.stop();
this.audio = null;
}
if (this.max_loop_ct > 0) {
if (this.end_callback) { this.end_callback(); }
}
}
MidiPlayer.prototype.play = function() {
if (this.started) {
this.stop();
//return;
}
this.started = true;
var o = this.target;
var _this = this; // must be 'var', otherwise _this is public, and causes problem.
var file = this.midi;
var loop = this.loop;
if (window.addEventListener) {
// Should not add more than one listener after first call, otherwise o has more
// and more listeners attached, and will fire n events the n-th time calling play.
if (! this.listener_added) {
this.listener_added = true;
if (o) { // If o does not exist, don't add listener.
o.addEventListener('ended', function() { // addEventListener not work for IE8.
//alert('ended');
if (_this.max_loop_ct <= 0 || (++ _this.ct) < _this.max_loop_ct) {
_this.replayer = Replayer(_this.midiFile, _this.synth);
_this.audio = AudioPlayer(_this.replayer, o, loop);
_this.debug( file + ': loop ' + (1 +_this.ct) );
}
else if (_this.max_loop_ct > 0) {
_this.stop();
}
}, false);
}
}
} else if (window.attachEvent) { // IE don't work anyway.
//document.getElementById('music').attachEvent(
// 'onclick', function(e) { alert('IE end'); }, true);
}
loadRemote(file, function(data) {
if (_this.ct == 0) {
_this.midiFile = MidiFile(data);
_this.synth = Synth(44100);
}
_this.replayer = Replayer(_this.midiFile, _this.synth);
_this.audio = AudioPlayer(_this.replayer, o, loop);
_this.debug( file + ': loop ' + (1 + _this.ct) );
//alert(_this.audio.type); // webkit for firefox, chrome; flash for opera/safari.
});
}
// This function is modified from [2] by adding support for IE. See:
// http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie
// https://code.google.com/p/jsdap/source/browse/trunk/?r=64
//
// However, IE8 and before do not support HTML5 Audio tag so this still will not work.
// See: http://www.impressivewebs.com/html5-support-ie9/
//
// A private function, defined by 'var'.
// Original definition in [2] is: function loadRemote(path, callback) {
var loadRemote = function(path, callback) {
var fetch = new XMLHttpRequest();
fetch.open('GET', path);
if (fetch.overrideMimeType) {
fetch.overrideMimeType("text/plain; charset=x-user-defined"); // for non-IE.
}
else {
fetch.setRequestHeader('Accept-Charset', 'x-user-defined'); // for IE.
}
fetch.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
// munge response into a binary string
if (IE_HACK) { // for IE.
var t = BinaryToArray(fetch.responseBody).toArray();
var ff = [];
var mx = t.length;
var scc= String.fromCharCode;
for (var z = 0; z < mx; z++) {
// t[z] here is equivalent to 't.charCodeAt(z) & 255' below.
// e.g., t[z] is 238, below t.charCodeAt[z] is 63470. 63470 & 255 = 238.
// But IE8 has no Audio element, so can't play anyway,
// and will report this error in audio.js: 'Audio' is undefined.
ff[z] = scc(t[z]);
}
callback(ff.join(""));
} else { // for non-IE.
var t = this.responseText || "" ;
var ff = [];
var mx = t.length;
var scc= String.fromCharCode;
for (var z = 0; z < mx; z++) {
ff[z] = scc(t.charCodeAt(z) & 255);
}
callback(ff.join(""));
}
}
}
fetch.send();
}
// Now expand definition of MidiPlayer to include the other 6 files below.
// So comment out the line below, and add the back curly bracket at the end of file.
//} // (previous) end of: if (typeof (MidiPlayer) == 'undefined')
/*******************************************************************************
* 2) vbscript.js
******************************************************************************/
/**
* Convert binary string to array.
*
* See:
* [1] http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie
* [2] https://code.google.com/p/jsdap/source/browse/trunk/?r=64
*/
var IE_HACK = (/msie/i.test(navigator.userAgent) &&
!/opera/i.test(navigator.userAgent));
if (IE_HACK) {
//alert('IE hack');
document.write('<script type="text/vbscript">\n\
Function BinaryToArray(Binary)\n\
Dim i\n\
ReDim byteArray(LenB(Binary))\n\
For i = 1 To LenB(Binary)\n\
byteArray(i-1) = AscB(MidB(Binary, i, 1))\n\
Next\n\
BinaryToArray = byteArray\n\
End Function\n\
</script>');
}
/*******************************************************************************
* Files 3) to 7) below are by:
* Matt Westcott <matt@west.co.tt> - @gasmanic - http://matt.west.co.tt/
* See:
* - http://matt.west.co.tt/music/jasmid-midi-synthesis-with-javascript-and-html5-audio/
* - http://jsspeccy.zxdemo.org/jasmid/
* - https://github.com/gasman/jasmid
******************************************************************************/
/*******************************************************************************
* 3) audio.js.
******************************************************************************/
var sampleRate = 44100; /* hard-coded in Flash player */
var context = null // XC.
// Note this may cause name conflict. So be careful of variable name "context".
//
// http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
// Added by XC.
//
function fireEventEnded(target) {
if (! target) return;
if (document.createEvent) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("ended", false, true);
target.dispatchEvent(evt);
}
else if (document.createEventObject) { // IE before version 9
var myEvent = document.createEventObject();
target.fireEvent('onclick', myEvent);
}
}
//function AudioPlayer(generator, opts) {
function AudioPlayer(generator, targetElement, opts) {
if (!opts) opts = {};
var latency = opts.latency || 1;
var checkInterval = latency * 100 /* in ms */
var audioElement = new Audio();
var webkitAudio = window.AudioContext || window.webkitAudioContext;
var requestStop = false;
if (audioElement.mozSetup) {
audioElement.mozSetup(2, sampleRate); /* channels, sample rate */
var buffer = []; /* data generated but not yet written */
var minBufferLength = latency * 2 * sampleRate; /* refill buffer when there are only this many elements remaining */
var bufferFillLength = Math.floor(latency * sampleRate);
function checkBuffer() {
if (requestStop) return; // no more data feed after request stop. xc.
if (buffer.length) {
var written = audioElement.mozWriteAudio(buffer);
buffer = buffer.slice(written);
}
if (buffer.length < minBufferLength && !generator.finished) {
buffer = buffer.concat(generator.generate(bufferFillLength));
}
if (!requestStop && (!generator.finished || buffer.length)) {
setTimeout(checkBuffer, checkInterval);
}
if (!requestStop && generator.finished) {
fireEventEnded(targetElement); // xc.
}
}
checkBuffer();
return {
'type': 'Firefox Audio',
'stop': function() {
requestStop = true;
}
}
} else if (webkitAudio) {
// Uses Webkit Web Audio API if available
// chrome stops after 5 invocation. XC. Error is:
// Failed to construct 'AudioContext': number of hardware contexts reached maximum (6)
//var context = new webkitAudio();
if (! context) context = new webkitAudio(); // fixed by this. XC.
sampleRate = context.sampleRate;
var channelCount = 2;
var bufferSize = 4096*4; // Higher for less gitches, lower for less latency
var node = context.createScriptProcessor(bufferSize, 0, channelCount);
node.onaudioprocess = function(e) { process(e) };
function process(e) {
if (generator.finished) {
node.disconnect();
//alert('done: ' + targetElement); // xc.
fireEventEnded(targetElement); // xc.
return;
}
var dataLeft = e.outputBuffer.getChannelData(0);
var dataRight = e.outputBuffer.getChannelData(1);
var generate = generator.generate(bufferSize);
for (var i = 0; i < bufferSize; ++i) {
dataLeft[i] = generate[i*2];
dataRight[i] = generate[i*2+1];
}
}
// start
node.connect(context.destination);
return {
'stop': function() {
// pause
node.disconnect();
requestStop = true;
},
'type': 'Webkit Audio'
}
} else {
// Fall back to creating flash player
var c = document.createElement('div');
c.innerHTML = '<embed type="application/x-shockwave-flash" id="da-swf" src="da.swf" width="8" height="8" allowScriptAccess="always" style="position: fixed; left:-10px;" />';
document.body.appendChild(c);
var swf = document.getElementById('da-swf');
var minBufferDuration = latency * 1000; /* refill buffer when there are only this many ms remaining */
var bufferFillLength = latency * sampleRate;
function write(data) {
var out = new Array(data.length);
for (var i = data.length-1; i != 0; i--) {
out[i] = Math.floor(data[i]*32768);
}
return swf.write(out.join(' '));
}
function checkBuffer() {
if (requestStop) return; // no more data feed after request stop. xc.
if (swf.bufferedDuration() < minBufferDuration) {
write(generator.generate(bufferFillLength));
};
if (!requestStop && !generator.finished) setTimeout(checkBuffer, checkInterval);
if (!requestStop && generator.finished) fireEventEnded(targetElement); // xc.
}
function checkReady() {
if (swf.write) {
checkBuffer();
} else {
setTimeout(checkReady, 10);
}
}
checkReady();
return {
'stop': function() {
swf.stop();
requestStop = true;
},
'bufferedDuration': function() {
return swf.bufferedDuration();
},
'type': 'Flash Audio'
}
}
}
/*******************************************************************************
* 4) midifile.js
******************************************************************************/
/**
* Class to parse the .mid file format. Depends on stream.js.
*/
function MidiFile(data) {
function readChunk(stream) {
var id = stream.read(4);
var length = stream.readInt32();
return {
'id': id,
'length': length,
'data': stream.read(length)
};
}
var lastEventTypeByte;
function readEvent(stream) {
var event = {};
event.deltaTime = stream.readVarInt();
var eventTypeByte = stream.readInt8();
if ((eventTypeByte & 0xf0) == 0xf0) {
/* system / meta event */
if (eventTypeByte == 0xff) {
/* meta event */
event.type = 'meta';
var subtypeByte = stream.readInt8();
var length = stream.readVarInt();
switch(subtypeByte) {
case 0x00:
event.subtype = 'sequenceNumber';
if (length != 2) throw "Expected length for sequenceNumber event is 2, got " + length;
event.number = stream.readInt16();
return event;
case 0x01:
event.subtype = 'text';
event.text = stream.read(length);
return event;
case 0x02:
event.subtype = 'copyrightNotice';
event.text = stream.read(length);
return event;
case 0x03:
event.subtype = 'trackName';
event.text = stream.read(length);
return event;
case 0x04:
event.subtype = 'instrumentName';
event.text = stream.read(length);
return event;
case 0x05:
event.subtype = 'lyrics';
event.text = stream.read(length);
return event;
case 0x06:
event.subtype = 'marker';
event.text = stream.read(length);
return event;
case 0x07:
event.subtype = 'cuePoint';
event.text = stream.read(length);
return event;
case 0x20:
event.subtype = 'midiChannelPrefix';
if (length != 1) throw "Expected length for midiChannelPrefix event is 1, got " + length;
event.channel = stream.readInt8();
return event;
case 0x2f:
event.subtype = 'endOfTrack';
if (length != 0) throw "Expected length for endOfTrack event is 0, got " + length;
return event;
case 0x51:
event.subtype = 'setTempo';
if (length != 3) throw "Expected length for setTempo event is 3, got " + length;
event.microsecondsPerBeat = (
(stream.readInt8() << 16)
+ (stream.readInt8() << 8)
+ stream.readInt8()
)
return event;
case 0x54:
event.subtype = 'smpteOffset';
if (length != 5) throw "Expected length for smpteOffset event is 5, got " + length;
var hourByte = stream.readInt8();
event.frameRate = {
0x00: 24, 0x20: 25, 0x40: 29, 0x60: 30
}[hourByte & 0x60];
event.hour = hourByte & 0x1f;
event.min = stream.readInt8();
event.sec = stream.readInt8();
event.frame = stream.readInt8();
event.subframe = stream.readInt8();
return event;
case 0x58:
event.subtype = 'timeSignature';
if (length != 4) throw "Expected length for timeSignature event is 4, got " + length;
event.numerator = stream.readInt8();
event.denominator = Math.pow(2, stream.readInt8());
event.metronome = stream.readInt8();
event.thirtyseconds = stream.readInt8();
return event;
case 0x59:
event.subtype = 'keySignature';
if (length != 2) throw "Expected length for keySignature event is 2, got " + length;
event.key = stream.readInt8(true);
event.scale = stream.readInt8();
return event;
case 0x7f:
event.subtype = 'sequencerSpecific';
event.data = stream.read(length);
return event;
default:
// console.log("Unrecognised meta event subtype: " + subtypeByte);
event.subtype = 'unknown'
event.data = stream.read(length);
return event;
}
event.data = stream.read(length);
return event;
} else if (eventTypeByte == 0xf0) {
event.type = 'sysEx';
var length = stream.readVarInt();
event.data = stream.read(length);
return event;
} else if (eventTypeByte == 0xf7) {
event.type = 'dividedSysEx';
var length = stream.readVarInt();
event.data = stream.read(length);
return event;
} else {
throw "Unrecognised MIDI event type byte: " + eventTypeByte;
}
} else {
/* channel event */
var param1;
if ((eventTypeByte & 0x80) == 0) {
/* running status - reuse lastEventTypeByte as the event type.
eventTypeByte is actually the first parameter
*/
param1 = eventTypeByte;
eventTypeByte = lastEventTypeByte;
} else {
param1 = stream.readInt8();
lastEventTypeByte = eventTypeByte;
}
var eventType = eventTypeByte >> 4;
event.channel = eventTypeByte & 0x0f;
event.type = 'channel';
switch (eventType) {
case 0x08:
event.subtype = 'noteOff';
event.noteNumber = param1;
event.velocity = stream.readInt8();
return event;
case 0x09:
event.noteNumber = param1;
event.velocity = stream.readInt8();
if (event.velocity == 0) {
event.subtype = 'noteOff';
} else {
event.subtype = 'noteOn';
}
return event;
case 0x0a:
event.subtype = 'noteAftertouch';
event.noteNumber = param1;
event.amount = stream.readInt8();
return event;
case 0x0b:
event.subtype = 'controller';
event.controllerType = param1;
event.value = stream.readInt8();
return event;
case 0x0c:
event.subtype = 'programChange';
event.programNumber = param1;
return event;
case 0x0d:
event.subtype = 'channelAftertouch';
event.amount = param1;
return event;
case 0x0e:
event.subtype = 'pitchBend';
event.value = param1 + (stream.readInt8() << 7);
return event;
default:
throw "Unrecognised MIDI event type: " + eventType
/*
console.log("Unrecognised MIDI event type: " + eventType);
stream.readInt8();
event.subtype = 'unknown';
return event;
*/
}
}
}
stream = Stream(data);
var headerChunk = readChunk(stream);
if (headerChunk.id != 'MThd' || headerChunk.length != 6) {
throw "Bad .mid file - header not found";
}
var headerStream = Stream(headerChunk.data);
var formatType = headerStream.readInt16();
var trackCount = headerStream.readInt16();
var timeDivision = headerStream.readInt16();
if (timeDivision & 0x8000) {
throw "Expressing time division in SMTPE frames is not supported yet"
} else {
ticksPerBeat = timeDivision;
}
var header = {
'formatType': formatType,
'trackCount': trackCount,
'ticksPerBeat': ticksPerBeat
}
var tracks = [];
for (var i = 0; i < header.trackCount; i++) {
tracks[i] = [];
var trackChunk = readChunk(stream);
if (trackChunk.id != 'MTrk') {
throw "Unexpected chunk - expected MTrk, got "+ trackChunk.id;
}
var trackStream = Stream(trackChunk.data);
while (!trackStream.eof()) {
var event = readEvent(trackStream);
tracks[i].push(event);
//console.log(event);
}
}
return {
'header': header,
'tracks': tracks
}
}
/*******************************************************************************
* 5) replayer.js
******************************************************************************/
function Replayer(midiFile, synth) {
var trackStates = [];
var beatsPerMinute = 120;
var ticksPerBeat = midiFile.header.ticksPerBeat;
var channelCount = 16;
for (var i = 0; i < midiFile.tracks.length; i++) {
trackStates[i] = {
'nextEventIndex': 0,
'ticksToNextEvent': (
midiFile.tracks[i].length ?
midiFile.tracks[i][0].deltaTime :
null
)
};
}
function Channel() {
var generatorsByNote = {};
var currentProgram = PianoProgram;
function noteOn(note, velocity) {
if (generatorsByNote[note] && !generatorsByNote[note].released) {
/* playing same note before releasing the last one. BOO */
generatorsByNote[note].noteOff(); /* TODO: check whether we ought to be passing a velocity in */
}
generator = currentProgram.createNote(note, velocity);
synth.addGenerator(generator);
generatorsByNote[note] = generator;
}
function noteOff(note, velocity) {
if (generatorsByNote[note] && !generatorsByNote[note].released) {
generatorsByNote[note].noteOff(velocity);
}
}
function setProgram(programNumber) {
currentProgram = PROGRAMS[programNumber] || PianoProgram;
}
return {
'noteOn': noteOn,
'noteOff': noteOff,
'setProgram': setProgram
}
}
var channels = [];
for (var i = 0; i < channelCount; i++) {
channels[i] = Channel();
}
var nextEventInfo;
var samplesToNextEvent = 0;
function getNextEvent() {
var ticksToNextEvent = null;
var nextEventTrack = null;
var nextEventIndex = null;
for (var i = 0; i < trackStates.length; i++) {
if (
trackStates[i].ticksToNextEvent != null
&& (ticksToNextEvent == null || trackStates[i].ticksToNextEvent < ticksToNextEvent)
) {
ticksToNextEvent = trackStates[i].ticksToNextEvent;
nextEventTrack = i;
nextEventIndex = trackStates[i].nextEventIndex;
}
}
if (nextEventTrack != null) {
/* consume event from that track */
var nextEvent = midiFile.tracks[nextEventTrack][nextEventIndex];
if (midiFile.tracks[nextEventTrack][nextEventIndex + 1]) {
trackStates[nextEventTrack].ticksToNextEvent += midiFile.tracks[nextEventTrack][nextEventIndex + 1].deltaTime;
} else {
trackStates[nextEventTrack].ticksToNextEvent = null;
}
trackStates[nextEventTrack].nextEventIndex += 1;
/* advance timings on all tracks by ticksToNextEvent */
for (var i = 0; i < trackStates.length; i++) {
if (trackStates[i].ticksToNextEvent != null) {
trackStates[i].ticksToNextEvent -= ticksToNextEvent
}
}
nextEventInfo = {
'ticksToEvent': ticksToNextEvent,
'event': nextEvent,
'track': nextEventTrack
}
var beatsToNextEvent = ticksToNextEvent / ticksPerBeat;
var secondsToNextEvent = beatsToNextEvent / (beatsPerMinute / 60);
samplesToNextEvent += secondsToNextEvent * synth.sampleRate;
} else {
nextEventInfo = null;
samplesToNextEvent = null;
self.finished = true;
}
}
getNextEvent();
function generate(samples) {
var data = new Array(samples*2);
var samplesRemaining = samples;
var dataOffset = 0;
while (true) {
if (samplesToNextEvent != null && samplesToNextEvent <= samplesRemaining) {
/* generate samplesToNextEvent samples, process event and repeat */
var samplesToGenerate = Math.ceil(samplesToNextEvent);
if (samplesToGenerate > 0) {
synth.generateIntoBuffer(samplesToGenerate, data, dataOffset);
dataOffset += samplesToGenerate * 2;
samplesRemaining -= samplesToGenerate;
samplesToNextEvent -= samplesToGenerate;
}
handleEvent();
getNextEvent();
} else {
/* generate samples to end of buffer */
if (samplesRemaining > 0) {
synth.generateIntoBuffer(samplesRemaining, data, dataOffset);
samplesToNextEvent -= samplesRemaining;
}
break;
}
}
return data;
}
function handleEvent() {
var event = nextEventInfo.event;
switch (event.type) {
case 'meta':
switch (event.subtype) {
case 'setTempo':
beatsPerMinute = 60000000 / event.microsecondsPerBeat
}
break;
case 'channel':
switch (event.subtype) {
case 'noteOn':
channels[event.channel].noteOn(event.noteNumber, event.velocity);
break;
case 'noteOff':
channels[event.channel].noteOff(event.noteNumber, event.velocity);
break;
case 'programChange':
//console.log('program change to ' + event.programNumber);
channels[event.channel].setProgram(event.programNumber);
break;
}
break;
}
}
function replay(audio) {
console.log('replay');
audio.write(generate(44100));
setTimeout(function() {replay(audio)}, 10);
}
var self = {
'replay': replay,
'generate': generate,
'finished': false
}
return self;
}
/*******************************************************************************
* 6) stream.js
******************************************************************************/
/**
* Wrapper for accessing strings through sequential reads.
*/
function Stream(str) {
var position = 0;
function read(length) {
var result = str.substr(position, length);
position += length;
return result;
}
/* read a big-endian 32-bit integer */
function readInt32() {
var result = (
(str.charCodeAt(position) << 24)
+ (str.charCodeAt(position + 1) << 16)
+ (str.charCodeAt(position + 2) << 8)
+ str.charCodeAt(position + 3));
position += 4;
return result;
}
/* read a big-endian 16-bit integer */
function readInt16() {
var result = (
(str.charCodeAt(position) << 8)
+ str.charCodeAt(position + 1));
position += 2;
return result;
}
/* read an 8-bit integer */
function readInt8(signed) {
var result = str.charCodeAt(position);
if (signed && result > 127) result -= 256;
position += 1;
return result;
}
function eof() {
return position >= str.length;
}
/* read a MIDI-style variable-length integer
(big-endian value in groups of 7 bits,
with top bit set to signify that another byte follows)
*/
function readVarInt() {
var result = 0;
while (true) {
var b = readInt8();
if (b & 0x80) {
result += (b & 0x7f);
result <<= 7;
} else {
/* b is the last byte */
return result + b;
}
}
}
return {
'eof': eof,
'read': read,
'readInt32': readInt32,
'readInt16': readInt16,
'readInt8': readInt8,
'readVarInt': readVarInt
}
}
/*******************************************************************************
* 7) synth.js
******************************************************************************/
function SineGenerator(freq) {
var self = {'alive': true};
var period = sampleRate / freq;
var t = 0;
self.generate = function(buf, offset, count) {
for (; count; count--) {
var phase = t / period;
var result = Math.sin(phase * 2 * Math.PI);
buf[offset++] += result;
buf[offset++] += result;
t++;
}
}
return self;
}
function SquareGenerator(freq, phase) {
var self = {'alive': true};
var period = sampleRate / freq;
var t = 0;
self.generate = function(buf, offset, count) {
for (; count; count--) {
var result = ( (t / period) % 1 > phase ? 1 : -1);
buf[offset++] += result;
buf[offset++] += result;
t++;
}
}
return self;
}
function ADSRGenerator(child, attackAmplitude, sustainAmplitude, attackTimeS, decayTimeS, releaseTimeS) {
var self = {'alive': true}
var attackTime = sampleRate * attackTimeS;
var decayTime = sampleRate * (attackTimeS + decayTimeS);
var decayRate = (attackAmplitude - sustainAmplitude) / (decayTime - attackTime);
var releaseTime = null; /* not known yet */
var endTime = null; /* not known yet */
var releaseRate = sustainAmplitude / (sampleRate * releaseTimeS);
var t = 0;
self.noteOff = function() {
if (self.released) return;
releaseTime = t;
self.released = true;
endTime = releaseTime + sampleRate * releaseTimeS;
}
self.generate = function(buf, offset, count) {
if (!self.alive) return;
var input = new Array(count * 2);
for (var i = 0; i < count*2; i++) {
input[i] = 0;
}
child.generate(input, 0, count);
childOffset = 0;
while(count) {
if (releaseTime != null) {
if (t < endTime) {
/* release */
while(count && t < endTime) {
var ampl = sustainAmplitude - releaseRate * (t - releaseTime);
buf[offset++] += input[childOffset++] * ampl;
buf[offset++] += input[childOffset++] * ampl;
t++;
count--;
}
} else {
/* dead */
self.alive = false;
return;
}
} else if (t < attackTime) {
/* attack */
while(count && t < attackTime) {
var ampl = attackAmplitude * t / attackTime;
buf[offset++] += input[childOffset++] * ampl;
buf[offset++] += input[childOffset++] * ampl;
t++;
count--;
}
} else if (t < decayTime) {
/* decay */
while(count && t < decayTime) {
var ampl = attackAmplitude - decayRate * (t - attackTime);
buf[offset++] += input[childOffset++] * ampl;
buf[offset++] += input[childOffset++] * ampl;
t++;
count--;
}
} else {
/* sustain */
while(count) {
buf[offset++] += input[childOffset++] * sustainAmplitude;
buf[offset++] += input[childOffset++] * sustainAmplitude;
t++;
count--;
}
}
}
}
return self;
}
function midiToFrequency(note) {
return 440 * Math.pow(2, (note-69)/12);
}
PianoProgram = {
'attackAmplitude': 0.2,
'sustainAmplitude': 0.1,
'attackTime': 0.02,
'decayTime': 0.3,
'releaseTime': 0.02,
'createNote': function(note, velocity) {
var frequency = midiToFrequency(note);
return ADSRGenerator(
SineGenerator(frequency),
this.attackAmplitude * (velocity / 128), this.sustainAmplitude * (velocity / 128),
this.attackTime, this.decayTime, this.releaseTime
);
}
}
StringProgram = {
'createNote': function(note, velocity) {
var frequency = midiToFrequency(note);
return ADSRGenerator(
SineGenerator(frequency),
0.5 * (velocity / 128), 0.2 * (velocity / 128),
0.4, 0.8, 0.4
);
}
}
PROGRAMS = {
41: StringProgram,
42: StringProgram,
43: StringProgram,
44: StringProgram,
45: StringProgram,
46: StringProgram,
47: StringProgram,
49: StringProgram,
50: StringProgram
};
function Synth(sampleRate) {
var generators = [];
function addGenerator(generator) {
generators.push(generator);
}
function generate(samples) {
var data = new Array(samples*2);
generateIntoBuffer(samples, data, 0);
return data;
}
function generateIntoBuffer(samplesToGenerate, buffer, offset) {
for (var i = offset; i < offset + samplesToGenerate * 2; i++) {
buffer[i] = 0;
}
for (var i = generators.length - 1; i >= 0; i--) {
generators[i].generate(buffer, offset, samplesToGenerate);
if (!generators[i].alive) generators.splice(i, 1);
}
}
return {
'sampleRate': sampleRate,
'addGenerator': addGenerator,
'generate': generate,
'generateIntoBuffer': generateIntoBuffer
}
}
} // end of: if (typeof (MidiPlayer) == 'undefined')
| fosscellcet/drishticryptex2017 | assets/js/midi.js | JavaScript | mit | 40,433 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Pirate.Ldap;
using Pirate.Ldap.Web;
using Pirate.Util.Logging;
namespace MemberService
{
public partial class ChangePassword : CustomPage
{
protected override string PageName
{
get { return "ChangePassword"; }
}
private TextBox _oldPasswordBox;
private Label _oldPasswordValid;
private TextBox _newPassword1Box;
private Label _newPassword1Valid;
private TextBox _newPassword2Box;
private Label _newPassword2Valid;
protected void Page_Load(object sender, EventArgs e)
{
if (!SetupLdap())
{
RedirectLogin();
return;
}
var user = CurrentUser;
var table = new Table();
table.AddHeaderRow(Resources.ChangePassword, 2);
table.AddVerticalSpace(10);
_oldPasswordBox = new TextBox();
_oldPasswordBox.TextMode = TextBoxMode.Password;
_oldPasswordValid = new Label();
table.AddRow(Resources.OldPassword, _oldPasswordBox, _oldPasswordValid);
table.AddVerticalSpace(10);
table.AddRow(string.Empty, Resources.PasswordLength);
_newPassword1Box = new TextBox();
_newPassword1Box.TextMode = TextBoxMode.Password;
_newPassword1Valid = new Label();
table.AddRow(Resources.NewPassword, _newPassword1Box, _newPassword1Valid);
_newPassword2Box = new TextBox();
_newPassword2Box.TextMode = TextBoxMode.Password;
_newPassword2Valid = new Label();
table.AddRow(Resources.RepeatPassword, _newPassword2Box, _newPassword2Valid);
var buttonPanel = new Panel();
var saveButton = new Button();
saveButton.Text = Resources.Save;
saveButton.Click += new EventHandler(SaveButton_Click);
buttonPanel.Controls.Add(saveButton);
var cancelButton = new Button();
cancelButton.Text = Resources.Cancel;
cancelButton.Click += new EventHandler(CancelButton_Click);
buttonPanel.Controls.Add(cancelButton);
table.AddRow(string.Empty, buttonPanel);
this.panel.Controls.Add(table);
}
private void SaveButton_Click(object sender, EventArgs e)
{
bool valid = true;
if (!SetupLdap())
{
RedirectLogin();
return;
}
var user = CurrentUser;
if (!Ldap.TestLogin(Request, user.Nickname, _oldPasswordBox.Text))
{
_oldPasswordValid.Text = Resources.PasswordWrong;
valid = false;
}
else
{
_oldPasswordValid.Text = string.Empty;
}
if (_newPassword1Box.Text.Length < 8)
{
_newPassword1Valid.Text = Resources.PasswordTooShort;
valid = false;
}
else
{
_newPassword1Valid.Text = string.Empty;
}
if (_newPassword2Box.Text != _newPassword1Box.Text)
{
_newPassword2Valid.Text = Resources.PasswordNotMatch;
valid = false;
}
else
{
_newPassword2Valid.Text = string.Empty;
}
if (valid)
{
Connection.SetPassword(user.DN, _newPassword1Box.Text);
BasicGlobal.Logger.Log(LogLevel.Info, "User id {0} name {1} changed password", user.Id, user.Name);
RedirectHome();
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
RedirectHome();
}
}
} | ppschweiz/MemberDatabase | Organigram/MemberService/ChangePassword.aspx.cs | C# | mit | 3,415 |
import * as React from 'react';
import { LangConsumer } from '../LangContext';
import { Schema } from 'jsoninput';
import { infoStyle } from './commonView';
import { css } from 'glamor';
import IconButton from '../Components/IconButton';
interface Translation {
translation: string;
status: string;
}
interface TranslatableProps {
value: {
[code: string]: Translation;
};
onChange: (value: { [code: string]: Translation }) => void;
view: Schema['view'] & {
label?: string;
readOnly: boolean;
};
}
interface EndProps {
value?: string | number;
onChange: (value: string) => void;
view: {};
}
/**
* HOC: Transform a hashmap (lang:value) into value based on current language
* @param Comp
*/
export default function translatable<P extends EndProps>(
Comp: React.ComponentType<P>,
): React.SFC<TranslatableProps & P> {
function Translated(props: TranslatableProps) {
if (!props.value) {
return null;
}
function catchUp(code: string) {
const value = props.value[code] ? props.value[code].translation : '';
const newValue = {
...props.value,
[code]: {
translation: value,
status: '',
},
};
props.onChange(newValue);
}
function outdate(code: string) {
const value = props.value[code] ? props.value[code].translation : '';
const newValue = {
...props.value,
[code]: {
translation: value,
status: 'outdated:manual',
},
};
props.onChange(newValue);
}
function markAsMajor(code: string, allLanguages: { code: string; label: string }[]) {
const newValue = {};
for (const lang of allLanguages) {
newValue[lang.code] = {
translation: props.value[lang.code] ? props.value[lang.code].translation : '',
status: 'outdated:' + code,
};
}
newValue[code].status = '';
props.onChange(newValue);
}
return (
<LangConsumer>
{({ lang, availableLang }) => {
// Updade label
const curCode = (
availableLang.find(l => l.code.toUpperCase() === lang.toUpperCase()) || {
code: '',
}
).code;
let translation;
let status;
if (props.value.hasOwnProperty(lang.toUpperCase())) {
translation = props.value[lang.toUpperCase()].translation;
status = props.value[lang.toUpperCase()].status;
} else if (props.value.hasOwnProperty(lang.toLowerCase())) {
translation = props.value[lang.toLowerCase()].translation;
status = props.value[lang.toLowerCase()].status;
}
const view = {
...props.view,
label: (
<span>
{(props.view || { label: '' }).label}{' '}
<span className={String(infoStyle)}>
[{curCode.toLowerCase()}] {status ? '(' + status + ')' : ''}
</span>
</span>
),
};
if (view.readOnly) {
// variable is protected by the model
const theLanguage = availableLang.find(al => al.code === lang);
if (theLanguage != null && theLanguage.visibility === 'PRIVATE') {
// but this language is not defined by the model
if (
Object.entries(props.value).find(([key, value]) => {
const theLang = availableLang.find(al => al.code === key);
return (
theLang && theLang.visibility !== 'PRIVATE' && value.translation
);
})
) {
view.readOnly = false;
}
}
}
const editor = (
// @ts-ignore https://github.com/Microsoft/TypeScript/issues/28748
<Comp
{...props}
value={translation}
view={view}
onChange={value => {
const theStatus = props.value[lang] ? props.value[lang].status : '';
const v = {
...props.value,
[lang]: {
translation: value,
status: theStatus,
},
};
props.onChange(v);
}}
/>
);
// return editor;
const readOnly = view.readOnly;
const orangeStyle = css({
color: '#F57C00',
});
const greenStyle = css({
color: '#388E3C',
});
const majorButton = !readOnly ? (
<IconButton
icon={[
`fa fa-toggle-on fa-stack-1x ${orangeStyle}`,
`fa fa-expand fa-stack-1x ${css({
transform: 'translate(0, 8px) rotate(45deg)',
})}`,
]}
className={`wegas-advanced-feature ${css({
lineHeight: '1.2em',
})}`}
tooltip="Major update"
onClick={() => {
markAsMajor(curCode, availableLang);
}}
/>
) : (
''
);
const outdateButton = !readOnly ? (
<IconButton
className="wegas-advanced-feature"
icon={[`fa fa-toggle-on ${greenStyle}`]}
tooltip="Mark as outdated "
onClick={() => {
outdate(curCode);
}}
/>
) : (
''
);
if (!props.value[curCode] || !props.value[curCode].status) {
return (
<span>
{editor}
{majorButton}
{outdateButton}
</span>
);
} else {
return (
<span>
{editor}
{majorButton}
{!readOnly ? (
<IconButton
icon={[`fa fa-toggle-on fa-flip-horizontal ${orangeStyle}`]}
className="wegas-advanced-feature"
tooltip="Mark as up-to-date"
onClick={() => {
catchUp(curCode);
}}
/>
) : (
''
)}
</span>
);
}
}}
</LangConsumer>
);
}
return Translated;
}
| Heigvd/Wegas | wegas-app/src/main/node/wegas-react-form/src/HOC/translatable.tsx | TypeScript | mit | 8,590 |
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import web
import simplejson as json
import karesansui
from karesansui.lib.rest import Rest, auth
from karesansui.lib.const import VIRT_COMMAND_APPLY_SNAPSHOT
from karesansui.lib.utils import is_param, is_int
from karesansui.lib.virt.snapshot import KaresansuiVirtSnapshot
from karesansui.db.access.machine import findbyguest1
from karesansui.db.access.snapshot import findbyname_guestby1 as s_findbyname_guestby1
from karesansui.db.access._2pysilhouette import save_job_collaboration
from karesansui.db.access.machine2jobgroup import new as m2j_new
from karesansui.db.model._2pysilhouette import Job, JobGroup
from pysilhouette.command import dict2command
class GuestBy1CurrentSnapshot(Rest):
@auth
def _PUT(self, *param, **params):
(host_id, guest_id) = self.chk_guestby1(param)
if guest_id is None: return web.notfound()
if is_param(self.input, 'id') is False \
or is_int(self.input.id) is False:
return web.badrequest("Request data is invalid.")
snapshot_id = str(self.input.id)
snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
if snapshot is None:
pass
# ignore snapshots that is not in database.
#return web.badrequest("Request data is invalid.")
model = findbyguest1(self.orm, guest_id)
kvs = KaresansuiVirtSnapshot(readonly=False)
snapshot_list = []
try:
domname = kvs.kvc.uuid_to_domname(model.uniq_key)
if not domname: return web.notfound()
self.view.is_creatable = kvs.isSupportedDomain(domname)
try:
snapshot_list = kvs.listNames(domname)[domname]
except:
pass
finally:
kvs.finish()
if not snapshot_id in snapshot_list:
self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
# ignore snapshots that is not in database.
#return web.notfound()
action_cmd = dict2command(
"%s/%s" % (karesansui.config['application.bin.dir'],
VIRT_COMMAND_APPLY_SNAPSHOT),
{"name" : domname, "id" : snapshot_id})
cmdname = 'Apply Snapshot'
_jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
_job = Job('%s command' % cmdname, 0, action_cmd)
_jobgroup.jobs.append(_job)
_machine2jobgroup = m2j_new(machine=model,
jobgroup_id=-1,
uniq_key=karesansui.sheconf['env.uniqkey'],
created_user=self.me,
modified_user=self.me,
)
save_job_collaboration(self.orm,
self.pysilhouette.orm,
_machine2jobgroup,
_jobgroup,
)
self.view.currentsnapshot = snapshot
return web.accepted(url=web.ctx.path)
urls = (
'/host/(\d+)/guest/(\d+)/currentsnapshot/?(\.part)?$', GuestBy1CurrentSnapshot,
)
| karesansui/karesansui | karesansui/gadget/guestby1currentsnapshot.py | Python | mit | 4,377 |
import uglify from 'rollup-plugin-uglify'
import buble from 'rollup-plugin-buble'
export default {
entry: 'js/index.js',
dest: 'public/bundle.js',
format: 'iife',
plugins: [buble(), uglify()],
}
| brbrakus/adomis | rollup.config.js | JavaScript | mit | 204 |
import { SelectableItem, LoadableItem } from '../core/classes';
import { Company, CompanyDetail } from './contracts';
import { StorageItem } from './storage/models';
export class CompanyItem extends SelectableItem {
private _item : Company;
get item() {
return this._item;
}
set item(i : Company) {
this._item = i;
}
constructor(i : Company) {
super();
this._item = i;
this.isOpen = false;
}
private _isOpen : boolean;
get isOpen() {
return !!this._isOpen;
}
set isOpen(val : boolean) {
this._isOpen = val;
}
}
export class CompanyDetailItem extends LoadableItem {
private _item : CompanyDetail;
private _storage : StorageItem[];
constructor(i? : CompanyDetail) {
super();
if(!!i) {
this._item = i;
this.checkLoading();
}
this.isOpen = false;
}
checkLoading() {
if(!!this._item && !!this._storage) this.isLoading = false;
else this.isLoading = true;
}
get item() {
return this._item;
}
set item(i : CompanyDetail) {
this._item = i;
this.checkLoading();
}
get storage() {
return this._storage;
}
set storage(list : StorageItem[]) {
this._storage = list;
this.checkLoading();
}
private _isOpen : boolean;
get isOpen() {
return !!this._isOpen;
}
set isOpen(val : boolean) {
this._isOpen = val;
}
}
| alexiusp/vc-manager | app/corps/models.ts | TypeScript | mit | 1,356 |
function filterSinceSync(d) {
var isValid = typeof d === 'number' ||
d instanceof Number ||
d instanceof Date;
if (!isValid) {
throw new Error('expected since option to be a date or a number');
}
return file.stat && file.stat.mtime > d;
};
module.exports = filterSinceSync; | xareelee/gulp-on-rx | src/filterSinceSync.js | JavaScript | mit | 300 |
var expect = require('chai').expect;
var sinon = require('sinon');
var ColumnShifter = require('component/grid/projection/column-shifter');
var Base = require('component/grid/projection/base');
var Response = require('component/grid/model/response');
describe('projection ColumnShifter', function () {
it('update should run normal', function () {
var model = new ColumnShifter();
var originalData = new Base();
originalData.data = new Response({
columns: {
name: { name: 'hello', property: 'name' },
id: { id: '007', property: 'id' },
},
select: ['name', 'id'],
});
originalData.pipe(model);
expect(model.data.get('select')[0]).to.be.equal('column.skip.less');
expect(model.data.get('select')[3]).to.be.equal('column.skip.more');
});
it('thClick should run normal', function () {
var model = new ColumnShifter();
model.get = sinon.stub().returns(1);
sinon.spy(model, 'set');
model.thClick({}, {
column: { $metadata: { enabled: true } },
property: 'column.skip.less',
});
expect(model.set.calledWith({ 'column.skip': 0 })).to.be.true;
});
});
| steins024/projection-grid | spec/unit/column-shifter-spec.js | JavaScript | mit | 1,152 |
<?php
class Zipbit_Bitcoins_Model_Standard extends Mage_Payment_Model_Method_Abstract {
protected $_code = 'zipbit';
protected $_isInitializeNeeded = true;
protected $_canUseInternal = true;
protected $_canUseForMultishipping = false;
public function getOrderPlaceRedirectUrl() {
return Mage::getUrl('zipbit/payment/redirect', array('_secure' => true));
}
}
?> | macanhhuy/magento-module | app/code/local/Zipbit/Bitcoins/Model/Standard.php | PHP | mit | 399 |
# Stack implementation
class Stack (object):
def __init__ (self):
self.stack = []
def push (self, data):
self.stack.append(data)
def peek (self):
if self.isEmpty():
return None
return self.stack[-1]
def pop (self):
if self.isEmpty():
return None
return self.stack.pop()
def isEmpty (self):
return len(self.stack) == 0
def __str__ (self):
return ' '.join(str(x) for x in self.stack)
| mag6367/Cracking_the_Coding_Interview_Python_Solutions | chapter3/stack.py | Python | mit | 418 |
namespace Toggle.Net
{
/// <summary>
/// Main interface at runtime.
/// </summary>
public interface IToggleChecker
{
/// <summary>
/// Returns <code>true</code> if feature with specified toggle name is enabled,
/// otherwise <code>false</code>.
/// </summary>
/// <param name="toggleName">Name of the toggle</param>
bool IsEnabled(string toggleName);
}
} | Teleopti/Toggle.Net | code/Toggle.Net/IToggleChecker.cs | C# | mit | 375 |
package org.foi.androidworkshop.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.foi.androidworkshop.R;
import org.foi.androidworkshop.models.Pokemon;
import java.util.List;
public class PokemonAdapter extends RecyclerView.Adapter<PokemonAdapter.ViewHolder> {
private List<Pokemon> pokemons;
public PokemonAdapter(List<Pokemon> pokemons) {
this.pokemons = pokemons;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.pokemon_item, parent, false));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.ivPokemonThumbnail.setImageResource(R.mipmap.ic_launcher);
holder.tvPokeName.setText(pokemons.get(position).getName());
holder.tvPokeUrl.setText(pokemons.get(position).getUrl());
}
@Override
public int getItemCount() {
return pokemons.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView ivPokemonThumbnail;
private TextView tvPokeName;
private TextView tvPokeUrl;
public ViewHolder(View itemView) {
super(itemView);
ivPokemonThumbnail = (ImageView) itemView.findViewById(R.id.ivPokeThumbnail);
tvPokeName = (TextView) itemView.findViewById(R.id.tvPokeName);
tvPokeUrl = (TextView) itemView.findViewById(R.id.tvPokeUrl);
}
}
}
| mjurinic/AndroidWorkshop | app/src/main/java/org/foi/androidworkshop/adapters/PokemonAdapter.java | Java | mit | 1,685 |
<?php
namespace App\LoginModule\LTI\Tool;
/**
* Class to represent a tool consumer
*
* @author Stephen P Vickers <stephen@spvsoftwareproducts.com>
* @version 2.5.00
* @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License, version 3
*/
class LTI_Tool_Consumer {
/**
* @var string Local name of tool consumer.
*/
public $name = NULL;
/**
* @var string Shared secret.
*/
public $secret = NULL;
/**
* @var string LTI version (as reported by last tool consumer connection).
*/
public $lti_version = NULL;
/**
* @var string Name of tool consumer (as reported by last tool consumer connection).
*/
public $consumer_name = NULL;
/**
* @var string Tool consumer version (as reported by last tool consumer connection).
*/
public $consumer_version = NULL;
/**
* @var string Tool consumer GUID (as reported by first tool consumer connection).
*/
public $consumer_guid = NULL;
/**
* @var string Optional CSS path (as reported by last tool consumer connection).
*/
public $css_path = NULL;
/**
* @var boolean Whether the tool consumer instance is protected by matching the consumer_guid value in incoming requests.
*/
public $protected = FALSE;
/**
* @var boolean Whether the tool consumer instance is enabled to accept incoming connection requests.
*/
public $enabled = FALSE;
/**
* @var object Date/time from which the the tool consumer instance is enabled to accept incoming connection requests.
*/
public $enable_from = NULL;
/**
* @var object Date/time until which the tool consumer instance is enabled to accept incoming connection requests.
*/
public $enable_until = NULL;
/**
* @var object Date of last connection from this tool consumer.
*/
public $last_access = NULL;
/**
* @var int Default scope to use when generating an Id value for a user.
*/
public $id_scope = LTI_Tool_Provider::ID_SCOPE_ID_ONLY;
/**
* @var string Default email address (or email domain) to use when no email address is provided for a user.
*/
public $defaultEmail = '';
/**
* @var object Date/time when the object was created.
*/
public $created = NULL;
/**
* @var object Date/time when the object was last updated.
*/
public $updated = NULL;
/**
* @var string Consumer key value.
*/
private $key = NULL;
/**
* @var mixed Data connector object or string.
*/
private $data_connector = NULL;
/**
* Class constructor.
*
* @param string $key Consumer key
* @param mixed $data_connector String containing table name prefix, or database connection object, or array containing one or both values (optional, default is MySQL with an empty table name prefix)
* @param boolean $autoEnable true if the tool consumers is to be enabled automatically (optional, default is false)
*/
public function __construct($key = NULL, $data_connector = '', $autoEnable = FALSE) {
$this->data_connector = LTI_Data_Connector::getDataConnector($data_connector);
if (!empty($key)) {
$this->load($key, $autoEnable);
} else {
$this->secret = LTI_Data_Connector::getRandomString(32);
}
}
/**
* Initialise the tool consumer.
*/
public function initialise() {
$this->key = NULL;
$this->name = NULL;
$this->secret = NULL;
$this->lti_version = NULL;
$this->consumer_name = NULL;
$this->consumer_version = NULL;
$this->consumer_guid = NULL;
$this->css_path = NULL;
$this->protected = FALSE;
$this->enabled = FALSE;
$this->enable_from = NULL;
$this->enable_until = NULL;
$this->last_access = NULL;
$this->id_scope = LTI_Tool_Provider::ID_SCOPE_ID_ONLY;
$this->defaultEmail = '';
$this->created = NULL;
$this->updated = NULL;
}
/**
* Save the tool consumer to the database.
*
* @return boolean True if the object was successfully saved
*/
public function save() {
return $this->data_connector->Tool_Consumer_save($this);
}
/**
* Delete the tool consumer from the database.
*
* @return boolean True if the object was successfully deleted
*/
public function delete() {
return $this->data_connector->Tool_Consumer_delete($this);
}
/**
* Get the tool consumer key.
*
* @return string Consumer key value
*/
public function getKey() {
return $this->key;
}
/**
* Get the data connector.
*
* @return mixed Data connector object or string
*/
public function getDataConnector() {
return $this->data_connector;
}
/**
* Is the consumer key available to accept launch requests?
*
* @return boolean True if the consumer key is enabled and within any date constraints
*/
public function getIsAvailable() {
$ok = $this->enabled;
$now = time();
if ($ok && !is_null($this->enable_from)) {
$ok = $this->enable_from <= $now;
}
if ($ok && !is_null($this->enable_until)) {
$ok = $this->enable_until > $now;
}
return $ok;
}
/**
* Add the OAuth signature to an LTI message.
*
* @param string $url URL for message request
* @param string $type LTI message type
* @param string $version LTI version
* @param array $params Message parameters
*
* @return array Array of signed message parameters
*/
public function signParameters($url, $type, $version, $params) {
if (!empty($url)) {
// Check for query parameters which need to be included in the signature
$query_params = array();
$query_string = parse_url($url, PHP_URL_QUERY);
if (!is_null($query_string)) {
$query_items = explode('&', $query_string);
foreach ($query_items as $item) {
if (strpos($item, '=') !== FALSE) {
list($name, $value) = explode('=', $item);
$query_params[urldecode($name)] = urldecode($value);
} else {
$query_params[urldecode($item)] = '';
}
}
}
$params = $params + $query_params;
// Add standard parameters
$params['lti_version'] = $version;
$params['lti_message_type'] = $type;
$params['oauth_callback'] = 'about:blank';
// Add OAuth signature
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$consumer = new OAuthConsumer($this->getKey(), $this->secret, NULL);
$req = OAuthRequest::from_consumer_and_token($consumer, NULL, 'POST', $url, $params);
$req->sign_request($hmac_method, $consumer, NULL);
$params = $req->get_parameters();
// Remove parameters being passed on the query string
foreach (array_keys($query_params) as $name) {
unset($params[$name]);
}
}
return $params;
}
###
### PRIVATE METHOD
###
/**
* Load the tool consumer from the database.
*
* @param string $key The consumer key value
* @param boolean $autoEnable True if the consumer should be enabled (optional, default if false)
*
* @return boolean True if the consumer was successfully loaded
*/
private function load($key, $autoEnable = FALSE) {
$this->initialise();
$this->key = $key;
$ok = $this->data_connector->Tool_Consumer_load($this);
if (!$ok) {
$this->enabled = $autoEnable;
}
return $ok;
}
} | France-ioi/login-module | app/LoginModule/LTI/Tool/LTI_Tool_Consumer.php | PHP | mit | 7,122 |
<?php
namespace Budgeit;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
protected $fillable = [
'name', 'status', 'amount', 'type'
];
public function user() {
return $this->belongsTo(User::class);
}
public function categories() {
return $this->hasMany(Category::class);
}
public function category() {
return $this->belongsTo(Category::class);
}
public function currency() {
return $this->belongsTo(Currency::class);
}
}
| syntacticNaCl/budgeit | app/Transaction.php | PHP | mit | 534 |
require_relative File.join 'support', 'coverage'
require_relative File.join '..', 'lib', 'arukamo'
subject = Object.new
fail unless subject.aru? === true
fail unless subject.nai? === false
| cyril/arukamo.rb | test/test_object.rb | Ruby | mit | 191 |
#!/usr/bin/env python
import os,sys
folder = "/media/kentir1/Development/Linux_Program/Fundkeep/"
def makinGetYear():
return os.popen("date +'%Y'").read()[:-1]
def makinGetMonth():
return os.popen("date +'%m'").read()[:-1]
def makinGetDay():
return os.popen("date +'%d'").read()[:-1]
def makinGetPrevYear(daypassed):
return os.popen("date --date='"+str(daypassed)+" day ago' +'%Y'").read()[:-1]
def makinGetPrevMonth(daypassed):
return os.popen("date --date='"+str(daypassed)+" day ago' +'%m'").read()[:-1]
def makinGetPrevDay(daypassed):
return os.popen("date --date='"+str(daypassed)+" day ago' +'%d'").read()[:-1]
#last entry
f = open(folder+"data/last_entry","r")
le = f.read()
le_y=le[:4]
le_m=le[4:6]
le_d=le[6:]
#input
os.system("gedit "+folder+"var/input")
f = open(folder+"var/input","r")
data = f.read()
f.close()
balance_out = int(data[:data.find(" ")])
balance_ket = data[data.find(" ")+1:-1]
print balance_ket
os.system("mkdir "+folder+"data")
os.system("mkdir "+folder+"data/"+makinGetYear())
os.system("mkdir "+folder+"data/"+makinGetYear()+"/"+makinGetMonth())
os.system("mkdir "+folder+"data/"+makinGetYear()+"/"+makinGetMonth()+"/"+makinGetDay())
balance_before = 0
#ambil balance dr hari sebelumnya
dapet = 0
while (dapet == 0):
dpassed = 1
try:
f = open(folder+"data/"
+makinGetPrevYear(dpassed)
+"/"
+makinGetPrevMonth(dpassed)
+"/"
+makinGetPrevDay(dpassed)
+"/balance_after","r")
if (makinGetDay()=="01"):
t_day = 31
t_bulan = ("0"+str(int(makinGetMonth())-1))[-2:]
t_tahun = makinGetYear()
if (int(makinGetMonth())=1):
t_bulan = 12
t_tahun = makinGetYear()-1
print t_bulan
dapet = 0
while (dapet==0):
try:
f = open(folder+"data/"+t_tahun+"/"+t_bulan+"/"+("0"+str(t_day))[-2:]+"/balance_after","r")
print t_day
dapet = 1
balance_before = int(f.read())
except:
t_day = t_day - 1
f.close()
else:
t_day = int(makinGetDay())-1
#~ t_bulan = ("0"+str(int(makinGetMonth())))[-2:]
t_bulan = makinGetMonth()
f = open(folder+"data/"+makinGetYear()+"/"+t_bulan+"/"+("0"+str(t_day))[-2:]+"/balance_after","r")
balance_before = int(f.read())
#bila fresh input
try:
f = open(folder+"data/"+t_tahun+"/"+t_bulan+"/"+("0"+str(t_day))[-2:]+"/balance_after","r")
except:
#bila hanya mengupdate isi balance_out (pengeluaran hari ini)
| imakin/PersonalAssistant | Fundkeep/modul/b__main_backu.py | Python | mit | 2,347 |
module Usb
def self.devices(conditions={})
get_device_list.select { |d| d.match?(conditions) }
end
def get_device_list(context=nil); end # Source code is in rusb.c.
end
class Usb::Device
def initialize
raise NotImplementedError, "To get a Usb::Device object, use Usb::get_device_list"
end
def bus_number; end # Source code is in rusb.c
def address; end # Source code is in rusb.c
def max_packet_size(endpoint_number); end # Source code is in rusb.c
def max_iso_packet_size(endpoint_number); end
def closed?; end # Source code is in rusb.c
def close; end # Source code is in rusb.c
def eql?(other); end # Source code in rusb.c
def get_config_descriptor_binary(index); end # Souce code is in rusb.c
private
def get_device_descriptor; end # Source code is in rusb.c
public
def unref
close
end
def device_descriptor
# TODO: move this function to DeviceHandle to make it
# portable to Windows? OR try to do this:
# http://www.osronline.com/showthread.cfm?link=207549
@device_descriptor ||= get_device_descriptor
end
def vendor_id
device_descriptor.idVendor
end
def product_id
device_descriptor.idProduct
end
def revision_bcd
device_descriptor.bcdDevice
end
def device_class
device_descriptor.bDeviceClass
end
def device_subclass
device_descriptor.bDeviceSubClass
end
def device_protocol
device_descriptor.bDeviceProtocol
end
def revision_bcd
device_descriptor.bcdDevice
end
def revision
self.class.revision_bcd_to_string(revision_bcd)
end
def self.revision_bcd_to_string(revision_bcd)
"%X.%02X" % [revision_bcd >> 8, revision_bcd & 0xFF]
end
def serial_number
open_handle do |handle|
handle.string_descriptor device_descriptor.iSerialNumber
end
end
def ==(other)
eql?(other)
end
def ===(other)
eql?(other)
end
def same_device_as?(other)
bus_number == other.bus_number && address == other.address
end
def match?(conditions)
conditions.each do |method_name, value|
return false if send(method_name) != value
end
return true
end
def open_handle(&block)
Usb::DeviceHandle.open self, &block
end
end
| DavidEGrayson/ruby-usb-pro | lib/ruby-usb-pro/device.rb | Ruby | mit | 2,250 |
/**
*/
package es.um.nosql.streaminginference.NoSQLSchema.impl;
import es.um.nosql.streaminginference.NoSQLSchema.NoSQLSchemaPackage;
import es.um.nosql.streaminginference.NoSQLSchema.PrimitiveType;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Primitive Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link es.um.nosql.streaminginference.NoSQLSchema.impl.PrimitiveTypeImpl#getName <em>Name</em>}</li>
* </ul>
*
* @generated
*/
public class PrimitiveTypeImpl extends TypeImpl implements PrimitiveType {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final long serialVersionUID = 6870693875L;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PrimitiveTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return NoSQLSchemaPackage.Literals.PRIMITIVE_TYPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
return getName();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
setName((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
setName(NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //PrimitiveTypeImpl
| catedrasaes-umu/NoSQLDataEngineering | projects/es.um.nosql.streaminginference/src/es/um/nosql/streaminginference/NoSQLSchema/impl/PrimitiveTypeImpl.java | Java | mit | 3,672 |
package com.chariotinstruments.markets;
import java.util.ArrayList;
/**
* Created by user on 1/30/16.
*/
public class CalcRSI {
private MarketDay marketDay;
private ArrayList<MarketCandle> marketCandles;
private double gainAverage;
private double lossAverage;
public CalcRSI(MarketDay marDay){
this.marketDay = marDay;
marketCandles = new ArrayList<MarketCandle>();
marketCandles = this.marketDay.getMarketCandles();
}
public double getGainAverage(){
return gainAverage;
}
public double getLossAverage(){
return lossAverage;
}
public double getCurrentRSI(){
double RSI = 0.0;
if(marketCandles.size()>1) {
getFirstAverages();
RSI = getRSI(gainAverage, lossAverage);
}
return RSI;
}
public void getFirstAverages(){
double curAmount = 0.0;
double prevAmount = 0.0;
double sum = 0.0;
double lastAmount = 0.0;
for(int i = 1; i < 15; i++) { //start from the beginning to get the first SMA
curAmount = marketCandles.get(i).getClose();
prevAmount = marketCandles.get(i-1).getClose();
sum = curAmount - prevAmount;
if(sum < 0){
lossAverage += (sum * -1);
}else{
gainAverage += sum;
}
}
lossAverage = lossAverage / 14;
gainAverage = gainAverage / 14;
getSmoothAverages(lossAverage, gainAverage);
}
public void getSmoothAverages(double lossAvg, double gainAvg){
double curAmount = 0.0;
double prevAmount = 0.0;
double lastAmount = 0.0;
//loop through the remaining amounts in the marketDay and calc the smoothed avgs
for(int i = 15; i < marketCandles.size(); i++){
curAmount = marketCandles.get(i).getClose();
prevAmount = marketCandles.get(i-1).getClose();
lastAmount = curAmount - prevAmount;
if(lastAmount < 0) {
lossAvg = ((lossAvg * 13) + (lastAmount * -1)) / 14;
gainAvg = ((gainAvg * 13) + 0) / 14;
}else{
lossAvg = ((lossAvg * 13) + 0) / 14;
gainAvg = ((gainAvg * 13) + lastAmount) / 14;
}
}
lossAverage = lossAvg;
gainAverage = gainAvg;
}
private double getRSI(double avgGain, double avgLoss){
double RS = avgGain/avgLoss;
double RSI = 0;
if(avgLoss > 0) {
RSI = (100 - (100 / (1 + RS)));
}else{
RSI = 100;
}
return RSI;
}
public String tester(){
String output = "";
for(int i = 0; i < marketCandles.size(); i++){
output = output + "\n" + Double.toString(marketCandles.get(i).getClose());
}
return output;
}
}
| mikemey01/Markets | app/src/main/java/com/chariotinstruments/markets/CalcRSI.java | Java | mit | 2,899 |
module Chotu
VERSION = "0.0.1"
end
| nishantmodak/chotu | lib/chotu/version.rb | Ruby | mit | 37 |
'use strict';
let TimeseriesShowController = function($scope, $controller, $timeout,
NpolarApiSecurity, NpolarTranslate,
npdcAppConfig,
Timeseries, TimeseriesModel, TimeseriesCitation, google, Sparkline) {
'ngInject';
let ctrl = this;
ctrl.authors = (t) => {
return t.authors.map(a => {
return { name: a['@id']};
});
};
// @todo NpolarLinkModel?
ctrl.collection_link = (links,hreflang='en') => {
return links.find(l => l.rel === 'collection' && l.hreflang === hreflang);
};
$controller("NpolarBaseController", {$scope: $scope});
$scope.resource = Timeseries;
let chartElement = Sparkline.getElement();
if (chartElement) {
chartElement.innerHTML = '';
}
$scope.show().$promise.then(timeseries => {
$scope.data = timeseries.data;
$scope.data_not_null = timeseries.data.filter(t => t.value !== undefined);
// Create facet-style links with counts to timeseries with all of the same keywords...
if (!$scope.keywords && timeseries.keywords && timeseries.keywords.length > 0) {
$scope.keywords = {};
let keywords = TimeseriesModel.keywords(timeseries);
['en', 'no'].forEach(l => {
let k = keywords[l];
let href = $scope.resource.uiBase+`?filter-keywords.@value=${ k.join(',') }`;
let link = { keywords: keywords[l], count: 0, href };
Timeseries.feed({"filter-keywords.@value": k.join(','), facets: 'keywords,species,locations.placename', limit: 0}).$promise.then((r) => {
link.count = r.feed.opensearch.totalResults; // All keywords
// Count for all keywords + species
if (timeseries.species) {
let f = r.feed.facets.find(f => f.hasOwnProperty('species'));
if (f && f.species) {
let c = f.species.find(f => f.term === timeseries.species);
link.count_keywords_and_species = c.count;
}
}
// Count for first all keywords + placename[0]
if (timeseries.locations && timeseries.locations.length > 0) {
let f = r.feed.facets.find(f => f.hasOwnProperty('locations.placename'));
if (f && f['locations.placename']) {
let c = f['locations.placename'].find(f => f.term === timeseries.locations[0].placename);
link.count_keywords_and_placename = c.count;
}
}
$scope.keywords[l] = link;
}, (e) => {
$scope.keywords[l] = link;
});
});
}
$scope.citation = (t) => {
if (!t) { return; }
return TimeseriesCitation.citation(timeseries);
};
// Create graph
if ($scope.data && $scope.data.length > 0) {
$timeout(function(){
$scope.sparkline = true;
let sparkline = timeseries.data.map(d => [d.value]);
google.setOnLoadCallback(Sparkline.draw(sparkline));
});
}
// Count number of timeseries belonging to the same collection
if (timeseries.links && timeseries.links.length > 0) {
['en', 'nb'].forEach(l => {
if (!$scope.collection || !$scope.collection[l]) {
let link = ctrl.collection_link(timeseries.links, l);
if (link && link.href) {
let query = {"filter-links.href": link.href, limit: 0 };
Timeseries.feed(query).$promise.then(r => {
if (!$scope.collection) {
$scope.collection = {};
}
$scope.collection[l] = { href: $scope.resource.uiBase+`?filter-links.href=${link.href}`,
title: link.title,
count: r.feed.opensearch.totalResults
};
});
}
}
});
}
});
};
module.exports = TimeseriesShowController;
| npolar/npdc-indicator | src/indicator-timeseries/TimeseriesShowController.js | JavaScript | mit | 3,741 |
package main.java.meterstanden.domain;
import java.io.IOException;
import java.util.List;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import com.google.gson.Gson;
import main.java.meterstanden.hibernate.HibernateUtil;
/**
* Servlet implementation class JaaroverzichtDomain
*/
@WebServlet(
description = "Get the yearly overview",
urlPatterns = {
"/Jaaroverzicht",
"/JAAROVERZICHT",
"/jaaroverzicht"
}
)
public class JaaroverzichtDomain extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(JaaroverzichtDomain.class);
/**
* @see HttpServlet#HttpServlet()
*/
public JaaroverzichtDomain() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("Getting the jaarverbruik.");
Session session = HibernateUtil.getSessionFactory().openSession();
StringBuilder hql = new StringBuilder();
hql.append("from Jaarverbruik");
Query q = session.createQuery(hql.toString());
List<?> rl = q.getResultList();
Gson gson = new Gson();
response.getWriter().append(gson.toJson(rl));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| borrob/Meterstanden | src/main/java/meterstanden/domain/JaaroverzichtDomain.java | Java | mit | 1,867 |
import { Box, Col } from '@tlon/indigo-react';
import { arrToString, Association, FlatGraph, FlatGraphNode, Group } from '@urbit/api';
import bigInt from 'big-integer';
import React from 'react';
import { RouteComponentProps, useHistory } from 'react-router';
import { resourceFromPath } from '~/logic/lib/group';
import { keyEq, ThreadScroller } from '~/views/components/ThreadScroller';
import PostItem from './PostItem/PostItem';
import PostInput from './PostInput';
import useGraphState, { GraphState } from '~/logic/state/graph';
const virtualScrollerStyle = {
height: '100%'
};
interface PostFeedProps {
flatGraph: FlatGraph;
graphPath: string;
getDeepOlderThan: GraphState['getDeepOlderThan'];
history: RouteComponentProps['history'];
baseUrl: string;
parentNode?: FlatGraphNode;
association: Association;
group: Group;
vip: string;
pendingSize: number;
isThread: boolean;
}
class PostFlatFeed extends React.Component<PostFeedProps, {}> {
isFetching: boolean;
constructor(props) {
super(props);
this.isFetching = false;
this.fetchPosts = this.fetchPosts.bind(this);
this.doNotFetch = this.doNotFetch.bind(this);
}
// eslint-disable-next-line max-lines-per-function
renderItem = React.forwardRef<HTMLDivElement, any>(({ index, scrollWindow }, ref) => {
const {
flatGraph,
graphPath,
history,
baseUrl,
association,
group,
vip,
isThread
} = this.props;
const node = flatGraph.get(index);
const parentNode = index.length > 1 ?
flatGraph.get(index.slice(0, index.length - 1)) : null;
if (!node) {
return null;
}
const key = arrToString(index);
const first = flatGraph.peekLargest()?.[0];
const last = flatGraph.peekSmallest()?.[0];
const isLast = last ? keyEq(index, last) : false;
if (keyEq(index, (first ?? [bigInt.zero]))) {
if (isThread) {
return (
<Col
pt={3}
width="100%"
alignItems="center"
key={key}
ref={ref}
>
<PostItem
node={node}
graphPath={graphPath}
association={association}
index={index}
baseUrl={baseUrl}
history={history}
parentPost={parentNode?.post}
isReply={index.length > 1}
isRelativeTime={true}
vip={vip}
group={group}
isThread={isThread}
isLast={isLast}
/>
</Col>
);
}
return (
<Col
width="100%"
alignItems="center"
key={key}
ref={ref}
>
<Col
width="100%"
maxWidth="608px"
pt={3}
pl={1}
pr={1}
mb={3}
>
<PostInput
group={group}
association={association}
vip={vip}
graphPath={graphPath}
/>
</Col>
<PostItem
node={node}
graphPath={graphPath}
association={association}
index={index}
baseUrl={baseUrl}
history={history}
parentPost={parentNode?.post}
isReply={index.length > 1}
isRelativeTime={true}
vip={vip}
group={group}
/>
</Col>
);
}
return (
<Box key={key} ref={ref}>
<PostItem
node={node}
graphPath={graphPath}
association={association}
index={index}
baseUrl={baseUrl}
history={history}
parentPost={parentNode?.post}
isReply={index.length > 1}
isRelativeTime={true}
vip={vip}
group={group}
isThread={isThread}
isLast={isLast}
/>
</Box>
);
});
async fetchPosts(newer) {
const { flatGraph, graphPath, getDeepOlderThan } = this.props;
const graphResource = resourceFromPath(graphPath);
if (this.isFetching) {
return false;
}
this.isFetching = true;
const { ship, name } = graphResource;
const currSize = flatGraph.size;
if (newer) {
return true;
} else {
const [index] = flatGraph.peekSmallest();
if (index && index.length > 0) {
await getDeepOlderThan(ship, name, 100, index[0].toString());
}
}
this.isFetching = false;
return currSize === flatGraph.size;
}
async doNotFetch(newer) {
return true;
}
render() {
const {
flatGraph,
pendingSize,
history
} = this.props;
return (
<Col width="100%" height="100%" position="relative">
<ThreadScroller
key={history.location.pathname}
origin="top"
offset={0}
data={flatGraph}
averageHeight={80}
size={flatGraph.size}
style={virtualScrollerStyle}
pendingSize={pendingSize}
renderer={this.renderItem}
loadRows={this.doNotFetch}
/>
</Col>
);
}
}
export default React.forwardRef<PostFlatFeed, Omit<PostFeedProps, 'history' | 'getDeepOlderThan'>>(
(props, ref) => {
const history = useHistory();
const getDeepOlderThan = useGraphState(s => s.getDeepOlderThan);
return (
<PostFlatFeed
ref={ref}
{...props}
history={history}
getDeepOlderThan={getDeepOlderThan}
/>
);
});
| urbit/urbit | pkg/interface/src/views/landscape/components/Home/Post/PostFlatFeed.tsx | TypeScript | mit | 5,543 |
class CreatePeople < ActiveRecord::Migration
def change
create_table :people do |t|
t.string :name
t.text :books
t.text :cars
t.timestamps
end
end
end
| joshblour/nested_store_attributes | test/dummy/db/migrate/20141016114846_create_people.rb | Ruby | mit | 188 |
# Created by PyCharm Community Edition
# User: Kaushik Talukdar
# Date: 22-03-2017
# Time: 03:52 PM
#python doesn't allow you to mix strings and numbers directly. numbers must be converted to strings
age = 28
print("Greetings on your " + str(age) + "th birthday") | KT26/PythonCourse | 1. Getting Started/11.py | Python | mit | 322 |
# This handy simplification is adapted from SphinxSearch (thanks)
# and originally came from Ultrasphinx
# it saves us a lot of including and bodging to make will_paginate's template calls work in the Page model
module Radiant
module Pagination
class LinkRenderer < WillPaginate::LinkRenderer
def initialize(tag)
@tag = tag
end
def to_html
links = @options[:page_links] ? windowed_links : []
links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:previous_label])
links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label])
html = links.join(@options[:separator])
@options[:container] ? %{<div class="pagination">#{html}</div>} : html
end
def page_link(page, text, attributes = {})
linkclass = %{ class="#{attributes[:class]}"} if attributes[:class]
linkrel = %{ rel="#{attributes[:rel]}"} if attributes[:rel]
%Q{<a href="#{@tag.locals.page.url}?p=#{page}"#{linkrel}#{linkclass}>#{text}</a>}
end
def page_span(page, text, attributes = {})
%{<span class="#{attributes[:class]}">#{text}</span>}
end
end
end
end | joshfrench/radiant | lib/radiant/pagination/link_renderer.rb | Ruby | mit | 1,236 |
# -*- coding: utf-8 -*-
from cachy import CacheManager
from cachy.serializers import PickleSerializer
class Cache(CacheManager):
_serializers = {
'pickle': PickleSerializer()
}
| sdispater/orator-cache | orator_cache/cache.py | Python | mit | 197 |
using System;
using Newtonsoft.Json;
namespace VkNet.Model
{
/// <summary>
/// API Level object.
/// </summary>
[Serializable]
public class SecureLevel
{
/// <summary>
/// Level
/// </summary>
[JsonProperty("level")]
public int? LevelCode { get; set; }
/// <summary>
/// User ID
/// </summary>
[JsonProperty("uid")]
public ulong? Uid { get; set; }
}
} | vknet/vk | VkNet/Model/SecureLevel.cs | C# | mit | 380 |
/**
* @file wavedrom.hpp
* @author Jeramie Vens
* @date March 7, 2016: Initial version
* @brief This is the main include for the Wavedrom C++ Library
*
*/
#ifndef WAVEDROM_HPP
#define WAVEDROM_HPP
#include "../libwavedrom/group.hpp"
#include "../libwavedrom/signal.hpp"
/**
* @brief The Wavedrom Library encases all of its code in the wavedrom namespace.
*/
namespace wavedrom
{
/**
* @brief A wavedrom object.
* @details The wavedrom object is the main entry point of the wavedrom
* library. It encapsulates all the supported features of
* Wavedrom.
*/
class Wavedrom : public Group
{
public:
/**
* @brief Create a new wavedrom object.
*/
Wavedrom();
virtual ~Wavedrom();
/**
* @brief Export this wavedrom object to a Wavedrom JSON format
* @details This will allocate a new c string containing a valid
* Wavedrom JSON formmated descrption of this waveform.
* The exported JSON description can be converted to an
* image using http://wavedrom.com/editor.html
* @return An allocated cstring that contains the JSON object.
*/
char * Export();
};
}
#endif
| drahosj/308labs | lab-08/Scheduler/libwavedrom/wavedrom.hpp | C++ | mit | 1,202 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using NetOffice;
using Office = NetOffice.OfficeApi;
using Excel = NetOffice.AccessApi;
using NetOffice.AccessApi.Enums;
namespace COMAddinTaskPaneExampleCS4
{
public partial class SampleControl : UserControl
{
List<Customer> _customers;
public SampleControl()
{
InitializeComponent();
LoadSampleCustomerData();
UpdateSearchResult();
}
#region Private Methods
private void LoadSampleCustomerData()
{
_customers = new List<Customer>();
string embeddedCustomerXmlContent = ReadString("SampleData.CustomerData.xml");
XmlDocument document = new XmlDocument();
document.LoadXml(embeddedCustomerXmlContent);
foreach (XmlNode customerNode in document.DocumentElement.ChildNodes)
{
int id = Convert.ToInt32(customerNode.Attributes["ID"].Value);
string name = customerNode.Attributes["Name"].Value;
string company = customerNode.Attributes["Company"].Value;
string city = customerNode.Attributes["City"].Value;
string postalCode = customerNode.Attributes["PostalCode"].Value;
string country = customerNode.Attributes["Country"].Value;
string phone = customerNode.Attributes["Phone"].Value;
_customers.Add(new Customer(id, name, company, city, postalCode, country, phone));
}
}
private string ReadString(string ressourcePath)
{
System.IO.Stream ressourceStream = null;
System.IO.StreamReader textStreamReader = null;
try
{
Assembly assembly = typeof(Addin).Assembly;
ressourceStream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + ressourcePath);
if (ressourceStream == null)
throw (new System.IO.IOException("Error accessing resource Stream."));
textStreamReader = new System.IO.StreamReader(ressourceStream);
if (textStreamReader == null)
throw (new System.IO.IOException("Error accessing resource File."));
string text = textStreamReader.ReadToEnd();
return text;
}
catch (Exception exception)
{
throw (exception);
}
finally
{
if (null != textStreamReader)
textStreamReader.Close();
if (null != ressourceStream)
ressourceStream.Close();
}
}
private void UpdateSearchResult()
{
listViewSearchResults.Items.Clear();
foreach (Customer item in _customers)
{
if (item.Name.IndexOf(textBoxSearch.Text.Trim(), StringComparison.InvariantCultureIgnoreCase) > -1)
{
ListViewItem viewItem = listViewSearchResults.Items.Add("");
viewItem.SubItems.Add(item.ID.ToString());
viewItem.SubItems.Add(item.Name);
viewItem.ImageIndex = 0;
viewItem.Tag = item;
}
}
}
private void UpdateDetails()
{
if (listViewSearchResults.SelectedItems.Count > 0)
{
Customer selectedCustomer = listViewSearchResults.SelectedItems[0].Tag as Customer;
propertyGridDetails.SelectedObject = selectedCustomer;
}
else
propertyGridDetails.SelectedObject = null;
}
#endregion
#region UI Trigger
private void listViewSearchResults_DoubleClick(object sender, EventArgs e)
{
try
{
if (listViewSearchResults.SelectedItems.Count > 0)
{
// any action...
}
}
catch (Exception exception)
{
MessageBox.Show(this, exception.Message, "An error occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void listViewSearchResults_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
try
{
UpdateDetails();
}
catch (Exception exception)
{
MessageBox.Show(this, exception.Message, "An error occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void textBoxSearch_TextChanged(object sender, EventArgs e)
{
try
{
UpdateSearchResult();
UpdateDetails();
}
catch (Exception exception)
{
MessageBox.Show(this, exception.Message, "An error occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
}
}
| NetOfficeFw/NetOffice | Examples/Access/C#/IExtensibility COMAddin Examples/TaskPane/SampleControl.cs | C# | mit | 5,276 |
package PathFinder_2;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Main extends JFrame{
private static final long serialVersionUID = 1L;
private final String TITLE = "ArenaGame";
private MouseEvents mouseEvent = new MouseEvents();
private KeyEvents keyEvent = new KeyEvents();
public static Display display;
public static int WIDTH,HEIGHT,gameIs;
public static boolean isRunning;
public static boolean fullScreen=true;
public static Mapa[][] map;
public static int block=40;
public static boolean onlyGoal,findGoal,removedPossibles;
public static int[] goal = null;
public static int[] start = null;
public static void main(String[] args) {
Main game = new Main();
game.init();
display.start();
Main.newGame();
};
private void init(){
Main.WIDTH =800;
Main.HEIGHT =600;
this.setResizable(true);
if(Main.fullScreen){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Main.WIDTH = (int)screenSize.getWidth();
Main.HEIGHT = (int)screenSize.getHeight();
this.setResizable(false);
this.setExtendedState(Frame.MAXIMIZED_BOTH);
this.setUndecorated(true);
}
display=new Display();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(display);
this.pack();
this.setTitle(TITLE);
this.setVisible(true);
display.addMouseListener(mouseEvent);
display.addKeyListener(keyEvent);
};
public static void newGame(){
Main.goal=Main.start=null;
Main.onlyGoal=Main.findGoal=removedPossibles=true;
Mapa.create((int)Main.HEIGHT/Main.block,(int)Main.WIDTH/Main.block);
//Mapa.create(5,5);
}
}
| G43riko/Java | PathFinder/src/PathFinder_2/Main.java | Java | mit | 1,742 |
// Template Source: BaseEntityRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.ActivityBasedTimeoutPolicy;
import com.microsoft.graph.models.DirectoryObject;
import com.microsoft.graph.models.ExtensionProperty;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Activity Based Timeout Policy Request.
*/
public class ActivityBasedTimeoutPolicyRequest extends BaseRequest<ActivityBasedTimeoutPolicy> {
/**
* The request for the ActivityBasedTimeoutPolicy
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public ActivityBasedTimeoutPolicyRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, ActivityBasedTimeoutPolicy.class);
}
/**
* Gets the ActivityBasedTimeoutPolicy from the service
*
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> getAsync() {
return sendAsync(HttpMethod.GET, null);
}
/**
* Gets the ActivityBasedTimeoutPolicy from the service
*
* @return the ActivityBasedTimeoutPolicy from the request
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public ActivityBasedTimeoutPolicy get() throws ClientException {
return send(HttpMethod.GET, null);
}
/**
* Delete this item from the service
*
* @return a future with the deletion result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> deleteAsync() {
return sendAsync(HttpMethod.DELETE, null);
}
/**
* Delete this item from the service
* @return the resulting response if the service returns anything on deletion
*
* @throws ClientException if there was an exception during the delete operation
*/
@Nullable
public ActivityBasedTimeoutPolicy delete() throws ClientException {
return send(HttpMethod.DELETE, null);
}
/**
* Patches this ActivityBasedTimeoutPolicy with a source
*
* @param sourceActivityBasedTimeoutPolicy the source object with updates
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> patchAsync(@Nonnull final ActivityBasedTimeoutPolicy sourceActivityBasedTimeoutPolicy) {
return sendAsync(HttpMethod.PATCH, sourceActivityBasedTimeoutPolicy);
}
/**
* Patches this ActivityBasedTimeoutPolicy with a source
*
* @param sourceActivityBasedTimeoutPolicy the source object with updates
* @return the updated ActivityBasedTimeoutPolicy
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public ActivityBasedTimeoutPolicy patch(@Nonnull final ActivityBasedTimeoutPolicy sourceActivityBasedTimeoutPolicy) throws ClientException {
return send(HttpMethod.PATCH, sourceActivityBasedTimeoutPolicy);
}
/**
* Creates a ActivityBasedTimeoutPolicy with a new object
*
* @param newActivityBasedTimeoutPolicy the new object to create
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> postAsync(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) {
return sendAsync(HttpMethod.POST, newActivityBasedTimeoutPolicy);
}
/**
* Creates a ActivityBasedTimeoutPolicy with a new object
*
* @param newActivityBasedTimeoutPolicy the new object to create
* @return the created ActivityBasedTimeoutPolicy
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public ActivityBasedTimeoutPolicy post(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) throws ClientException {
return send(HttpMethod.POST, newActivityBasedTimeoutPolicy);
}
/**
* Creates a ActivityBasedTimeoutPolicy with a new object
*
* @param newActivityBasedTimeoutPolicy the object to create/update
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<ActivityBasedTimeoutPolicy> putAsync(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) {
return sendAsync(HttpMethod.PUT, newActivityBasedTimeoutPolicy);
}
/**
* Creates a ActivityBasedTimeoutPolicy with a new object
*
* @param newActivityBasedTimeoutPolicy the object to create/update
* @return the created ActivityBasedTimeoutPolicy
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public ActivityBasedTimeoutPolicy put(@Nonnull final ActivityBasedTimeoutPolicy newActivityBasedTimeoutPolicy) throws ClientException {
return send(HttpMethod.PUT, newActivityBasedTimeoutPolicy);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public ActivityBasedTimeoutPolicyRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public ActivityBasedTimeoutPolicyRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
}
| microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/ActivityBasedTimeoutPolicyRequest.java | Java | mit | 6,648 |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Diagnostics;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osuTK;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Localisation;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class DrawableMostPlayedBeatmap : CompositeDrawable
{
private const int cover_width = 100;
private const int corner_radius = 6;
private readonly APIUserMostPlayedBeatmap mostPlayed;
public DrawableMostPlayedBeatmap(APIUserMostPlayedBeatmap mostPlayed)
{
this.mostPlayed = mostPlayed;
RelativeSizeAxes = Axes.X;
Height = 50;
Masking = true;
CornerRadius = corner_radius;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
AddRangeInternal(new Drawable[]
{
new UpdateableOnlineBeatmapSetCover(BeatmapSetCoverType.List)
{
RelativeSizeAxes = Axes.Y,
Width = cover_width,
BeatmapSet = mostPlayed.BeatmapSet,
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Left = cover_width - corner_radius },
Children = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
CornerRadius = corner_radius,
Children = new Drawable[]
{
new MostPlayedBeatmapContainer
{
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding(10),
Children = new Drawable[]
{
new FillFlowContainer
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new MostPlayedBeatmapMetadataContainer(mostPlayed.BeatmapInfo),
new LinkFlowContainer(t =>
{
t.Font = OsuFont.GetFont(size: 12, weight: FontWeight.Regular);
t.Colour = colourProvider.Foreground1;
})
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
}.With(d =>
{
d.AddText("mapped by ");
d.AddUserLink(mostPlayed.BeatmapSet.Author);
}),
}
},
new PlayCountText(mostPlayed.PlayCount)
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight
},
}
},
}
}
}
}
}
});
}
private class MostPlayedBeatmapContainer : ProfileItemContainer
{
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
IdleColour = colourProvider.Background4;
HoverColour = colourProvider.Background3;
}
}
private class MostPlayedBeatmapMetadataContainer : BeatmapMetadataContainer
{
public MostPlayedBeatmapMetadataContainer(IBeatmapInfo beatmapInfo)
: base(beatmapInfo)
{
}
protected override Drawable[] CreateText(IBeatmapInfo beatmapInfo)
{
var metadata = beatmapInfo.Metadata;
Debug.Assert(metadata != null);
return new Drawable[]
{
new OsuSpriteText
{
Text = new RomanisableString(metadata.TitleUnicode, metadata.Title),
Font = OsuFont.GetFont(weight: FontWeight.Bold)
},
new OsuSpriteText
{
Text = $" [{beatmapInfo.DifficultyName}]",
Font = OsuFont.GetFont(weight: FontWeight.Bold)
},
new OsuSpriteText
{
Text = " by ",
Font = OsuFont.GetFont(weight: FontWeight.Regular)
},
new OsuSpriteText
{
Text = new RomanisableString(metadata.ArtistUnicode, metadata.Artist),
Font = OsuFont.GetFont(weight: FontWeight.Regular)
},
};
}
}
private class PlayCountText : CompositeDrawable, IHasTooltip
{
public LocalisableString TooltipText => UsersStrings.ShowExtraHistoricalMostPlayedCount;
public PlayCountText(int playCount)
{
AutoSizeAxes = Axes.Both;
InternalChild = new FillFlowContainer
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
AutoSizeAxes = Axes.Both,
Spacing = new Vector2(5, 0),
Children = new Drawable[]
{
new SpriteIcon
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Size = new Vector2(12),
Icon = FontAwesome.Solid.Play,
},
new OsuSpriteText
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Text = playCount.ToString(),
Font = OsuFont.GetFont(size: 20, weight: FontWeight.Regular),
},
}
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Colour = colours.Yellow;
}
}
}
}
| peppy/osu-new | osu.Game/Overlays/Profile/Sections/Historical/DrawableMostPlayedBeatmap.cs | C# | mit | 8,261 |
using BulletML;
using BulletML.Enums;
using BulletML.Nodes;
using NUnit.Framework;
using Tests.Utils;
namespace Tests.Node
{
[TestFixture]
[Category("NodeTest")]
public class ActionNodeTest
{
[Test]
public void TestOneTop()
{
var filename = TestUtils.GetFilePath(@"Content\ActionOneTop.xml");
var pattern = new BulletPattern();
pattern.Parse(filename);
var testNode = pattern.RootNode.FindLabelNode("top", NodeName.action) as ActionNode;
Assert.IsNotNull(testNode);
}
[Test]
public void TestNoRepeatNode()
{
var filename = TestUtils.GetFilePath(@"Content\ActionOneTop.xml");
var pattern = new BulletPattern();
pattern.Parse(filename);
var testNode = pattern.RootNode.FindLabelNode("top", NodeName.action) as ActionNode;
Assert.IsNotNull(testNode);
Assert.IsNull(testNode.ParentRepeatNode);
}
[Test]
public void TestManyTop()
{
var filename = TestUtils.GetFilePath(@"Content\ActionManyTop.xml");
var pattern = new BulletPattern();
pattern.Parse(filename);
var testNode1 = pattern.RootNode.FindLabelNode("top1", NodeName.action) as ActionNode;
var testNode2 = pattern.RootNode.FindLabelNode("top2", NodeName.action) as ActionNode;
Assert.IsNotNull(testNode1);
Assert.IsNotNull(testNode2);
}
}
} | Noxalus/BulletML | Tests/Node/ActionNodeTest.cs | C# | mit | 1,532 |
// Copyright 2017 Axel Etcheverry. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package request
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/go-openapi/spec"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
"github.com/go-yaml/yaml"
"github.com/rs/zerolog/log"
)
// ioReader interface for testing
// Hack for generate mock
//go:generate mockery -case=underscore -inpkg -name=ioReader
// nolint: deadcode,megacheck
type ioReader interface {
io.Reader
}
// ErrSchemaFileFormatNotSupported type
type ErrSchemaFileFormatNotSupported struct {
Ext string
}
// NewErrSchemaFileFormatNotSupported error
func NewErrSchemaFileFormatNotSupported(ext string) error {
return &ErrSchemaFileFormatNotSupported{
Ext: ext,
}
}
func (e *ErrSchemaFileFormatNotSupported) Error() string {
return fmt.Sprintf("%s file schema is not supported", e.Ext)
}
// ErrSchemaNotFound type
type ErrSchemaNotFound struct {
Name string
}
// NewErrSchemaNotFound error
func NewErrSchemaNotFound(name string) error {
return &ErrSchemaNotFound{
Name: name,
}
}
func (e *ErrSchemaNotFound) Error() string {
return fmt.Sprintf(`schema "%s" not found`, e.Name)
}
// SchemaValidator interface experimental
//go:generate mockery -case=underscore -inpkg -name=SchemaValidator
type SchemaValidator interface {
SchemaValidator() *spec.Schema
}
// Validator struct
type Validator struct {
schemas map[string]*validate.SchemaValidator
}
// NewValidator constructor
func NewValidator() *Validator {
return &Validator{
schemas: make(map[string]*validate.SchemaValidator),
}
}
// AddSchemaFromFile name
func (v *Validator) AddSchemaFromFile(name string, filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Error().Err(err).Msgf("Close %s file", filename)
}
}()
return v.AddSchemaFromReader(name, strings.Trim(filepath.Ext(filename), "."), file)
}
// AddSchemaFromReader func
func (v *Validator) AddSchemaFromReader(name string, format string, reader io.Reader) error {
b, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
switch format {
case "json":
return v.AddSchemaFromJSON(name, b)
case "yml", "yaml":
return v.AddSchemaFromYAML(name, b)
default:
return NewErrSchemaFileFormatNotSupported(format)
}
}
// AddSchemaFromJSON string
func (v *Validator) AddSchemaFromJSON(name string, content json.RawMessage) error {
var schema spec.Schema
if err := json.Unmarshal(content, &schema); err != nil {
return err
}
return v.AddSchema(name, &schema)
}
// AddSchemaFromYAML string
func (v *Validator) AddSchemaFromYAML(name string, content []byte) error {
var schema spec.Schema
if err := yaml.Unmarshal(content, &schema); err != nil {
return err
}
return v.AddSchema(name, &schema)
}
// AddSchema by name
func (v *Validator) AddSchema(name string, schema *spec.Schema) error {
validator := validate.NewSchemaValidator(schema, nil, "", strfmt.Default)
v.schemas[name] = validator
return nil
}
// AddSchemFromObject experimental
func (v *Validator) AddSchemFromObject(object SchemaValidator) error {
rt := reflect.TypeOf(object)
return v.AddSchemFromObjectName(rt.Name(), object)
}
// AddSchemFromObjectName experimental
func (v *Validator) AddSchemFromObjectName(name string, object SchemaValidator) error {
return v.AddSchema(name, object.SchemaValidator())
}
// Validate data
func (v Validator) Validate(name string, data interface{}) *validate.Result {
result := &validate.Result{}
validator, ok := v.schemas[name]
if !ok {
result.AddErrors(NewErrSchemaNotFound(name))
return result
}
result = validator.Validate(data)
return result
}
| euskadi31/go-server | request/validator.go | GO | mit | 3,851 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityWithReferenceRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type UserWithReferenceRequest.
/// </summary>
public partial class UserWithReferenceRequest : BaseRequest, IUserWithReferenceRequest
{
/// <summary>
/// Constructs a new UserWithReferenceRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public UserWithReferenceRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Gets the specified User.
/// </summary>
/// <returns>The User.</returns>
public System.Threading.Tasks.Task<User> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified User.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The User.</returns>
public async System.Threading.Tasks.Task<User> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<User>(null, cancellationToken).ConfigureAwait(false);
return retrievedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IUserWithReferenceRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IUserWithReferenceRequest Expand(Expression<Func<User, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IUserWithReferenceRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IUserWithReferenceRequest Select(Expression<Func<User, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
}
}
| ginach/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/UserWithReferenceRequest.cs | C# | mit | 4,908 |
package com.dumu.housego.presenter;
import com.dumu.housego.entity.UserInfo;
import com.dumu.housego.model.ILoginUserInfoModel;
import com.dumu.housego.model.IModel.AsycnCallBack;
import com.dumu.housego.model.LoginUserInfoModel;
import com.dumu.housego.view.ILoginUserInfoView;
public class LoginUserInfoPresenter implements ILoginUserInfoPresenter {
private ILoginUserInfoModel model;
private ILoginUserInfoView view;
public LoginUserInfoPresenter(ILoginUserInfoView view) {
super();
this.view = view;
model = new LoginUserInfoModel();
}
@Override
public void login(String userid) {
model.login(userid, new AsycnCallBack() {
@Override
public void onSuccess(Object success) {
UserInfo userinfo = (UserInfo) success;
view.loginUserInfoSuccess();
}
@Override
public void onError(Object error) {
view.loginUserInfoFail(error.toString());
}
});
}
}
| rentianhua/tsf_android | houseAd/HouseGo/src/com/dumu/housego/presenter/LoginUserInfoPresenter.java | Java | mit | 902 |
<?php
namespace MPM\Bundle\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
/**
* Persona
*
* @ORM\Table(name="personas")
* @ORM\Entity(repositoryClass="MPM\Bundle\AdminBundle\Entity\PersonaRepository")
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="discr", type="string")
* @ORM\DiscriminatorMap({"person" = "Persona", "client" = "Cliente", "personal" = "Personal"})
*
*/
class Persona implements AdvancedUserInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=255)
*/
protected $nombre;
/**
* @var string
*
* @ORM\Column(name="apellido", type="string", length=255)
*/
protected $apellido;
/**
* @var string
*
* @ORM\Column(name="dni", type="string", length=255)
*/
protected $dni;
/**
* @var boolean
*
* @ORM\Column(name="sexo", type="boolean")
*/
protected $sexo;
/**
* @var string
*
* @ORM\Column(name="telefono", type="string", length=255)
*/
protected $telefono;
/**
* @var string
*
* @ORM\Column(name="mail", type="string", length=255)
*/
protected $mail;
/**
* @var \DateTime
*
* @ORM\Column(name="sysLog", type="datetime")
*/
protected $sysLog;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=255)
*/
protected $password;
/**
* @var string
*
* @ORM\Column(name="salt", type="string", length=255)
*/
protected $salt;
/**
* @var boolean
*
* @ORM\Column(name="enabled", type="boolean")
*/
protected $enabled;
/**
* @var boolean
*
* @ORM\Column(name="locked", type="boolean")
*/
protected $locked;
/**
* @var boolean
*
* @ORM\Column(name="expired", type="boolean")
*/
protected $expired;
/**
* @var \DateTime
*
* @ORM\Column(name="expiresAt", type="datetime", nullable=true)
*/
protected $expiresAt;
/**
* @var string
*
* @ORM\Column(name="credentials", type="string", length=255, nullable=true)
*/
protected $credentials;
/**
* @var boolean
*
* @ORM\Column(name="credentialsExpired", type="boolean")
*/
protected $credentialsExpired;
/**
* @var \DateTime
*
* @ORM\Column(name="credentialsExpireAt", type="datetime", nullable=true)
*/
protected $credentialsExpireAt;
/**
* @var string
*
* @ORM\Column(name="image", type="blob", nullable=true)
*/
protected $image;
/**
* @var string
*
* @ORM\Column(name="imageType", type="string", length=255, nullable=true)
*/
protected $imageType;
/**
* @var string
*
* @ORM\Column(name="notas", type="text", nullable=true)
*/
protected $notas;
/**
* @ORM\OneToMany(targetEntity="Log", mappedBy="usuario")
**/
protected $logs;
/**
* Constructor
*/
public function __construct()
{
$this->logs = new \Doctrine\Common\Collections\ArrayCollection();
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
$this->sysLog = new \DateTime("now");
$this->enabled = true;
$this->locked = false;
$this->expired = false;
$this->credentialsExpired = false;
}
//.....::::Interface Code::::.....//
public function getUsername()
{
return $this->mail;
}
public function getPassword()
{
return $this->password;
}
public function getSalt()
{
return $this->salt;
}
public function getRoles()
{
return array("ROLE_USER");
}
public function eraseCredentials()
{
$this->credentials = null;
return $this;
}
public function isEnabled ()
{
return $this->enabled;
}
public function isAccountNonExpired()
{
if (true === $this->expired) {
return false;
}
if (null !== $this->expiresAt && $this->expiresAt->getTimestamp() < time()) {
return false;
}
return true;
}
public function isAccountNonLocked()
{
return !$this->locked;
}
public function isCredentialsNonExpired()
{
if (true === $this->credentialsExpired) {
return false;
}
if (null !== $this->credentialsExpireAt && $this->credentialsExpireAt->getTimestamp() < time()) {
return false;
}
return true;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return Persona
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set apellido
*
* @param string $apellido
* @return Persona
*/
public function setApellido($apellido)
{
$this->apellido = $apellido;
return $this;
}
/**
* Get apellido
*
* @return string
*/
public function getApellido()
{
return $this->apellido;
}
/**
* Set dni
*
* @param string $dni
* @return Persona
*/
public function setDni($dni)
{
$this->dni = $dni;
return $this;
}
/**
* Get dni
*
* @return string
*/
public function getDni()
{
return $this->dni;
}
/**
* Set sexo
*
* @param boolean $sexo
* @return Persona
*/
public function setSexo($sexo)
{
$this->sexo = $sexo;
return $this;
}
/**
* Get sexo
*
* @return boolean
*/
public function getSexo()
{
return $this->sexo;
}
/**
* Set telefono
*
* @param string $telefono
* @return Persona
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* @return string
*/
public function getTelefono()
{
return $this->telefono;
}
/**
* Set mail
*
* @param string $mail
* @return Persona
*/
public function setMail($mail)
{
$this->mail = $mail;
return $this;
}
/**
* Get mail
*
* @return string
*/
public function getMail()
{
return $this->mail;
}
/**
* Set sysLog
*
* @param \DateTime $sysLog
* @return Persona
*/
public function setSysLog($sysLog)
{
$this->sysLog = $sysLog;
return $this;
}
/**
* Get sysLog
*
* @return \DateTime
*/
public function getSysLog()
{
return $this->sysLog;
}
/**
* Set password
*
* @param string $password
* @return Persona
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set salt
*
* @param string $salt
* @return Persona
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Set image
*
* @param string $image
* @return Persona
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* @return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set imageType
*
* @param string $imageType
* @return Persona
*/
public function setImageType($imageType)
{
$this->imageType = $imageType;
return $this;
}
/**
* Get imageType
*
* @return string
*/
public function getImageType()
{
return $this->imageType;
}
/**
* Set notas
*
* @param string $notas
* @return Persona
*/
public function setNotas($notas)
{
$this->notas = $notas;
return $this;
}
/**
* Get notas
*
* @return string
*/
public function getNotas()
{
return $this->notas;
}
/**
* Add logs
*
* @param Log $logs
* @return Persona
*/
public function addLog(Log $logs)
{
$this->logs[] = $logs;
return $this;
}
/**
* Remove logs
*
* @param Log $logs
*/
public function removeLog(Log $logs)
{
$this->logs->removeElement($logs);
}
/**
* Get logs
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getLogs()
{
return $this->logs;
}
/**
* Set enabled
*
* @param boolean $enabled
* @return Persona
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* @return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set locked
*
* @param boolean $locked
* @return Persona
*/
public function setLocked($locked)
{
$this->locked = $locked;
return $this;
}
/**
* Get locked
*
* @return boolean
*/
public function getLocked()
{
return $this->locked;
}
/**
* Set expired
*
* @param boolean $expired
* @return Persona
*/
public function setExpired($expired)
{
$this->expired = $expired;
return $this;
}
/**
* Get expired
*
* @return boolean
*/
public function getExpired()
{
return $this->expired;
}
/**
* Set expiresAt
*
* @param \DateTime $expiresAt
* @return Persona
*/
public function setExpiresAt($expiresAt)
{
$this->expiresAt = $expiresAt;
return $this;
}
/**
* Get expiresAt
*
* @return \DateTime
*/
public function getExpiresAt()
{
return $this->expiresAt;
}
/**
* Set credentials
*
* @param string $credentials
* @return Persona
*/
public function setCredentials($credentials)
{
$this->credentials = $credentials;
return $this;
}
/**
* Get credentials
*
* @return string
*/
public function getCredentials()
{
return $this->credentials;
}
/**
* Set credentialsExpired
*
* @param boolean $credentialsExpired
* @return Persona
*/
public function setCredentialsExpired($credentialsExpired)
{
$this->credentialsExpired = $credentialsExpired;
return $this;
}
/**
* Get credentialsExpired
*
* @return boolean
*/
public function getCredentialsExpired()
{
return $this->credentialsExpired;
}
/**
* Set credentialsExpireAt
*
* @param \DateTime $credentialsExpireAt
* @return Persona
*/
public function setCredentialsExpireAt($credentialsExpireAt)
{
$this->credentialsExpireAt = $credentialsExpireAt;
return $this;
}
/**
* Get credentialsExpireAt
*
* @return \DateTime
*/
public function getCredentialsExpireAt()
{
return $this->credentialsExpireAt;
}
}
| matias-pierobon/tonga | src/MPM/Bundle/AdminBundle/Entity/Persona.php | PHP | mit | 12,030 |
/**
* LICENSE : MIT
*/
"use strict";
(function (mod) {
if (typeof exports == "object" && typeof module == "object") {
mod(require("codemirror"));
}
else if (typeof define == "function" && define.amd) {
define(["codemirror"], mod);
}
else {
mod(CodeMirror);
}
})(function (CodeMirror) {
"use strict";
CodeMirror.commands.scrollSelectionToCenter = function (cm) {
if (cm.getOption("disableInput")) {
return CodeMirror.Pass;
}
var cursor = cm.getCursor('anchor');
var top = cm.charCoords({line: cursor.line, ch: 0}, "local").top;
var halfWindowHeight = cm.getWrapperElement().offsetHeight / 2;
var scrollTo = Math.round((top - halfWindowHeight));
cm.scrollTo(null, scrollTo);
};
CodeMirror.defineOption("typewriterScrolling", false, function (cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.off("changes", onChanges);
}
if (val) {
cm.on("changes", onChanges);
}
});
function onChanges(cm, changes) {
if (cm.getSelection().length !== 0) {
return;
}
for (var i = 0, len = changes.length; i < len; i++) {
var each = changes[i];
if (each.origin === '+input' || each.origin === '+delete') {
cm.execCommand("scrollSelectionToCenter");
return;
}
}
}
});
| azu/codemirror-typewriter-scrolling | typewriter-scrolling.js | JavaScript | mit | 1,466 |
import os
from setuptools import setup
import sys
if sys.version_info < (2, 6):
raise Exception('Wiggelen requires Python 2.6 or higher.')
install_requires = []
# Python 2.6 does not include the argparse module.
try:
import argparse
except ImportError:
install_requires.append('argparse')
# Python 2.6 does not include OrderedDict.
try:
from collections import OrderedDict
except ImportError:
install_requires.append('ordereddict')
try:
with open('README.rst') as readme:
long_description = readme.read()
except IOError:
long_description = 'See https://pypi.python.org/pypi/wiggelen'
# This is quite the hack, but we don't want to import our package from here
# since that's recipe for disaster (it might have some uninstalled
# dependencies, or we might import another already installed version).
distmeta = {}
for line in open(os.path.join('wiggelen', '__init__.py')):
try:
field, value = (x.strip() for x in line.split('='))
except ValueError:
continue
if field == '__version_info__':
value = value.strip('[]()')
value = '.'.join(x.strip(' \'"') for x in value.split(','))
else:
value = value.strip('\'"')
distmeta[field] = value
setup(
name='wiggelen',
version=distmeta['__version_info__'],
description='Working with wiggle tracks in Python',
long_description=long_description,
author=distmeta['__author__'],
author_email=distmeta['__contact__'],
url=distmeta['__homepage__'],
license='MIT License',
platforms=['any'],
packages=['wiggelen'],
install_requires=install_requires,
entry_points = {
'console_scripts': ['wiggelen = wiggelen.commands:main']
},
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
],
keywords='bioinformatics'
)
| martijnvermaat/wiggelen | setup.py | Python | mit | 2,054 |
namespace P10TraverseDirectoryWithXDocElAttr
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
class P10TraverseDirectoryWithXDocElAttr
{
static void Main()
{
string directoryPath = @"C:\";
string fileToWriteLocation = "../../directoryStructure.xml";
Encoding encoding = Encoding.GetEncoding("windows-1251");
System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(directoryPath);
var directories = directory.GetDirectories("*.*");
var files = directory.GetFiles("*.*");
XElement directoryStructure = new XElement(XName.Get("directory"));
foreach (var dir in directories)
{
directoryStructure.Add(new XElement("directory", dir.Name));
}
foreach (var file in files)
{
var node = new XElement("file", file.Name);
node.Add(new XAttribute("size", file.Length / 1025 + " KB"));
directoryStructure.Add(node);
}
directoryStructure.Save(fileToWriteLocation);
Console.WriteLine("File directoryStructure.xml saved.");
}
}
} | dechoD/Telerik-Homeworks | Module II Homeworks/Data Bases/XML Parsing/P10TraverseDirectoryWithXDocElAttr/P10TraverseDirectoryWithXDocElAttr.cs | C# | mit | 1,352 |
using UnityEngine;
using System.Collections;
using UnityEditor;
using BMAPI.v1;
public class OpenFileDialog : MonoBehaviour {
private BMAPI.v1.Beatmap m_beatmap;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void SelectFile()
{
string path = EditorUtility.OpenFilePanel("Select .osu Beatmap File", "./Beatmaps", "osu");
if (path.Length != 0)
{
// var www = WWW("file:///" + path);
string newPath = path.Replace('/', '\\');
Debug.Log(newPath + " Beatmap Loaded");
m_beatmap = new BMAPI.v1.Beatmap(newPath);
gameObject.GetComponent<BeatmapMeta>().LoadBeatmap(m_beatmap);
}
}
}
| jump4r/ProceduralGenerationFinal | Audio Based Procedural Mesh/Assets/Scripts/OpenFileDialog.cs | C# | mit | 766 |
/**
* @name Evemit
* @description Minimal and fast JavaScript event emitter for Node.js and front-end.
* @author Nicolas Tallefourtane <dev@nicolab.net>
* @link https://github.com/Nicolab/evemit
* @license MIT https://github.com/Nicolab/evemit/blob/master/LICENSE
*/
;(function() {
'use strict';
/**
* Evemit
*
* @constructor
* @api public
*/
function Evemit() {
this.events = {};
}
/**
* Register a new event listener for a given event.
*
* @param {string} event Event name.
* @param {function} fn Callback function (listener).
* @param {*} [context] Context for function execution.
* @return {Evemit} Current instance.
* @api public
*/
Evemit.prototype.on = function(event, fn, context) {
if (!this.events[event]) {
this.events[event] = [];
}
if(context) {
fn._E_ctx = context;
}
this.events[event].push(fn);
return this;
};
/**
* Add an event listener that's only called once.
*
* @param {string} event Event name.
* @param {function} fn Callback function (listener).
* @param {*} [context] Context for function execution.
* @return {Evemit} Current instance.
* @api public
*/
Evemit.prototype.once = function(event, fn, context) {
fn._E_once = true;
return this.on(event, fn, context);
};
/**
* Emit an event to all registered event listeners.
*
* @param {string} event Event name.
* @param {*} [...arg] One or more arguments to pass to the listeners.
* @return {bool} Indication, `true` if at least one listener was executed,
* otherwise returns `false`.
* @api public
*/
Evemit.prototype.emit = function(event, arg1, arg2, arg3, arg4) {
var fn, evs, args, aLn;
if(!this.events[event]) {
return false;
}
args = Array.prototype.slice.call(arguments, 1);
aLn = args.length;
evs = this.events[event];
for(var i = 0, ln = evs.length; i < ln; i++) {
fn = evs[i];
if (fn._E_once) {
this.off(event, fn);
}
// Function.apply() is a bit slower, so try to do without
switch (aLn) {
case 0:
fn.call(fn._E_ctx);
break;
case 1:
fn.call(fn._E_ctx, arg1);
break;
case 2:
fn.call(fn._E_ctx, arg1, arg2);
break;
case 3:
fn.call(fn._E_ctx, arg1, arg2, arg3);
break;
case 4:
fn.call(fn._E_ctx, arg1, arg2, arg3, arg4);
break;
default:
fn.apply(fn._E_ctx, args);
}
}
return true;
};
/**
* Remove event listeners.
*
* @param {string} event The event to remove.
* @param {function} fn The listener that we need to find.
* @return {Evemit} Current instance.
* @api public
*/
Evemit.prototype.off = function(event, fn) {
if (!this.events[event]) {
return this;
}
for (var i = 0, ln = this.events[event].length; i < ln; i++) {
if (this.events[event][i] === fn) {
this.events[event][i] = null;
delete this.events[event][i];
}
}
// re-index
this.events[event] = this.events[event].filter(function(ltns) {
return typeof ltns !== 'undefined';
});
return this;
};
/**
* Get a list of assigned event listeners.
*
* @param {string} [event] The events that should be listed.
* If not provided, all listeners are returned.
* Use the property `Evemit.events` if you want to get an object like
* ```
* {event1: [array of listeners], event2: [array of listeners], ...}
* ```
*
* @return {array}
* @api public
*/
Evemit.prototype.listeners = function(event) {
var evs, ltns;
if(event) {
return this.events[event] || [];
}
evs = this.events;
ltns = [];
for(var ev in evs) {
ltns = ltns.concat(evs[ev].valueOf());
}
return ltns;
};
/**
* Expose Evemit
* @type {Evemit}
*/
if(typeof module !== 'undefined' && module.exports) {
module.exports = Evemit;
} else {
window.Evemit = Evemit;
}
})();
| Nicolab/evemit | evemit.js | JavaScript | mit | 4,182 |
package org.simpleflatmapper.poi.impl;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.simpleflatmapper.map.ConsumerErrorHandler;
import org.simpleflatmapper.map.ContextualSourceFieldMapper;
import org.simpleflatmapper.map.SourceFieldMapper;
import org.simpleflatmapper.map.MappingContext;
import org.simpleflatmapper.map.MappingException;
import org.simpleflatmapper.map.context.MappingContextFactory;
import org.simpleflatmapper.map.mapper.JoinMapperEnumerable;
import org.simpleflatmapper.poi.RowMapper;
import org.simpleflatmapper.util.CheckedConsumer;
import java.util.Iterator;
import org.simpleflatmapper.util.Enumerable;
import org.simpleflatmapper.util.EnumerableIterator;
//IFJAVA8_START
import org.simpleflatmapper.util.EnumerableSpliterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
//IFJAVA8_END
public class JoinSheetMapper<T> implements RowMapper<T> {
private final ContextualSourceFieldMapper<Row, T> mapper;
private final int startRow = 0;
private final ConsumerErrorHandler consumerErrorHandler;
private final MappingContextFactory<? super Row> mappingContextFactory;
public JoinSheetMapper(ContextualSourceFieldMapper<Row, T> mapper, ConsumerErrorHandler consumerErrorHandler, MappingContextFactory<? super Row> mappingContextFactory) {
this.mapper = mapper;
this.consumerErrorHandler = consumerErrorHandler;
this.mappingContextFactory = mappingContextFactory;
}
@Override
public Iterator<T> iterator(Sheet sheet) {
return iterator(startRow, sheet);
}
@Override
public Iterator<T> iterator(int startRow, Sheet sheet) {
return new EnumerableIterator<T>(enumerable(startRow, sheet, newMappingContext()));
}
@Override
public Enumerable<T> enumerate(Sheet sheet) {
return enumerate(startRow, sheet);
}
@Override
public Enumerable<T> enumerate(int startRow, Sheet sheet) {
return enumerable(startRow, sheet, newMappingContext());
}
private Enumerable<T> enumerable(int startRow, Sheet sheet, MappingContext<? super Row> mappingContext) {
return new JoinMapperEnumerable<Row, T>(mapper, mappingContext, new RowEnumerable(startRow, sheet));
}
@Override
public <RH extends CheckedConsumer<? super T>> RH forEach(Sheet sheet, RH consumer) {
return forEach(startRow, sheet, consumer);
}
@Override
public <RH extends CheckedConsumer<? super T>> RH forEach(int startRow, Sheet sheet, RH consumer) {
MappingContext<? super Row> mappingContext = newMappingContext();
Enumerable<T> enumarable = enumerable(startRow, sheet, mappingContext);
while(enumarable.next()) {
try {
consumer.accept(enumarable.currentValue());
} catch(Exception e) {
consumerErrorHandler.handlerError(e, enumarable.currentValue());
}
}
return consumer;
}
//IFJAVA8_START
@Override
public Stream<T> stream(Sheet sheet) {
return stream(startRow, sheet);
}
@Override
public Stream<T> stream(int startRow, Sheet sheet) {
return StreamSupport.stream(new EnumerableSpliterator<T>(enumerable(startRow, sheet, newMappingContext())), false);
}
//IFJAVA8_END
@Override
public T map(Row source) throws MappingException {
return mapper.map(source);
}
@Override
public T map(Row source, MappingContext<? super Row> context) throws MappingException {
return mapper.map(source, context);
}
private MappingContext<? super Row> newMappingContext() {
return mappingContextFactory.newContext();
}
}
| arnaudroger/SimpleFlatMapper | sfm-poi/src/main/java/org/simpleflatmapper/poi/impl/JoinSheetMapper.java | Java | mit | 3,746 |
<?php
/*
* This is a firt example of user script,
* used eg. from a special button
*
*/
// Add the conf file and first bootstrap
require_once("../inc/conn.php");
// remove the comment if the script is not public
// proteggi(); // authenticated users
// proteggi(2); // level 2 users
// proteggi(3); // level 3 users (administrator only)
if(isset($_GET['yourid'])){
$sql="SELECT * FROM youtable WHERE yourid='".$vmsql->escape($_GET['yourid'])."'";
//exec the query
$q=$vmsql->query($sql);
// if have results
if($vmsql->num_rows($q) > 0){
// get the recordset
$RS=$vmsql->fetch_assoc($q);
// do what you want with results
var_dump($RS);
}
else{
// no results case
}
}
| rockborg/wellness_server | vfront/usr/script.example.php | PHP | mit | 745 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Student CNN encoder for XE training."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from models.encoders.core.cnn_util import conv_layer, max_pool, batch_normalization
############################################################
# Architecture: (feature map, kernel(f*t), stride(f,t))
# CNN1: (128, 9*9, (1,1)) * 1 layers
# Batch normalization
# ReLU
# Max pool (3,1)
# CNN2: (256, 3*4, (1,1)) * 1 layers
# Batch normalization
# ReLU
# Max pool (1,1)
# fc: 2048 (ReLU) * 4 layers
############################################################
class StudentCNNXEEncoder(object):
"""Student CNN encoder for XE training.
Args:
input_size (int): the dimensions of input vectors.
This is expected to be num_channels * 3 (static + Δ + ΔΔ)
splice (int): frames to splice
num_stack (int): the number of frames to stack
parameter_init (float, optional): the range of uniform distribution to
initialize weight parameters (>= 0)
name (string, optional): the name of encoder
"""
def __init__(self,
input_size,
splice,
num_stack,
parameter_init,
name='cnn_student_xe_encoder'):
assert input_size % 3 == 0
self.num_channels = (input_size // 3) // num_stack // splice
self.splice = splice
self.num_stack = num_stack
self.parameter_init = parameter_init
self.name = name
def __call__(self, inputs, keep_prob, is_training):
"""Construct model graph.
Args:
inputs (placeholder): A tensor of size
`[B, input_size (num_channels * splice * num_stack * 3)]`
keep_prob (placeholder, float): A probability to keep nodes
in the hidden-hidden connection
is_training (bool):
Returns:
outputs: Encoder states.
if time_major is True, a tensor of size `[T, B, output_dim]`
otherwise, `[B, output_dim]`
"""
# inputs: 2D tensor `[B, input_dim]`
batch_size = tf.shape(inputs)[0]
input_dim = inputs.shape.as_list()[-1]
# NOTE: input_dim: num_channels * splice * num_stack * 3
# for debug
# print(input_dim) # 1200
# print(self.num_channels) # 40
# print(self.splice) # 5
# print(self.num_stack) # 2
assert input_dim == self.num_channels * self.splice * self.num_stack * 3
# Reshape to 4D tensor `[B, num_channels, splice * num_stack, 3]`
inputs = tf.reshape(
inputs,
shape=[batch_size, self.num_channels, self.splice * self.num_stack, 3])
# NOTE: filter_size: `[H, W, C_in, C_out]`
with tf.variable_scope('CNN1'):
inputs = conv_layer(inputs,
filter_size=[9, 9, 3, 128],
stride=[1, 1],
parameter_init=self.parameter_init,
activation='relu')
inputs = batch_normalization(inputs, is_training=is_training)
inputs = max_pool(inputs,
pooling_size=[3, 1],
stride=[3, 1],
name='max_pool')
with tf.variable_scope('CNN2'):
inputs = conv_layer(inputs,
filter_size=[3, 4, 128, 256],
stride=[1, 1],
parameter_init=self.parameter_init,
activation='relu')
inputs = batch_normalization(inputs, is_training=is_training)
inputs = max_pool(inputs,
pooling_size=[1, 1],
stride=[1, 1],
name='max_pool')
# Reshape to 2D tensor `[B, new_h * new_w * C_out]`
outputs = tf.reshape(
inputs, shape=[batch_size, np.prod(inputs.shape.as_list()[-3:])])
for i in range(1, 5, 1):
with tf.variable_scope('fc%d' % (i)) as scope:
outputs = tf.contrib.layers.fully_connected(
inputs=outputs,
num_outputs=2048,
activation_fn=tf.nn.relu,
weights_initializer=tf.truncated_normal_initializer(
stddev=self.parameter_init),
biases_initializer=tf.zeros_initializer(),
scope=scope)
return outputs
| hirofumi0810/tensorflow_end2end_speech_recognition | models/encoders/core/student_cnn_xe.py | Python | mit | 4,732 |
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_WSANSClassInfoA.hpp>
START_ATF_NAMESPACE
typedef _WSANSClassInfoA *LPWSANSCLASSINFO;
END_ATF_NAMESPACE
| goodwinxp/Yorozuya | library/ATF/LPWSANSCLASSINFO.hpp | C++ | mit | 270 |
package com.lqtemple.android.lqbookreader.model;
import java.io.Serializable;
/**音乐信息
* Created by chenling on 2016/3/15.
*/
public class MusicMedia implements Serializable{
private int id;
private String title;
private String artist;
private String url;
private String time;
private String size;
private int albumId;
private String album;
private int duration;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getTime() {
return time;
}
//格式化时间
public void setTime(int time) {
time /= 1000;
int minute = time / 60;
int hour = minute / 60;
int second = time % 60;
minute %= 60;
this.time = String.format("%02d:%02d", minute, second);
}
public String getSize() {
return size;
}
public void setSize(Long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
this.size = String.format("%.1f GB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
this.size = String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
} else if (size >= kb) {
float f = (float) size / kb;
this.size = String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
} else
this.size = String.format("%d B", size);
}
public int getAlbumId() {
return albumId;
}
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
@Override
public String toString() {
return "MusicMedia{" +
"id=" + id +
", title='" + title + '\'' +
", artist='" + artist + '\'' +
", url='" + url + '\'' +
", time='" + time + '\'' +
", size='" + size + '\'' +
", albumId=" + albumId +
", album='" + album + '\'' +
'}';
}
}
| ceji-longquan/ceji_android | app/src/main/java/com/lqtemple/android/lqbookreader/model/MusicMedia.java | Java | mit | 2,766 |
(function() {
//###########################################################################################################
var CND, Multimix, alert, badge, debug, dec, decG, echo, help, hex, hexG, info, isa, log, name, nameO, nameOG, rpr, type_of, types, urge, validate, warn, whisper;
CND = require('cnd');
rpr = CND.rpr.bind(CND);
badge = 'NCR';
log = CND.get_logger('plain', badge);
info = CND.get_logger('info', badge);
alert = CND.get_logger('alert', badge);
debug = CND.get_logger('debug', badge);
warn = CND.get_logger('warn', badge);
urge = CND.get_logger('urge', badge);
whisper = CND.get_logger('whisper', badge);
help = CND.get_logger('help', badge);
echo = CND.echo.bind(CND);
//...........................................................................................................
this._input_default = 'plain';
// @_input_default = 'ncr'
// @_input_default = 'xncr'
//...........................................................................................................
Multimix = require('multimix006modern');
this.cloak = (require('./cloak')).new();
this._aggregate = null;
this._ISL = require('interskiplist');
this.unicode_isl = (() => {
var R, i, interval, len, ref;
R = this._ISL.new();
this._ISL.add_index(R, 'rsg');
this._ISL.add_index(R, 'tag');
ref = require('../data/unicode-9.0.0-intervals.json');
for (i = 0, len = ref.length; i < len; i++) {
interval = ref[i];
this._ISL.add(R, interval);
}
this._aggregate = this._ISL.aggregate.use(R);
return R;
})();
types = require('./types');
({isa, validate, type_of} = types.export());
//===========================================================================================================
//-----------------------------------------------------------------------------------------------------------
this._copy_library = function(input_default = 'plain') {
/* TAINT makeshift method until we have something better; refer to
`tests[ "(v2) create derivatives of NCR (2)" ]` for example usage */
var R, mix, reducers;
reducers = {
fallback: 'assign',
fields: {
unicode_isl: (values) => {
return this._ISL.copy(this.unicode_isl);
}
}
};
//.........................................................................................................
mix = (require('multimix006modern')).mix.use(reducers);
R = mix(this, {
_input_default: input_default
});
R._aggregate = R._ISL.aggregate.use(R.unicode_isl);
//.........................................................................................................
return R;
};
//===========================================================================================================
// CLOAK
//-----------------------------------------------------------------------------------------------------------
this._XXX_escape_chrs = (text) => {
return this.cloak.backslashed.hide(this.cloak.hide(text));
};
this._XXX_unescape_escape_chrs = (text) => {
return this.cloak.reveal(this.cloak.backslashed.reveal(text));
};
this._XXX_remove_escaping_backslashes = (text) => {
return this.cloak.backslashed.remove(text);
};
//===========================================================================================================
// SPLIT TEXT INTO CHARACTERS
//-----------------------------------------------------------------------------------------------------------
this.chrs_from_esc_text = function(text, settings) {
var R, chrs, i, is_escaped, len, part, parts;
R = [];
parts = text.split(/\\([^.])/);
is_escaped = true;
for (i = 0, len = parts.length; i < len; i++) {
part = parts[i];
if (is_escaped = !is_escaped) {
/* almost */
R.push(part);
continue;
}
chrs = this.chrs_from_text(part, settings);
if (chrs[chrs.length - 1] === '\\') {
chrs.pop();
}
R.splice(R.length, 0, ...chrs);
}
//.........................................................................................................
return R;
};
//-----------------------------------------------------------------------------------------------------------
this.chrs_from_text = function(text, settings) {
var input_mode, ref, splitter;
if (text.length === 0) {
return [];
}
//.........................................................................................................
switch (input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default) {
case 'plain':
splitter = this._plain_splitter;
break;
case 'ncr':
splitter = this._ncr_splitter;
break;
case 'xncr':
splitter = this._xncr_splitter;
break;
default:
throw new Error(`unknown input mode: ${rpr(input_mode)}`);
}
//.........................................................................................................
return (text.split(splitter)).filter(function(element, idx) {
return element.length !== 0;
});
};
//-----------------------------------------------------------------------------------------------------------
this._new_chunk = function(csg, rsg, chrs) {
var R;
R = {
'~isa': 'NCR/chunk',
'csg': csg,
'rsg': rsg,
// 'chrs': chrs
'text': chrs.join('')
};
//.........................................................................................................
return R;
};
//-----------------------------------------------------------------------------------------------------------
this.chunks_from_text = function(text, settings) {
/* Given a `text` and `settings` (of which `csg` is irrelevant here), return a list of `NCR/chunk`
objects (as returned by `NCR._new_chunk`) that describes stretches of characters with codepoints in the
same 'range' (Unicode block).
*/
var R, chr, chrs, csg, description, i, last_csg, last_rsg, len, output_mode, ref, ref1, rsg, transform_output;
R = [];
if (text.length === 0) {
return R;
}
last_csg = 'u';
last_rsg = null;
chrs = [];
//.........................................................................................................
switch (output_mode = (ref = settings != null ? settings['output'] : void 0) != null ? ref : this._input_default) {
case 'plain':
transform_output = function(chr) {
return chr;
};
break;
case 'html':
transform_output = function(chr) {
switch (chr) {
case '&':
return '&';
case '<':
return '<';
case '>':
return '>';
default:
return chr;
}
};
break;
default:
throw new Error(`unknown output mode: ${rpr(output_mode)}`);
}
ref1 = this.chrs_from_text(text, settings);
//.........................................................................................................
for (i = 0, len = ref1.length; i < len; i++) {
chr = ref1[i];
description = this.analyze(chr, settings);
({csg, rsg} = description);
chr = description[csg === 'u' ? 'chr' : 'ncr'];
if (rsg !== last_rsg) {
if (chrs.length > 0) {
R.push(this._new_chunk(last_csg, last_rsg, chrs));
}
last_csg = csg;
last_rsg = rsg;
chrs = [];
}
//.......................................................................................................
chrs.push(transform_output(chr));
}
if (chrs.length > 0) {
//.........................................................................................................
R.push(this._new_chunk(last_csg, last_rsg, chrs));
}
return R;
};
//-----------------------------------------------------------------------------------------------------------
this.html_from_text = function(text, settings) {
var R, chunk, chunks, i, input_mode, len, ref, ref1;
R = [];
//.........................................................................................................
input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default;
chunks = this.chunks_from_text(text, {
input: input_mode,
output: 'html'
});
for (i = 0, len = chunks.length; i < len; i++) {
chunk = chunks[i];
R.push(`<span class="${(ref1 = chunk['rsg']) != null ? ref1 : chunk['csg']}">${chunk['text']}</span>`);
}
//.........................................................................................................
return R.join('');
};
//===========================================================================================================
// CONVERTING TO CID
//-----------------------------------------------------------------------------------------------------------
this.cid_from_chr = function(chr, settings) {
var input_mode, ref;
input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default;
return (this._chr_csg_cid_from_chr(chr, input_mode))[2];
};
//-----------------------------------------------------------------------------------------------------------
this.csg_cid_from_chr = function(chr, settings) {
var input_mode, ref;
input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default;
return (this._chr_csg_cid_from_chr(chr, input_mode)).slice(1);
};
//-----------------------------------------------------------------------------------------------------------
this._chr_csg_cid_from_chr = function(chr, input_mode) {
/* thx to http://perldoc.perl.org/Encode/Unicode.html */
var cid, cid_dec, cid_hex, csg, first_chr, hi, lo, match, matcher;
if (chr.length === 0) {
/* Given a text with one or more characters, return the first character, its CSG, and its CID (as a
non-negative integer). Additionally, an input mode may be given as either `plain`, `ncr`, or `xncr`.
*/
//.........................................................................................................
throw new Error("unable to obtain CID from empty string");
}
//.........................................................................................................
if (input_mode == null) {
input_mode = 'plain';
}
switch (input_mode) {
case 'plain':
matcher = this._first_chr_matcher_plain;
break;
case 'ncr':
matcher = this._first_chr_matcher_ncr;
break;
case 'xncr':
matcher = this._first_chr_matcher_xncr;
break;
default:
throw new Error(`unknown input mode: ${rpr(input_mode)}`);
}
//.........................................................................................................
match = chr.match(matcher);
if (match == null) {
throw new Error(`illegal character sequence in ${rpr(chr)}`);
}
first_chr = match[0];
//.........................................................................................................
switch (first_chr.length) {
//.......................................................................................................
case 1:
return [first_chr, 'u', first_chr.charCodeAt(0)];
//.......................................................................................................
case 2:
hi = first_chr.charCodeAt(0);
lo = first_chr.charCodeAt(1);
cid = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
return [first_chr, 'u', cid];
default:
//.......................................................................................................
[chr, csg, cid_hex, cid_dec] = match;
cid = cid_hex != null ? parseInt(cid_hex, 16) : parseInt(cid_dec, 10);
if (csg.length === 0) {
csg = 'u';
}
return [first_chr, csg, cid];
}
};
// #-----------------------------------------------------------------------------------------------------------
// @cid_from_ncr = ( ) ->
// #-----------------------------------------------------------------------------------------------------------
// @cid_from_xncr = ( ) ->
// #-----------------------------------------------------------------------------------------------------------
// @cid_from_fncr = ( ) ->
//===========================================================================================================
// CONVERTING FROM CID &c
//-----------------------------------------------------------------------------------------------------------
this.as_csg = function(cid_hint, O) {
return (this._csg_cid_from_hint(cid_hint, O))[0];
};
this.as_cid = function(cid_hint, O) {
return (this._csg_cid_from_hint(cid_hint, O))[1];
};
//...........................................................................................................
this.as_chr = function(cid_hint, O) {
return this._as_chr.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
this.as_uchr = function(cid_hint, O) {
return this._as_uchr.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
this.as_fncr = function(cid_hint, O) {
return this._as_fncr.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
this.as_sfncr = function(cid_hint, O) {
return this._as_sfncr.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
this.as_xncr = function(cid_hint, O) {
return this._as_xncr.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
this.as_ncr = function(cid_hint, O) {
return this._as_xncr.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
this.as_rsg = function(cid_hint, O) {
return this._as_rsg.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
this.as_range_name = function(cid_hint, O) {
return this._as_range_name.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
//...........................................................................................................
this.analyze = function(cid_hint, O) {
return this._analyze.apply(this, this._csg_cid_from_hint(cid_hint, O));
};
//-----------------------------------------------------------------------------------------------------------
this._analyze = function(csg, cid) {
var R, chr, ncr, xncr;
if (csg === 'u') {
chr = this._unicode_chr_from_cid(cid);
ncr = xncr = this._as_xncr(csg, cid);
} else {
chr = this._as_xncr(csg, cid);
xncr = this._as_xncr(csg, cid);
ncr = this._as_xncr('u', cid);
}
//.........................................................................................................
R = {
'~isa': 'NCR/info',
'chr': chr,
'uchr': this._unicode_chr_from_cid(cid),
'csg': csg,
'cid': cid,
'fncr': this._as_fncr(csg, cid),
'sfncr': this._as_sfncr(csg, cid),
'ncr': ncr,
'xncr': xncr,
'rsg': this._as_rsg(csg, cid)
};
//.........................................................................................................
return R;
};
//-----------------------------------------------------------------------------------------------------------
this._as_chr = function(csg, cid) {
if (csg === 'u') {
return this._unicode_chr_from_cid(cid);
}
return (this._analyze(csg, cid))['chr'];
};
//-----------------------------------------------------------------------------------------------------------
this._as_uchr = function(csg, cid) {
return this._unicode_chr_from_cid(cid);
};
//-----------------------------------------------------------------------------------------------------------
this._unicode_chr_from_cid = function(cid) {
if (!((0x000000 <= cid && cid <= 0x10ffff))) {
return null;
}
return String.fromCodePoint(cid);
};
// ### thx to http://perldoc.perl.org/Encode/Unicode.html ###
// hi = ( Math.floor ( cid - 0x10000 ) / 0x400 ) + 0xD800
// lo = ( cid - 0x10000 ) % 0x400 + 0xDC00
// return ( String.fromCharCode hi ) + ( String.fromCharCode lo )
//-----------------------------------------------------------------------------------------------------------
this._as_fncr = function(csg, cid) {
var ref, rsg;
rsg = (ref = this._as_rsg(csg, cid)) != null ? ref : csg;
return `${rsg}-${cid.toString(16)}`;
};
//-----------------------------------------------------------------------------------------------------------
this._as_sfncr = function(csg, cid) {
return `${csg}-${cid.toString(16)}`;
};
//-----------------------------------------------------------------------------------------------------------
this._as_xncr = function(csg, cid) {
if (csg === 'u' || (csg == null)) {
csg = '';
}
return `&${csg}#x${cid.toString(16)};`;
};
//-----------------------------------------------------------------------------------------------------------
this._as_rsg = function(csg, cid) {
var ref;
if (csg !== 'u') {
return csg;
}
return (ref = (this._aggregate(cid))['rsg']) != null ? ref : csg;
};
//-----------------------------------------------------------------------------------------------------------
this._as_range_name = function(csg, cid) {
var ref;
if (csg !== 'u') {
return this._as_rsg(csg, cid);
}
return (ref = (this._aggregate(cid))['block']) != null ? ref : this._as_rsg(csg, cid);
};
//===========================================================================================================
// ANALYZE ARGUMENTS
//-----------------------------------------------------------------------------------------------------------
this._csg_cid_from_hint = function(cid_hint, settings) {
var cid, csg, csg_of_cid_hint, csg_of_options, input_mode, type;
/* This helper is used to derive the correct CSG and CID from arguments as accepted by the `as_*` family
of methods, such as `NCR.as_fncr`, `NCR.as_rsg` and so on; its output may be directly applied to the
respective namesake private method (`NCR._as_fncr`, `NCR._as_rsg` and so on). The method arguments should
obey the following rules:
* Methods may be called with one or two arguments; the first is known as the 'CID hint', the second as
'settings'.
* The CID hint may be a number or a text; if it is a number, it is understood as a CID; if it
is a text, its interpretation is subject to the `settings[ 'input' ]` setting.
* Options must be an object with the optional members `input` and `csg`.
* `settings[ 'input' ]` is *only* observed if the CID hint is a text; it governs which kinds of character
references are recognized in the text. `input` may be one of `plain`, `ncr`, or `xncr`; it defaults to
`plain` (no character references will be recognized).
* `settings[ 'csg' ]` sets the character set sigil. If `csg` is set in the settings, then it will override
whatever the outcome of `NCR.csg_cid_from_chr` w.r.t. CSG is—in other words, if you call
`NCR.as_sfncr '&jzr#xe100', input: 'xncr', csg: 'u'`, you will get `u-e100`, with the numerically
equivalent codepoint from the `u` (Unicode) character set.
* Before CSG and CID are returned, they will be validated for plausibility.
*/
//.........................................................................................................
switch (type = type_of(settings)) {
case 'null':
case 'undefined':
csg_of_options = null;
input_mode = null;
break;
case 'object':
csg_of_options = settings['csg'];
input_mode = settings['input'];
break;
default:
throw new Error(`expected an object as second argument, got a ${type}`);
}
//.........................................................................................................
switch (type = type_of(cid_hint)) {
case 'float':
csg_of_cid_hint = null;
cid = cid_hint;
break;
case 'text':
[csg_of_cid_hint, cid] = this.csg_cid_from_chr(cid_hint, {
input: input_mode
});
break;
default:
throw new Error(`expected a text or a number as first argument, got a ${type}`);
}
//.........................................................................................................
if (csg_of_options != null) {
csg = csg_of_options;
} else if (csg_of_cid_hint != null) {
csg = csg_of_cid_hint;
} else {
csg = 'u';
}
//.........................................................................................................
// @validate_is_csg csg
this.validate_cid(csg, cid);
return [csg, cid];
};
//===========================================================================================================
// PATTERNS
//-----------------------------------------------------------------------------------------------------------
// G: grouped
// O: optional
name = /(?:[a-z][a-z0-9]*)/.source;
// nameG = ( /// ( (?: [a-z][a-z0-9]* ) | ) /// ).source
nameO = /(?:(?:[a-z][a-z0-9]*)|)/.source;
nameOG = /((?:[a-z][a-z0-9]*)|)/.source;
hex = /(?:x[a-fA-F0-9]+)/.source;
hexG = /(?:x([a-fA-F0-9]+))/.source;
dec = /(?:[0-9]+)/.source;
decG = /(?:([0-9]+))/.source;
//...........................................................................................................
this._csg_matcher = RegExp(`^${name}$`);
this._ncr_matcher = RegExp(`(?:&\\#(?:${hex}|${dec});)`);
this._xncr_matcher = RegExp(`(?:&${nameO}\\#(?:${hex}|${dec});)`);
this._ncr_csg_cid_matcher = RegExp(`(?:&()\\#(?:${hexG}|${decG});)`);
this._xncr_csg_cid_matcher = RegExp(`(?:&${nameOG}\\#(?:${hexG}|${decG});)`);
//...........................................................................................................
/* Matchers for surrogate sequences and non-surrogate, 'ordinary' characters: */
this._surrogate_matcher = /(?:[\ud800-\udbff][\udc00-\udfff])/;
this._nonsurrogate_matcher = /[^\ud800-\udbff\udc00-\udfff]/;
//...........................................................................................................
/* Matchers for the first character of a string, in three modes (`plain`, `ncr`, `xncr`): */
this._first_chr_matcher_plain = RegExp(`^(?:${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`);
this._first_chr_matcher_ncr = RegExp(`^(?:${this._surrogate_matcher.source}|${this._ncr_csg_cid_matcher.source}|${this._nonsurrogate_matcher.source})`);
this._first_chr_matcher_xncr = RegExp(`^(?:${this._surrogate_matcher.source}|${this._xncr_csg_cid_matcher.source}|${this._nonsurrogate_matcher.source})`);
//...........................................................................................................
this._plain_splitter = RegExp(`(${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`);
this._ncr_splitter = RegExp(`(${this._ncr_matcher.source}|${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`);
this._xncr_splitter = RegExp(`(${this._xncr_matcher.source}|${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`);
// #-----------------------------------------------------------------------------------------------------------
// @cid_range_from_rsg = ( rsg ) ->
// # [ csg, ... ] = rsg.split '-'
// unless ( R = @_ranges_by_rsg[ rsg ] )?
// throw new Error "unknown RSG: #{rpr rsg}"
// return R
// #-----------------------------------------------------------------------------------------------------------
// @validate_is_csg = ( x ) ->
// validate.text x
// throw new Error "not a valid CSG: #{rpr x}" unless ( x.match @_csg_matcher )?
// throw new Error "unknown CSG: #{rpr x}" unless @_names_and_ranges_by_csg[ x ]?
// return null
//-----------------------------------------------------------------------------------------------------------
this.validate_cid = function(csg, cid) {
validate.float(cid);
if (cid !== Math.floor(cid)) {
throw new Error(`expected an integer, got ${cid}`);
}
if (!(cid >= 0)) {
throw new Error(`expected a positive integer, got ${cid}`);
}
if ((csg === 'u') && !((0x000000 <= cid && cid <= 0x10ffff))) {
throw new Error(`expected an integer between 0x000000 and 0x10ffff, got 0x${cid.toString(16)}`);
}
return null;
};
// #===========================================================================================================
// class @XXX_Ncr extends Multimix
// @include @, { overwrite: true, } # instance methods
// # @include @, { overwrite: false, } # instance methods
// # @extend @, { overwrite: false, } # class methods
// #---------------------------------------------------------------------------------------------------------
// constructor: ( input_default = 'plain' ) ->
// super()
// debug '^44443^', ( k for k of @ )
// return undefined
}).call(this);
//# sourceMappingURL=main.js.map | loveencounterflow/ncr | lib/main.js | JavaScript | mit | 25,632 |
/**
* Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element).
*
* @example
* this.demoTest = function (browser) {
* browser.expect.element('body').to.have.property('className').equals('test-class');
* browser.expect.element('body').to.have.property('className').matches(/^something\ else/);
* browser.expect.element('body').to.not.have.property('classList').equals('test-class');
* browser.expect.element('body').to.have.property('classList').deep.equal(['class-one', 'class-two']);
* browser.expect.element('body').to.have.property('classList').contain('class-two');
* };
*
* @method property
* @param {string} property The property name
* @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default.
* @display .property(name)
* @api expect.element
*/
const BaseAssertion = require('./_element-assertion.js');
class PropertyAssertion extends BaseAssertion {
static get assertionType() {
return BaseAssertion.AssertionType.METHOD;
}
init(property, msg) {
super.init();
this.flag('attributeFlag', true);
this.property = property;
this.hasCustomMessage = typeof msg != 'undefined';
this.message = msg || 'Expected element <%s> to ' + (this.negate ? 'not have' : 'have') + ' dom property "' + property + '"';
this.start();
}
executeCommand() {
return this.executeProtocolAction('getElementProperty', [this.property]).then(result => {
if (!this.transport.isResultSuccess(result) || result.value === null) {
throw result;
}
return result;
}).catch(result => {
this.propertyNotFound();
return false;
});
}
onResultSuccess() {
if (this.retries > 0 && this.negate) {
return;
}
if (!this.hasCondition()) {
this.passed = !this.negate;
this.expected = this.negate ? 'not found' : 'found';
this.actual = 'found';
}
this.addExpectedInMessagePart();
}
propertyNotFound() {
this.processFlags();
this.passed = this.hasCondition() ? false : this.negate;
if (!this.passed && this.shouldRetry()) {
this.scheduleRetry();
} else {
this.addExpectedInMessagePart();
if (!this.hasCondition()) {
//this.expected = this.negate ? 'not found' : 'found';
this.actual = 'not found';
}
if (!this.negate) {
this.messageParts.push(' - property was not found');
}
this.done();
}
}
onResultFailed() {
this.passed = false;
}
}
module.exports = PropertyAssertion;
| beatfactor/nightwatch | lib/api/expect/assertions/element/property.js | JavaScript | mit | 2,710 |
import javax.naming.directory.DirContext;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.reference.DefaultEncoder;
public void ldapQueryBad(HttpServletRequest request, DirContext ctx) throws NamingException {
String organizationName = request.getParameter("organization_name");
String username = request.getParameter("username");
// BAD: User input used in DN (Distinguished Name) without encoding
String dn = "OU=People,O=" + organizationName;
// BAD: User input used in search filter without encoding
String filter = "username=" + userName;
ctx.search(dn, filter, new SearchControls());
}
public void ldapQueryGood(HttpServletRequest request, DirContext ctx) throws NamingException {
String organizationName = request.getParameter("organization_name");
String username = request.getParameter("username");
// ESAPI encoder
Encoder encoder = DefaultEncoder.getInstance();
// GOOD: Organization name is encoded before being used in DN
String safeOrganizationName = encoder.encodeForDN(organizationName);
String safeDn = "OU=People,O=" + safeOrganizationName;
// GOOD: User input is encoded before being used in search filter
String safeUsername = encoder.encodeForLDAP(username);
String safeFilter = "username=" + safeUsername;
ctx.search(safeDn, safeFilter, new SearchControls());
} | github/codeql | java/ql/src/Security/CWE/CWE-090/LdapInjectionJndi.java | Java | mit | 1,337 |
package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private TextArea input;
@FXML
private TextFlow display;
public void FocusInput(){
input.requestFocus();
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
Editor ed = new Editor();
input.textProperty().addListener((observableValue, s, s2) -> {
display.getChildren().clear();
ed.render(observableValue.getValue());
List x = ed.parse();
x.forEach(i -> {
List y = (List) i;
Text t1 = new Text(y.get(1) + " ");
if((int) y.get(0) == 1) t1.setFill(Color.BLUE);
display.getChildren().add(t1);
System.out.println(i);
});
});
}
}
| Jacob-Gray/Ario | src/sample/Controller.java | Java | mit | 1,145 |
namespace BookShop
{
using BookShop.Data;
using BookShop.Models;
using BookShop.Initializer;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Text;
public class StartUp
{
static void Main()
{
var input = Console.ReadLine();
using (var db = new BookShopContext())
{
var result = GetBooksByCategory(db, input);
Console.WriteLine(result);
}
}
public static string GetBooksByCategory(BookShopContext context, string input)
{
string[] categories = input.ToLower().Split(new[] { "\t", " ", Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries );
string[] titles = context.Books
.Where(b => b.BookCategories.Any(c => categories.Contains(c.Category.Name.ToLower())))
.Select(b => b.Title)
.OrderBy(b => b)
.ToArray();
var result = String.Join(Environment.NewLine, titles);
return result;
}
}
}
| DimitarIvanov8/software-university | DB_Advanced_Entity_Framework/Advanced Querying/Book Titles by Category StartUp/StartUp.cs | C# | mit | 1,130 |
const rangeParser = require(`parse-numeric-range`)
module.exports = language => {
if (!language) {
return ``
}
if (language.split(`{`).length > 1) {
let [splitLanguage, ...options] = language.split(`{`)
let highlightLines = [],
numberLines = false,
numberLinesStartAt
// Options can be given in any order and are optional
options.forEach(option => {
option = option.slice(0, -1)
// Test if the option is for line hightlighting
if (rangeParser.parse(option).length > 0) {
highlightLines = rangeParser.parse(option).filter(n => n > 0)
}
option = option.split(`:`)
// Test if the option is for line numbering
// Option must look like `numberLines: true` or `numberLines: <integer>`
// Otherwise we disable line numbering
if (
option.length === 2 &&
option[0] === `numberLines` &&
(option[1].trim() === `true` ||
Number.isInteger(parseInt(option[1].trim(), 10)))
) {
numberLines = true
numberLinesStartAt =
option[1].trim() === `true` ? 1 : parseInt(option[1].trim(), 10)
}
})
return {
splitLanguage,
highlightLines,
numberLines,
numberLinesStartAt,
}
}
return { splitLanguage: language }
}
| mingaldrichgan/gatsby | packages/gatsby-remark-prismjs/src/parse-line-number-range.js | JavaScript | mit | 1,302 |
import ruleError from './ruleError'
// Tags that have no associated components but are allowed even so
const componentLessTags = [
'mj-all',
'mj-class',
'mj-selector',
'mj-html-attribute',
]
export default function validateTag(element, { components }) {
const { tagName } = element
if (componentLessTags.includes(tagName)) return null
const Component = components[tagName]
if (!Component) {
return ruleError(
`Element ${tagName} doesn't exist or is not registered`,
element,
)
}
return null
}
| mjmlio/mjml | packages/mjml-validator/src/rules/validTag.js | JavaScript | mit | 539 |
class dximagetransform_microsoft_crblinds_1 {
constructor() {
// short bands () {get} {set}
this.bands = undefined;
// int Capabilities () {get}
this.Capabilities = undefined;
// string Direction () {get} {set}
this.Direction = undefined;
// float Duration () {get} {set}
this.Duration = undefined;
// float Progress () {get} {set}
this.Progress = undefined;
// float StepResolution () {get}
this.StepResolution = undefined;
}
}
module.exports = dximagetransform_microsoft_crblinds_1;
| mrpapercut/wscript | testfiles/COMobjects/JSclasses/DXImageTransform.Microsoft.CrBlinds.1.js | JavaScript | mit | 598 |
'use strict';
var webpack = require('webpack');
var cfg = {
entry: './src/main.jsx',
output: {
path: __dirname + '/dist',
filename: 'main.js',
},
externals: {
yaspm: 'commonjs yaspm'
},
target: process.env.NODE_ENV === 'web' ? 'web' : 'node-webkit',
module: {
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader?includePaths[]=' +
__dirname + '/src'
},
{
test: /\.(js|jsx)$/,
loader: 'jsx-loader?harmony'
}
]
},
plugins: [
new webpack.DefinePlugin({
'__NODEWEBKIT__': process.env.NODE_ENV === 'nodewebkit',
})
]
};
module.exports = cfg;
| cirocosta/ledmatrix | webpack.config.js | JavaScript | mit | 772 |
/**
* Created by ff on 2016/10/25.
*/
require('./style.css');
var vm = avalon.define({
$id:'map'
})
module.exports = vm; | orgrinDataOrganization/orgrinData | src/mv/map/index.js | JavaScript | mit | 123 |
///////////////////////////////////////////////////////////////////////////////
// This source file is part of Hect.
//
// Copyright (c) 2016 Colin Hill
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////
#include "DefaultScene.h"
#include "Hect/Runtime/Platform.h"
#include "Hect/Scene/Systems/InputSystem.h"
#include "Hect/Scene/Systems/PhysicsSystem.h"
#include "Hect/Scene/Systems/TransformSystem.h"
#include "Hect/Scene/Systems/BoundingBoxSystem.h"
#include "Hect/Scene/Systems/CameraSystem.h"
#include "Hect/Scene/Systems/DebugSystem.h"
#include "Hect/Scene/Systems/InterfaceSystem.h"
using namespace hect;
DefaultScene::DefaultScene(Engine& engine) :
Scene(engine),
_interface_system(*this, engine.asset_cache(), engine.platform(), engine.renderer(), engine.vector_renderer()),
_debug_system(*this, engine.asset_cache(), _interface_system),
_input_system(*this, engine.platform(), engine.settings()),
_camera_system(*this),
_bounding_box_system(*this, _debug_system),
_transform_system(*this, _bounding_box_system),
_physics_system(*this, _transform_system),
_scene_renderer(engine.asset_cache(), engine.task_pool())
{
Platform& platform = engine.platform();
if (platform.has_keyboard())
{
Keyboard& keyboard = platform.keyboard();
keyboard.register_listener(*this);
}
}
void DefaultScene::pre_tick(Seconds time_step)
{
Scene::refresh();
_input_system.update_axes(time_step);
_debug_system.clear_enqueued_debug_geometry();
}
void DefaultScene::post_tick(Seconds time_step)
{
_physics_system.wait_for_simulation_task();
_physics_system.sync_with_simulation();
_physics_system.begin_simulation_task(engine().task_pool(), time_step);
_transform_system.update_committed_transforms();
_camera_system.update_all_cameras();
_interface_system.tick_all_interfaces(time_step);
if (_debug_rendering_enabled)
{
_bounding_box_system.render_debug_geometry();
}
Scene::refresh();
}
void DefaultScene::tick(Seconds time_step)
{
pre_tick(time_step);
post_tick(time_step);
}
void DefaultScene::render(RenderTarget& target)
{
Renderer& renderer = engine().renderer();
_scene_renderer.render(*this, _camera_system, renderer, target);
_interface_system.render_all_interfaces();
}
void DefaultScene::receive_event(const KeyboardEvent& event)
{
if (event.is_key_down(Key::F5))
{
_debug_rendering_enabled = !_debug_rendering_enabled;
}
}
InterfaceSystem& DefaultScene::interface_system()
{
return _interface_system;
}
DebugSystem& DefaultScene::debug_system()
{
return _debug_system;
}
InputSystem& DefaultScene::input_system()
{
return _input_system;
}
CameraSystem& DefaultScene::camera_system()
{
return _camera_system;
}
BoundingBoxSystem& DefaultScene::bounding_box_system()
{
return _bounding_box_system;
}
TransformSystem& DefaultScene::transform_system()
{
return _transform_system;
}
PhysicsSystem& DefaultScene::physics_system()
{
return _physics_system;
}
| colinhect/hect | Engine/Source/Hect/Scene/Scenes/DefaultScene.cpp | C++ | mit | 4,169 |
package com.glazebrook.tictactoe.responses;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotNull;
import java.util.UUID;
public class JoinGameResponse {
@JsonProperty
@NotNull
private UUID gameId;
@JsonProperty
@NotNull
private UUID playerId;
@JsonProperty
@NotNull
private UUID token;
public JoinGameResponse() {
}
public JoinGameResponse(UUID gameId, UUID playerId, UUID token) {
this.gameId = gameId;
this.playerId = playerId;
this.token = token;
}
public UUID getGameId() {
return gameId;
}
public void setGameId(UUID gameId) {
this.gameId = gameId;
}
public UUID getToken() {
return token;
}
public void setToken(UUID token) {
this.token = token;
}
public UUID getPlayerId() {
return playerId;
}
public void setPlayerId(UUID playerId) {
this.playerId = playerId;
}
}
| JoshGlazebrook/tictactoe-glazebrook | api/src/main/java/com/glazebrook/tictactoe/responses/JoinGameResponse.java | Java | mit | 1,004 |
module HealthSeven::V2_6
class RorRor < ::HealthSeven::Message
attribute :msh, Msh, position: "MSH", require: true
attribute :msa, Msa, position: "MSA", require: true
attribute :errs, Array[Err], position: "ERR", multiple: true
attribute :sfts, Array[Sft], position: "SFT", multiple: true
attribute :uac, Uac, position: "UAC"
class Definition < ::HealthSeven::SegmentGroup
attribute :qrd, Qrd, position: "QRD", require: true
attribute :qrf, Qrf, position: "QRF"
class Patient < ::HealthSeven::SegmentGroup
attribute :pid, Pid, position: "PID", require: true
attribute :ntes, Array[Nte], position: "NTE", multiple: true
end
attribute :patient, Patient, position: "ROR_ROR.PATIENT"
class Order < ::HealthSeven::SegmentGroup
attribute :orc, Orc, position: "ORC", require: true
attribute :rxo, Rxo, position: "RXO", require: true
attribute :rxrs, Array[Rxr], position: "RXR", require: true, multiple: true
attribute :rxcs, Array[Rxc], position: "RXC", multiple: true
end
attribute :orders, Array[Order], position: "ROR_ROR.ORDER", require: true, multiple: true
end
attribute :definitions, Array[Definition], position: "ROR_ROR.DEFINITION", require: true, multiple: true
attribute :dsc, Dsc, position: "DSC"
end
end | niquola/health_seven | lib/health_seven/2.6/messages/ror_ror.rb | Ruby | mit | 1,296 |
'use strict';
const _ = require('lodash');
const path = require('path');
/**
* Special settings for use with serverless-offline.
*/
module.exports = {
prepareOfflineInvoke() {
// Use service packaging for compile
_.set(this.serverless, 'service.package.individually', false);
return this.serverless.pluginManager.spawn('webpack:validate').then(() => {
// Set offline location automatically if not set manually
if (!this.options.location && !_.get(this.serverless, 'service.custom.serverless-offline.location')) {
_.set(
this.serverless,
'service.custom.serverless-offline.location',
path.relative(this.serverless.config.servicePath, path.join(this.webpackOutputPath, 'service'))
);
}
return null;
});
}
};
| elastic-coders/serverless-webpack | lib/prepareOfflineInvoke.js | JavaScript | mit | 802 |
<?php
namespace Convict\Validator;
class Any implements Validator {
public function validate($key, $value)
{
}
public function coerce($value)
{
return $value;
}
}
| jsol/php-convict | src/Validator/Any.php | PHP | mit | 183 |
package com.mrmq.poker.common.glossary;
public enum ServiceType {
ADMIN("admin"),
POKER("poker");
String value;
private ServiceType(String value) {
this.value = value;
}
public String getValue(){
return value;
}
}
| quyenlm/pokersu | poker-common/src/main/java/com/mrmq/poker/common/glossary/ServiceType.java | Java | mit | 230 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Ch04_01BasicTessellation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Ch04_01BasicTessellation")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8aeb0b9b-bde8-4c56-a90f-582fde8da41c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| spazzarama/Direct3D-Rendering-Cookbook | Ch05_01TessellationPrimitives/Properties/AssemblyInfo.cs | C# | mit | 1,424 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Regex_Test_MatchCollection
{
class Program
{
static void Main(string[] args)
{
string pattern = "[A-Z][a-z]+ [A-Z][a-z]+";
Regex regex = new Regex(pattern);
string text = "Ivan Ivanov Martin Milenov Iordan Iovkov";
MatchCollection names = regex.Matches(text);
foreach(Match matches in names)
{
Console.WriteLine(matches.Groups[0]);
}
}
}
}
| VelizarMitrev/Programmming_Fundamentals | Regex Test/Regex Test MatchCollection/Program.cs | C# | mit | 647 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.06.05 at 08:50:12 PM SAMT
//
package ru.fsrar.wegais.infoversionttn;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the ru.fsrar.wegais.infoversionttn package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: ru.fsrar.wegais.infoversionttn
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link InfoVersionTTN }
*
*/
public InfoVersionTTN createInfoVersionTTN() {
return new InfoVersionTTN();
}
}
| ytimesru/kkm-pc-client | src/main/java/ru/fsrar/wegais/infoversionttn/ObjectFactory.java | Java | mit | 1,434 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MakeTime for Arabic/Islamic Higri Calendar</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
</head>
<body>
<div class="Paragraph">
<h2 dir="ltr">Example Output:</h2>
<?php
/**
* Example of MakeTime for Arabic/Islamic Higri Calendar
*
* @category I18N
* @package I18N_Arabic
* @author Khaled Al-Sham'aa <khaled@ar-php.org>
* @copyright 2006-2013 Khaled Al-Sham'aa
*
* @license LGPL <http://www.gnu.org/licenses/lgpl.txt>
* @link http://www.ar-php.org
*/
error_reporting(E_STRICT);
$time_start = microtime(true);
date_default_timezone_set('UTC');
require '../../Arabic.php';
$Arabic = new I18N_Arabic('Mktime');
$correction = $Arabic->mktimeCorrection(9, 1429);
$time = $Arabic->mktime(0, 0, 0, 9, 1, 1429, $correction);
echo "Calculated first day of Ramadan 1429 unix timestamp is: $time<br>";
$Gregorian = date('l F j, Y', $time);
echo "Which is $Gregorian in Gregorian calendar<br>";
$days = $Arabic->hijriMonthDays(9, 1429);
echo "That Ramadan has $days days in total";
?>
</div><br />
<div class="Paragraph">
<h2>Example Code:</h2>
<?php
$code = <<< END
<?php
date_default_timezone_set('UTC');
require '../../Arabic.php';
\$Arabic = new I18N_Arabic('Mktime');
\$correction = \$Arabic->mktimeCorrection(9, 1429);
\$time = \$Arabic->mktime(0, 0, 0, 9, 1, 1429, \$correction);
echo "Calculated first day of Ramadan 1429 unix timestamp is: \$time<br>";
\$Gregorian = date('l F j, Y', \$time);
echo "Which is \$Gregorian in Gregorian calendar";
\$days = \$Arabic->hijriMonthDays(9, 1429);
echo "That Ramadan has \$days days in total";
END;
highlight_string($code);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<hr />Total execution time is $time seconds<br />\n";
echo 'Amount of memory allocated to this script is ' . memory_get_usage() . ' bytes';
$included_files = get_included_files();
echo '<h4>Names of included or required files:</h4><ul>';
foreach ($included_files as $filename) {
echo "<li>$filename</li>";
}
echo '</ul>';
?>
<a href="../Docs/I18N_Arabic/_Arabic---Mktime.php.html" target="_blank">Related Class Documentation</a>
</div>
</body>
</html>
| jtarleton/jt-web | lib/i18n/Arabic/Examples/Mktime.php | PHP | mit | 2,458 |
/**
* (c) raptor_MVK, 2015. All rights reserved.
*/
package ru.mvk.biblioGuide.service;
import org.jetbrains.annotations.NotNull;
import ru.mvk.biblioGuide.dao.BookCaseDao;
import ru.mvk.biblioGuide.model.BookCase;
import ru.mvk.iluvatar.descriptor.ListViewInfo;
import ru.mvk.iluvatar.descriptor.ListViewInfoImpl;
import ru.mvk.iluvatar.descriptor.ViewInfo;
import ru.mvk.iluvatar.descriptor.ViewInfoImpl;
import ru.mvk.iluvatar.descriptor.column.NumColumnInfo;
import ru.mvk.iluvatar.descriptor.column.StringColumnInfo;
import ru.mvk.iluvatar.descriptor.field.NaturalFieldInfo;
import ru.mvk.iluvatar.descriptor.field.TextFieldInfo;
import ru.mvk.iluvatar.module.db.HibernateAdapter;
import ru.mvk.iluvatar.service.ViewServiceDescriptor;
import ru.mvk.iluvatar.service.ViewServiceImpl;
import ru.mvk.iluvatar.view.Layout;
public class BookCaseViewService extends ViewServiceImpl<BookCase> {
public BookCaseViewService(@NotNull HibernateAdapter hibernateAdapter,
@NotNull Layout layout) {
super(new ViewServiceDescriptor<>(new BookCaseDao(hibernateAdapter),
prepareBookCaseViewInfo(), prepareAuthorListViewInfo()), layout, "Шкафы");
}
@NotNull
private static ViewInfo<BookCase> prepareBookCaseViewInfo() {
@NotNull ViewInfo<BookCase> viewInfo = new ViewInfoImpl<>(BookCase.class);
viewInfo.addFieldInfo("name", new TextFieldInfo("Название", 20));
viewInfo.addFieldInfo("shelfCount", new NaturalFieldInfo<>(Byte.class,
"Кол-во полок", 2));
return viewInfo;
}
@NotNull
private static ListViewInfo<BookCase> prepareAuthorListViewInfo() {
@NotNull ListViewInfo<BookCase> listViewInfo = new ListViewInfoImpl<>(BookCase.class);
listViewInfo.addColumnInfo("lowerName", new StringColumnInfo("Название", 20));
listViewInfo.addColumnInfo("lowerInitials", new NumColumnInfo("Полок", 5));
return listViewInfo;
}
}
| raptor-mvk/BiblioGuide-Java | src/ru/mvk/biblioGuide/service/BookCaseViewService.java | Java | mit | 1,907 |
let widget = document.getElementsByClassName('markdownx-widget')[0];
let element = document.getElementsByClassName('markdownx');
let element_divs = element[0].getElementsByTagName('div');
let div_editor = element_divs[0];
let div_preview = element_divs[1];
let navbar_bar = document.getElementsByClassName('markdownx-toolbar')[0].getElementsByTagName('li');
let btn_preview = navbar_bar[0];
let btn_fullscreen = navbar_bar[1];
var turn_active = function(element) {
value = element.classname;
classval = element.getAttribute('class');
if (value.indexOf('active') >= 0) {
element.removeClass('active');
}
else {
value += 'active'
}
}
var refresh_pretty = function() {
// 每次有都需要重新渲染code
PR.prettyPrint();
};
var enable_preview = function() {
var class_btn_preview = btn_preview.getAttribute('class');
var index = class_btn_preview.indexOf('active');
if (index >= 0) {
btn_preview.setAttribute('class', '');
div_editor.setAttribute('class', 'col-md-12 child-left');
div_preview.style.display = 'none';
}
else {
btn_preview.setAttribute('class', 'active');
div_editor.setAttribute('class', 'col-md-6 child-left');
div_preview.style.display = 'block';
}
};
var enable_fullscreen = function() {
var class_btn_fullscreen = btn_fullscreen.getAttribute('class');
var index = class_btn_fullscreen.indexOf('active');
if (index >= 0) {
btn_fullscreen.setAttribute('class', '');
widget.setAttribute('class', 'markup-widget');
}
else{
btn_fullscreen.setAttribute('class', 'active');
widget.setAttribute('class', 'markup-widget fullscreen');
}
}
Object.keys(element).map(key =>
element[key].addEventListener('markdownx.update', refresh_pretty)
);
btn_preview.addEventListener('click', enable_preview);
btn_fullscreen.addEventListener('click', enable_fullscreen);
| BaskerShu/typeidea | typeidea/typeidea/themes/default/static/js/markdownx-widget.js | JavaScript | mit | 1,967 |
module.exports = {};
var app_data = {};
function initCharts()
{
$(document).ready(function() {
$.get(app_data.config.analytics_data_route, function(analytics_data) {
data = analytics_data.data;
max_val = analytics_data.highest_value;
var parseDate = d3.time.format('%Y%m%d').parse;
data.forEach(function(d) {
d.date = parseDate(d.date);
});
$('.sessions-value').html(formatAnalyticsValue((analytics_data.total_sessions).toString()));
$('.views-value').html(formatAnalyticsValue((analytics_data.total_views).toString()));
d3.select(window).on('resize', resize);
loadCharts();
}, 'json');
});
}
function loadChart(data, max_val, selector, graph_width, graph_height)
{
var margin = { top: 20, right: 0, bottom: 30, left: 50 },
width = graph_width - margin.left - margin.right,
height = graph_height - margin.top - margin.bottom;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var color = d3.scale.category10();
var x_axis = d3.svg.axis().scale(x).orient('bottom'); //.tickFormat(d3.time.format('%m/%d/%y'));
var y_axis = d3.svg.axis().scale(y).orient('left').ticks(6);
var line = d3.svg.line()
.interpolate('cardinal')
.tension(0.8)
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.val); });
var line_gridline = d3.svg.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
var area = d3.svg.area()
.interpolate('cardinal')
.tension(0.8)
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.val); });
d3.select(selector + ' > svg').remove();
var svg = d3.select(selector).append('svg')
.attr('viewBox', '0 0 ' + graph_width + ' ' + graph_height)
.attr('perserveAspectRatio', 'xMinYMid')
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
color.domain([ 'sessions', 'views' ]);
var analytics = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, val: +d[name]};
})
};
});
var x_extent = d3.extent(data, function(d) { return d.date; });
x.domain(x_extent);
y.domain([
d3.min(analytics, function(c) { return 0; }),
d3.max(analytics, function(c) { return max_val; /*d3.max(c.values, function(v) { return v.val; });*/ })
]);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(x_axis);
svg.append('g')
.attr('class', 'y axis')
.call(y_axis)
.append('text')
.style('text-anchor', 'end');
var gridline_data = [];
svg.selectAll('.y.axis .tick').each(function(data) {
var tick = d3.select(this);
var transform = d3.transform(tick.attr('transform')).translate;
if (data > 0)
{
gridline_data.push({ values: [[x_extent[0], transform[1]], [x_extent[1], transform[1]]] });
}
});
gridline_data.forEach(function(data) {
svg.append('line')
.attr('class', 'gridline')
.attr('x1', x(data.values[0][0]))
.attr('x2', x(data.values[1][0]))
.attr('y1', data.values[0][1])
.attr('y2', data.values[1][1]);
});
var analytics_line = svg.selectAll('.analytics_line')
.data(analytics)
.enter().append('g')
.attr('class', 'analytics_line');
analytics_line.append('path')
.attr('class', 'line')
.attr('d', function(d) { return line(d.values); })
.style('stroke', function(d) { return '#f2711c'; });
analytics_line.append('path')
.attr('class', 'area')
.attr('d', function(d) { return area(d.values); })
.style('fill', function(d) { return '#f2711c'; });
/*analytics.forEach(function(category) {
category.values.forEach(function(item) {
analytics_line.append('circle')
.attr('class', 'dot')
.attr('r', 4)
.attr('cx', x(item.date))
.attr('cy', y(item.val))
.style('fill', '#f2711c');
});
});*/
}
function formatAnalyticsValue(value)
{
var formatted_val = '';
var c = 1;
for (var i=value.length-1; i>=0; i--)
{
formatted_val = (c++ % 3 == 0 && i > 0 ? ' ' : '') + value.substring(i, i+1) + formatted_val;
}
return formatted_val;
}
var aspect = 4;
var chart = null;
var data = null;
var max_val = 0;
var resize_timeout = -1;
function resize()
{
if (resize_timeout != -1) clearTimeout(resize_timeout);
resize_timeout = setTimeout(function() {
resize_timeout = -1;
loadCharts();
}, 1000);
}
function loadCharts()
{
if (data == null) return;
var width = $('.analytics-graph').width();
var height = Math.max(200, $('.analytics-graph').width()/aspect); //prevents height to be smaller than 200px
loadChart(data, max_val, '.analytics-graph', width, height);
chart = $('.analytics-graph > svg');
}
module.exports.init = function(trans, config) {
app_data.trans = trans;
app_data.config = config;
$(document).ready(function() {
initCharts();
});
};
| neonbug/meexo-common | src/assets/admin_assets/js/app/src/modules/dashboard.js | JavaScript | mit | 5,037 |
const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
jasmine.getEnv().clearReporters(); // remove default reporter logs
jasmine.getEnv().addReporter(new SpecReporter({ // add jasmine-spec-reporter
spec: {
displayPending: true,
},
summary: {
displayDuration: true,
}
})); | royNiladri/js-big-decimal | spec/helper/reporter.js | JavaScript | mit | 317 |
/*
* Copyright (c) 2009 Piotr Piastucki
*
* This file is part of Patchca CAPTCHA library.
*
* Patchca 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 3 of the License, or
* (at your option) any later version.
*
* Patchca 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 Patchca. If not, see <http://www.gnu.org/licenses/>.
*/
package cn.osworks.aos.core.captcha.filter.library;
public class DoubleRippleImageOp extends RippleImageOp {
@Override
protected void transform(int x, int y, double[] t) {
double tx = Math.sin((double) y / yWavelength + yRandom) + 1.3 * Math.sin((double) 0.6 * y / yWavelength + yRandom);
double ty = Math.cos((double) x / xWavelength + xRandom) + 1.3 * Math.cos((double) 0.6 * x / xWavelength + xRandom);
t[0] = x + xAmplitude * tx;
t[1] = y + yAmplitude * ty;
}
}
| thomasloto/migang-crawler | src/aos/java/cn/osworks/aos/core/captcha/filter/library/DoubleRippleImageOp.java | Java | mit | 1,248 |
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="">
<!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Nom de la conférence</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic' rel='stylesheet' type='text/css'>
<!--[if lt IE 9]>
<script src="js/vendor/html5-3.6-respond-1.4.2.min.js"></script>
<![endif]-->
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<aside id="loader">
<p>Nom de la conférence</p>
</aside>
<div id="t-template">
<div class="container-fluid rh-template" id="rh-template">
<div class="row">
<?php include('include/menu.php'); ?>
<main role="main" class="col-xs-12 col-lg-10">
<section class="rh-conference">
<article class="col-xs-12 col-sm-6 col-lg-6 rh-modal-affiche">
<figure><img src="img/affiche.jpg"></figure>
</article>
<article class="col-xs-12 col-sm-6 col-lg-6 rh-modal-description">
<button type="button" class="btn btn-success align-center">Inscription</button>
<hr>
<h2 class="align-center">Info conférence :<br> L'intégration de la génération Y en entreprise</h2>
<hr>
<hr>
<ul class="rh-modal-heure">
<li class="full-gauche">07/07/2016</li>
<li class="full-droite">15h00</li>
</ul>
<hr>
<hr>
<ul class="rh-modal-favoris">
<li class="full-gauche">
<a href="#"><i class="glyphicon glyphicon-heart"></i></a>
</li>
<li class="full-droite">
<a href="#"><i class="glyphicon glyphicon-star"></i></a>
<a href="#"><i class="glyphicon glyphicon-star"></i></a>
<a href="#"><i class="glyphicon glyphicon-star-empty"></i></a>
<a href="#"><i class="glyphicon glyphicon-star-empty"></i></a>
<a href="#"><i class="glyphicon glyphicon-star-empty"></i></a>
</li>
</ul>
<p>A l'ère d'un monde du travail changeant, nous vous proposons une présentation de notre cabinet de conseil FutuRH 2.0 sur la digitalisation des fonctions RH. Cette présentation sera l'occasion de vous sensibiliser sur la transformation digitale des différents services RH et des nouvelles méthodes de travail qui en découlent, ainsi que les avantages pour une entreprise de se digitaliser. Dans un jeu de rôles ludique, nous espérons vous voir nombreux pour partager notre passion !</p>
<ul class="rh-modal-reseaux">
<li><button type="button" class="btn btn-success">Telecharger PDF</button></li>
<li><button type="button" class="btn btn-success">Facebook</button></li>
<li><button type="button" class="btn btn-success">twitter</button></li>
</ul>
<hr>
<div class="row">
<div class="col-xs-12 col-sm-4 col-lg-4 rh-modal-photo-conferencier">
<figure><img src="img/tof_conferencier.jpg"></figure>
</div>
<div class="col-xs-12 col-sm-8 col-lg-8 rh-modal-descriptif-conferencier">
<h3>Info conférencier : <br> David Bossdar</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur faucibus accumsan nibh maximus cursus. Proin purus ex, sodales a diam eu, sagittis viverra tellus. Vivamus eget ultricies justo. Aliquam vitae mattis justo. Mauris sollicitudin placerat turpis eget hendrerit. Aliquam semper justo massa, quis lobortis purus varius a. Nam lorem mi, interdum sit amet ullamcorper eu, pharetra vitae est. Suspendisse tempor elit id volutpat maximus.</p>
<br>
<button type="button" class="btn btn-success">linkedin</button>
</div>
</div>
</article>
</section>
</main>
</div>
</div>
</div>
<script src="js/vendor/jquery-1.11.2.min.js"></script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/vendor/wow.js"></script>
<script src="js/main.js"></script>
</body>
</html> | Corjo/Website-of-M.-Roller | template.php | PHP | mit | 6,141 |
//
// Created by Yorick on 18/10/2016.
//
#include "Room.h"
#include "../Rng.h"
using namespace std;
Room::Room(Coordinate coordinate, RoomType roomType, int securityLevel) {
_coordinate = coordinate;
_securityLevel = securityLevel;
_type = roomType;
_visited = false;
if (coordinate.x == 0 && coordinate.y == 0) {
throw 8;
}
_size = (RoomSize) Rng::getRandomIntBetween(0, 3);
_curiosity = (RoomCuriosity) Rng::getRandomIntBetween(0, 10);
}
Room::~Room() {
}
void Room::addDoor(Corridor *newCorridor, Direction direction) {
Room *newRoom = newCorridor->otherSide(this);
if (direction == Direction::NORTH) {
if (this->getCoordinate()->x == newRoom->getCoordinate()->x &&
this->getCoordinate()->y - newRoom->getCoordinate()->y == 1) {
direction = Direction::NORTH;
} else if (this->getCoordinate()->y == newRoom->getCoordinate()->y &&
this->getCoordinate()->x - newRoom->getCoordinate()->x == -1) {
direction = Direction::EAST;
} else if (this->getCoordinate()->x == newRoom->getCoordinate()->x &&
this->getCoordinate()->y - newRoom->getCoordinate()->y == -1) {
direction = Direction::SOUTH;
} else if (this->getCoordinate()->y == newRoom->getCoordinate()->y &&
this->getCoordinate()->x - newRoom->getCoordinate()->x == 1) {
direction = Direction::WEST;
}
}
if (_doors[direction]) {
delete _doors[direction];
throw -1212;
}
_doors[direction] = newCorridor;
}
Room *Room::getRoomBehindDoor(Direction direction, int securityLevel) {
Corridor *targetCorridor = _doors[direction];
if (targetCorridor) {
Room *target = targetCorridor->otherSide(this);
if (target && (target->getSecurityLevel() <= securityLevel || securityLevel == -1)) {
return target;
}
}
return nullptr;
}
void Room::addMonster(Monster monster) {
_monsters.push_back(monster);
}
void Room::clearRoom() {
_monsters.clear();
}
bool Room::hasMonsters() {
return !_monsters.empty();
}
bool Room::hasLivingMonsters() {
int count = 0;
for (int i = 0; i < _monsters.size(); ++i) {
if (_monsters[i].getCurrentHp() > 0) {
count++;
}
}
return count > 0;
}
Corridor *Room::getCorridorBehindDoor(Direction direction, int securityLevel) {
Corridor *targetCorridor = _doors[direction];
if (targetCorridor) {
Room *target = targetCorridor->otherSide(this);
if (target && (target->getSecurityLevel() <= securityLevel || securityLevel == -1)) {
return targetCorridor;
}
}
return nullptr;
}
void Room::addItemToLootList(Item *item) {
if (_lootList.find(item) == _lootList.end()) {
_lootList[item] = 1;
} else {
_lootList[item] += 1;
}
}
void Room::removeItemFromLootList(Item *item) {
if (_lootList.find(item) != _lootList.end()) {
if (_lootList[item] == 1) {
_lootList.erase(item);
} else if (_lootList[item] > 1) {
_lootList[item] -= 1;
}
}
}
void Room::setAsSecurityLevelUpgrade() {
if (_type == RoomType::NORMAL) {
_type = RoomType::UPGRADE;
}
}
| Yorick666/The-Elder-Codes | dungeon/Room.cpp | C++ | mit | 3,313 |
using System.ComponentModel;
namespace K4W.KinectDrone.Core.Enums
{
public enum DroneFlyingAction
{
[Description("Unkown")]
Unknown = 0,
[Description("Emergency")]
Emergency = 1,
[Description("Land")]
Land = 2,
[Description("Takeoff")]
TakeOff = 4
}
}
| KinectingForWindows/GIK-KinectingARDrone | src/K4W.KinectDrone.Core/Enums/DroneFlyingAction.cs | C# | mit | 332 |
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: google/api/servicecontrol/v1/log_entry.proto
package google_api_servicecontrol_v1
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "go.pedge.io/pb/gogo/google/api"
import google_logging_type "go.pedge.io/pb/gogo/google/logging/type"
import google_protobuf1 "github.com/gogo/protobuf/types"
import google_protobuf2 "github.com/gogo/protobuf/types"
import google_protobuf3 "github.com/gogo/protobuf/types"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// An individual log entry.
type LogEntry struct {
// Required. The log to which this log entry belongs. Examples: `"syslog"`,
// `"book_log"`.
Name string `protobuf:"bytes,10,opt,name=name,proto3" json:"name,omitempty"`
// The time the event described by the log entry occurred. If
// omitted, defaults to operation start time.
Timestamp *google_protobuf3.Timestamp `protobuf:"bytes,11,opt,name=timestamp" json:"timestamp,omitempty"`
// The severity of the log entry. The default value is
// `LogSeverity.DEFAULT`.
Severity google_logging_type.LogSeverity `protobuf:"varint,12,opt,name=severity,proto3,enum=google.logging.type.LogSeverity" json:"severity,omitempty"`
// A unique ID for the log entry used for deduplication. If omitted,
// the implementation will generate one based on operation_id.
InsertId string `protobuf:"bytes,4,opt,name=insert_id,json=insertId,proto3" json:"insert_id,omitempty"`
// A set of user-defined (key, value) data that provides additional
// information about the log entry.
Labels map[string]string `protobuf:"bytes,13,rep,name=labels" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
// The log entry payload, which can be one of multiple types.
//
// Types that are valid to be assigned to Payload:
// *LogEntry_ProtoPayload
// *LogEntry_TextPayload
// *LogEntry_StructPayload
Payload isLogEntry_Payload `protobuf_oneof:"payload"`
}
func (m *LogEntry) Reset() { *m = LogEntry{} }
func (m *LogEntry) String() string { return proto.CompactTextString(m) }
func (*LogEntry) ProtoMessage() {}
func (*LogEntry) Descriptor() ([]byte, []int) { return fileDescriptorLogEntry, []int{0} }
type isLogEntry_Payload interface {
isLogEntry_Payload()
}
type LogEntry_ProtoPayload struct {
ProtoPayload *google_protobuf1.Any `protobuf:"bytes,2,opt,name=proto_payload,json=protoPayload,oneof"`
}
type LogEntry_TextPayload struct {
TextPayload string `protobuf:"bytes,3,opt,name=text_payload,json=textPayload,proto3,oneof"`
}
type LogEntry_StructPayload struct {
StructPayload *google_protobuf2.Struct `protobuf:"bytes,6,opt,name=struct_payload,json=structPayload,oneof"`
}
func (*LogEntry_ProtoPayload) isLogEntry_Payload() {}
func (*LogEntry_TextPayload) isLogEntry_Payload() {}
func (*LogEntry_StructPayload) isLogEntry_Payload() {}
func (m *LogEntry) GetPayload() isLogEntry_Payload {
if m != nil {
return m.Payload
}
return nil
}
func (m *LogEntry) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *LogEntry) GetTimestamp() *google_protobuf3.Timestamp {
if m != nil {
return m.Timestamp
}
return nil
}
func (m *LogEntry) GetSeverity() google_logging_type.LogSeverity {
if m != nil {
return m.Severity
}
return google_logging_type.LogSeverity_DEFAULT
}
func (m *LogEntry) GetInsertId() string {
if m != nil {
return m.InsertId
}
return ""
}
func (m *LogEntry) GetLabels() map[string]string {
if m != nil {
return m.Labels
}
return nil
}
func (m *LogEntry) GetProtoPayload() *google_protobuf1.Any {
if x, ok := m.GetPayload().(*LogEntry_ProtoPayload); ok {
return x.ProtoPayload
}
return nil
}
func (m *LogEntry) GetTextPayload() string {
if x, ok := m.GetPayload().(*LogEntry_TextPayload); ok {
return x.TextPayload
}
return ""
}
func (m *LogEntry) GetStructPayload() *google_protobuf2.Struct {
if x, ok := m.GetPayload().(*LogEntry_StructPayload); ok {
return x.StructPayload
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*LogEntry) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _LogEntry_OneofMarshaler, _LogEntry_OneofUnmarshaler, _LogEntry_OneofSizer, []interface{}{
(*LogEntry_ProtoPayload)(nil),
(*LogEntry_TextPayload)(nil),
(*LogEntry_StructPayload)(nil),
}
}
func _LogEntry_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*LogEntry)
// payload
switch x := m.Payload.(type) {
case *LogEntry_ProtoPayload:
_ = b.EncodeVarint(2<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.ProtoPayload); err != nil {
return err
}
case *LogEntry_TextPayload:
_ = b.EncodeVarint(3<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.TextPayload)
case *LogEntry_StructPayload:
_ = b.EncodeVarint(6<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.StructPayload); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("LogEntry.Payload has unexpected type %T", x)
}
return nil
}
func _LogEntry_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*LogEntry)
switch tag {
case 2: // payload.proto_payload
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf1.Any)
err := b.DecodeMessage(msg)
m.Payload = &LogEntry_ProtoPayload{msg}
return true, err
case 3: // payload.text_payload
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.Payload = &LogEntry_TextPayload{x}
return true, err
case 6: // payload.struct_payload
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(google_protobuf2.Struct)
err := b.DecodeMessage(msg)
m.Payload = &LogEntry_StructPayload{msg}
return true, err
default:
return false, nil
}
}
func _LogEntry_OneofSizer(msg proto.Message) (n int) {
m := msg.(*LogEntry)
// payload
switch x := m.Payload.(type) {
case *LogEntry_ProtoPayload:
s := proto.Size(x.ProtoPayload)
n += proto.SizeVarint(2<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case *LogEntry_TextPayload:
n += proto.SizeVarint(3<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.TextPayload)))
n += len(x.TextPayload)
case *LogEntry_StructPayload:
s := proto.Size(x.StructPayload)
n += proto.SizeVarint(6<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
func init() {
proto.RegisterType((*LogEntry)(nil), "google.api.servicecontrol.v1.LogEntry")
}
func init() {
proto.RegisterFile("google/api/servicecontrol/v1/log_entry.proto", fileDescriptorLogEntry)
}
var fileDescriptorLogEntry = []byte{
// 425 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x4d, 0x8b, 0xdb, 0x30,
0x10, 0x86, 0xe3, 0xcd, 0x36, 0x8d, 0xc7, 0xc9, 0x52, 0xc4, 0x42, 0x5d, 0x37, 0x50, 0xd3, 0x42,
0xc9, 0xa1, 0xc8, 0x6c, 0xf6, 0xb2, 0xfd, 0x38, 0xb4, 0x81, 0x42, 0x5a, 0x72, 0x58, 0xb4, 0xbd,
0x07, 0x25, 0x51, 0x85, 0xa8, 0x22, 0x19, 0x5b, 0x31, 0xf5, 0x4f, 0xee, 0xbf, 0x28, 0xd6, 0x87,
0xbb, 0xdd, 0x85, 0xdc, 0x66, 0x34, 0xcf, 0x3b, 0x33, 0xef, 0x08, 0xde, 0x71, 0xad, 0xb9, 0x64,
0x05, 0x2d, 0x45, 0x51, 0xb3, 0xaa, 0x11, 0x3b, 0xb6, 0xd3, 0xca, 0x54, 0x5a, 0x16, 0xcd, 0x55,
0x21, 0x35, 0xdf, 0x30, 0x65, 0xaa, 0x16, 0x97, 0x95, 0x36, 0x1a, 0xcd, 0x1c, 0x8d, 0x69, 0x29,
0xf0, 0xff, 0x34, 0x6e, 0xae, 0xb2, 0xd9, 0xbd, 0x5e, 0x54, 0x29, 0x6d, 0xa8, 0x11, 0x5a, 0xd5,
0x4e, 0x9b, 0xbd, 0xf5, 0x55, 0xa9, 0x39, 0x17, 0x8a, 0x17, 0xa6, 0x2d, 0x6d, 0xb2, 0xa9, 0x59,
0xc3, 0x2a, 0x61, 0xfc, 0x8c, 0xec, 0x85, 0xe7, 0x6c, 0xb6, 0x3d, 0xfe, 0x2c, 0xa8, 0x0a, 0xa5,
0xd9, 0xc3, 0x52, 0x6d, 0xaa, 0xe3, 0xce, 0xf8, 0xea, 0xab, 0x87, 0x55, 0x23, 0x0e, 0xac, 0x36,
0xf4, 0x50, 0x3a, 0xe0, 0xf5, 0x9f, 0x21, 0x8c, 0xd7, 0x9a, 0x7f, 0xed, 0x0c, 0x21, 0x04, 0xe7,
0x8a, 0x1e, 0x58, 0x0a, 0x79, 0x34, 0x8f, 0x89, 0x8d, 0xd1, 0x0d, 0xc4, 0xbd, 0x26, 0x4d, 0xf2,
0x68, 0x9e, 0x2c, 0x32, 0xec, 0x2d, 0x87, 0xae, 0xf8, 0x47, 0x20, 0xc8, 0x3f, 0x18, 0x7d, 0x82,
0x71, 0xb0, 0x91, 0x4e, 0xf2, 0x68, 0x7e, 0xb1, 0xc8, 0x83, 0xd0, 0xfb, 0xc5, 0x9d, 0x5f, 0xbc,
0xd6, 0xfc, 0xce, 0x73, 0xa4, 0x57, 0xa0, 0x97, 0x10, 0x0b, 0x55, 0xb3, 0xca, 0x6c, 0xc4, 0x3e,
0x3d, 0xb7, 0x0b, 0x8d, 0xdd, 0xc3, 0xb7, 0x3d, 0xfa, 0x0e, 0x23, 0x49, 0xb7, 0x4c, 0xd6, 0xe9,
0x34, 0x1f, 0xce, 0x93, 0xc5, 0x02, 0x9f, 0xfa, 0x04, 0x1c, 0x0c, 0xe2, 0xb5, 0x15, 0xd9, 0x98,
0xf8, 0x0e, 0xe8, 0x23, 0x4c, 0xad, 0x8f, 0x4d, 0x49, 0x5b, 0xa9, 0xe9, 0x3e, 0x3d, 0xb3, 0x26,
0x2f, 0x1f, 0x99, 0xfc, 0xa2, 0xda, 0xd5, 0x80, 0x4c, 0x6c, 0x7e, 0xeb, 0x58, 0xf4, 0x06, 0x26,
0x86, 0xfd, 0x36, 0xbd, 0x76, 0xd8, 0x2d, 0xba, 0x1a, 0x90, 0xa4, 0x7b, 0x0d, 0xd0, 0x67, 0xb8,
0x70, 0x9f, 0xd2, 0x63, 0x23, 0x3b, 0xe2, 0xf9, 0xa3, 0x11, 0x77, 0x16, 0x5b, 0x0d, 0xc8, 0xd4,
0x09, 0x7c, 0x87, 0xec, 0x3d, 0x24, 0xf7, 0x56, 0x47, 0xcf, 0x60, 0xf8, 0x8b, 0xb5, 0x69, 0x64,
0xaf, 0xd2, 0x85, 0xe8, 0x12, 0x9e, 0x34, 0x54, 0x1e, 0x99, 0x5d, 0x3e, 0x26, 0x2e, 0xf9, 0x70,
0x76, 0x13, 0x2d, 0x63, 0x78, 0xea, 0xa7, 0x2e, 0xaf, 0x21, 0xdf, 0xe9, 0xc3, 0xc9, 0x53, 0x2d,
0xa7, 0xe1, 0x56, 0xb7, 0xd6, 0x66, 0xb4, 0x1d, 0xd9, 0xe5, 0xae, 0xff, 0x06, 0x00, 0x00, 0xff,
0xff, 0x5b, 0x7a, 0x37, 0x09, 0x15, 0x03, 0x00, 0x00,
}
| peter-edge/pb | gogo/google/api/servicecontrol/v1/log_entry.pb.go | GO | mit | 9,725 |
Given /^I have installed the plugin$/ do
# Do nothing here
end
Given /^Nark is setup to monitor my application$/ do
Capybara.app = Nark::Middleware.with(DummyApp)
end
Given /^I have a application I want to track$/ do
# Do nothing here
end
When /^I created the following plugin$/ do |string|
eval string
end
Then /^The "([^"]*)" plugin should be created$/ do |plugin_name|
steps %{
Then a file named "plugins/#{plugin_name}.rb" should exist
}
end
Then /^it should be included$/ do
params = {
:name=>"requests",
:description=>"Fallback description: Use the description macro to define the plugins description"
}
expect(Nark.available_plugins).to include(params)
end
Then /^the "(.*?)" will be accessible via "(.*?)"$/ do |method, module_name|
expect(module_name.constantize).to respond_to(method.to_sym)
end
Then /^the "(.*?)" should be (\d+)$/ do |method, value|
expect(Nark.send(method.to_sym)).to eql(value)
end
When /^I request a page$/ do
visit '/'
end
Then /^the total requests should be (\d+)$/ do |amount|
expect(Nark.total_requests).to eql(amount.to_i)
end
Then /^the "(.*?)" should be$/ do |method, string|
expect(Nark.send(method.to_sym)).to eql(eval(string))
end
When /^I setup Nark with the following$/ do |string|
eval string
end
Then /^the "(.*?)" should be "(.*?)"$/ do |method, value|
expect(Nark.send(method.to_sym)).to eql value
end
Then /^(\d+) plugins should be loaded$/ do |amount|
expect(Nark.available_plugins.count).to eql(amount.to_i)
end
Then /^the plugin path should be set to "(.*?)"$/ do |value|
expect(Nark::Configuration.plugins_path).to eql(value)
end
| baphled/nark | features/step_definitions/nark_steps.rb | Ruby | mit | 1,647 |
package com.baldy.commons.models.ref;
/**
* @author mbmartinez
*/
public enum RentalStatus {
AVAILABLE,
LEASED
}
| lordmarkm/baldy-commons | baldy-commons-models/src/main/java/com/baldy/commons/models/ref/RentalStatus.java | Java | mit | 126 |
package fasthttp
import (
"net"
"runtime"
"runtime/debug"
"strings"
"sync"
"time"
)
// workerPool serves incoming connections via a pool of workers
// in FILO order, i.e. the most recently stopped worker will serve the next
// incoming connection.
//
// Such a scheme keeps CPU caches hot (in theory).
type workerPool struct {
// Function for serving server connections.
// It must leave c unclosed.
WorkerFunc func(c net.Conn) error
MaxWorkersCount int
LogAllErrors bool
Logger Logger
lock sync.Mutex
workersCount int
mustStop bool
ready []*workerChan
stopCh chan struct{}
}
type workerChan struct {
t time.Time
ch chan net.Conn
}
func (wp *workerPool) Start() {
if wp.stopCh != nil {
panic("BUG: workerPool already started")
}
wp.stopCh = make(chan struct{})
stopCh := wp.stopCh
go func() {
for {
select {
case <-stopCh:
return
default:
time.Sleep(10 * time.Second)
}
wp.clean()
}
}()
}
func (wp *workerPool) Stop() {
if wp.stopCh == nil {
panic("BUG: workerPool wasn't started")
}
close(wp.stopCh)
wp.stopCh = nil
// Stop all the workers waiting for incoming connections.
// Do not wait for busy workers - they will stop after
// serving the connection and noticing wp.mustStop = true.
wp.lock.Lock()
for _, ch := range wp.ready {
ch.ch <- nil
}
wp.ready = nil
wp.mustStop = true
wp.lock.Unlock()
}
const maxIdleWorkerDuration = 10 * time.Second
func (wp *workerPool) clean() {
// Clean least recently used workers if they didn't serve connections
// for more than maxIdleWorkerDuration.
wp.lock.Lock()
ready := wp.ready
for len(ready) > 1 && time.Since(ready[0].t) > maxIdleWorkerDuration {
// notify the worker to stop.
ready[0].ch <- nil
ready = ready[1:]
wp.workersCount--
}
if len(ready) < len(wp.ready) {
copy(wp.ready, ready)
for i := len(ready); i < len(wp.ready); i++ {
wp.ready[i] = nil
}
wp.ready = wp.ready[:len(ready)]
}
wp.lock.Unlock()
}
func (wp *workerPool) Serve(c net.Conn) bool {
ch := wp.getCh()
if ch == nil {
return false
}
ch.ch <- c
return true
}
var workerChanCap = func() int {
// Use blocking workerChan if GOMAXPROCS=1.
// This immediately switches Serve to WorkerFunc, which results
// in higher performance (under go1.5 at least).
if runtime.GOMAXPROCS(0) == 1 {
return 0
}
// Use non-blocking workerChan if GOMAXPROCS>1,
// since otherwise the Serve caller (Acceptor) may lag accepting
// new connections if WorkerFunc is CPU-bound.
return 1
}()
func (wp *workerPool) getCh() *workerChan {
var ch *workerChan
createWorker := false
wp.lock.Lock()
ready := wp.ready
n := len(ready) - 1
if n < 0 {
if wp.workersCount < wp.MaxWorkersCount {
createWorker = true
wp.workersCount++
}
} else {
ch = ready[n]
wp.ready = ready[:n]
}
wp.lock.Unlock()
if ch == nil {
if !createWorker {
return nil
}
vch := workerChanPool.Get()
if vch == nil {
vch = &workerChan{
ch: make(chan net.Conn, workerChanCap),
}
}
ch = vch.(*workerChan)
go func() {
wp.workerFunc(ch)
workerChanPool.Put(vch)
}()
}
return ch
}
func (wp *workerPool) release(ch *workerChan) bool {
ch.t = time.Now()
wp.lock.Lock()
if wp.mustStop {
wp.lock.Unlock()
return false
}
wp.ready = append(wp.ready, ch)
wp.lock.Unlock()
return true
}
var workerChanPool sync.Pool
func (wp *workerPool) workerFunc(ch *workerChan) {
var c net.Conn
var err error
defer func() {
if r := recover(); r != nil {
wp.Logger.Printf("panic: %s\nStack trace:\n%s", r, debug.Stack())
}
if c != nil {
c.Close()
wp.release(ch)
}
}()
for c = range ch.ch {
if c == nil {
break
}
if err = wp.WorkerFunc(c); err != nil && err != errHijacked {
errStr := err.Error()
if wp.LogAllErrors || !(strings.Contains(errStr, "broken pipe") ||
strings.Contains(errStr, "reset by peer") ||
strings.Contains(errStr, "i/o timeout")) {
wp.Logger.Printf("error when serving connection %q<->%q: %s", c.LocalAddr(), c.RemoteAddr(), err)
}
}
if err != errHijacked {
c.Close()
}
c = nil
if !wp.release(ch) {
break
}
}
}
| j-musca/mutservice | vendor/github.com/valyala/fasthttp/workerpool.go | GO | mit | 4,152 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Class Index
*/
class Pemasukan extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('model_kelas');
$this->load->model('model_siswa');
$this->load->model('model_pemasukan');
$this->load->model('model_pengaturan');
}
public function index()
{
# code...
$data['kelas'] = $this->model_kelas->namaKelas();
$data['tambahkelas'] = $this->model_kelas->namaKelas();
$data['siswa'] = $this->model_siswa->listSiswa();
$data['pembayaran'] = $this->model_pemasukan->listPemasukan();
$data['pengaturan'] = $this->model_pengaturan->listPengaturan();
$data['biayapendidikan'] = $this->model_pengaturan->biayaPendidikan();
$this->load->view('head', $data);
$this->load->view('nav', $data);
$this->load->view('pemasukan', $data);
$this->load->view('foot');
}
public function siswa($by, $id) {
$data['pengaturan'] = $this->model_pengaturan->listPengaturan();
$data['pembayaran'] = $this->model_pemasukan->perSiswa($by, $id);
$data['biayapendidikan'] = $this->model_pengaturan->biayaPendidikan();
$this->load->view('head', $data);
$this->load->view('nav', $data);
$this->load->view('pemasukansiswa', $data);
$this->load->view('foot');
}
public function kelas($by, $id) {
$data['pengaturan'] = $this->model_pengaturan->listPengaturan();
$data['pembayaran'] = $this->model_pemasukan->perKelas($by, $id);
$data['kelas'] = $this->model_kelas->namaKelas();
$this->load->view('head', $data);
$this->load->view('nav', $data);
$this->load->view('pemasukankelas', $data);
$this->load->view('foot');
}
public function tambah() {
$this->model_pemasukan->addPemasukan();
}
}
| sendz/aplikasi-keuangan | application/controllers/Pemasukan.php | PHP | mit | 1,823 |
/**
*
*/
package org.necros.settings;
/**
* @author weiht
*
*/
public class CascadingServiceInjector<T> {
private Integer zIndex = 0;
private T service;
private CascadingService<T> cascadingService;
public void doInject() {
if (cascadingService != null && service != null) {
cascadingService.injectImplementer(zIndex, service);
}
}
public void setzIndex(Integer zIndex) {
this.zIndex = zIndex;
}
public void setService(T service) {
this.service = service;
}
public void setCascadingService(CascadingService<T> cascadingService) {
this.cascadingService = cascadingService;
}
}
| weiht/nrt.core | nrt-core-config/src/main/java/org/necros/settings/CascadingServiceInjector.java | Java | mit | 644 |
class IpnMessage < ActiveRecord::Base
alias_method :success?, :success
def self.create_from_message(hash)
ipn_message = IpnMessage.new
ipn_message.body = hash.to_yaml
ipn_message.success = hash["ACK"] == "Success"
ipn_message.correlation_id = hash["correlation_id"]
ipn_message.transaction_id = hash["transaction_id"]
ipn_message.save
return ipn_message
end
# returns hash of unique_id:string => status:bool
def unique_ids
hash = YAML.load(self.body)
return hash.inject({}){|acc, (k,v)|
k.to_s =~ /unique_id_(\d+)/
acc[v] = hash["status_#{$1}"] == "Completed" if $1
acc
}
end
end | matthandlersux/paypal_api | lib/generators/templates/ipn_message.rb | Ruby | mit | 621 |
<?php
namespace Oro\Bundle\MeasureBundle\Family;
/**
* Temperature measures constants
*
*
*/
interface TemperatureFamilyInterface
{
/**
* Family measure name
* @staticvar string
*/
const FAMILY = 'Temperature';
/**
* @staticvar string
*/
const CELCIUS = 'CELCIUS';
/**
* @staticvar string
*/
const FAHRENHEIT = 'FAHRENHEIT';
/**
* @staticvar string
*/
const KELVIN = 'KELVIN';
/**
* @staticvar string
*/
const RANKINE = 'RANKINE';
/**
* @staticvar string
*/
const REAUMUR = 'REAUMUR';
}
| umpirsky/platform | src/Oro/Bundle/MeasureBundle/Family/TemperatureFamilyInterface.php | PHP | mit | 624 |