repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
safan-lab/safan | Safan/Handler/ConsoleHandler.php | 1129 | <?php
/**
* This file is part of the Safan package.
*
* (c) Harut Grigoryan <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Safan\Handler;
use Safan\CliManager\CliManager;
class ConsoleHandler extends HttpHandler
{
/**
* Run Http applications
*/
public function runApplication()
{
parent::runApplication();
}
/**
* @return CliManager|void
*/
public function handlingProcess()
{
// Set Environments
$env = $_SERVER['argv'];
if(sizeof($env) != 2 || !strpos($env[1], ":"))
return CliManager::getErrorMessage("Unknown Command \nview help:commands");
$this->getObjectManager()->get('eventListener')->runEvent('preCliCheckRoute');
$this->getObjectManager()->get('router')->checkCliRoutes();
$this->getObjectManager()->get('eventListener')->runEvent('postCliCheckRoute');
// initialize libraries from config
$this->initLibraries();
return new CliManager($env[1]);
}
} | mit |
jshimko/react-time-ago | src/language-strings/gl.js | 475 | /* @flow */
import type {L10nsStrings} from '../formatters/buildFormatter'
// Galician
const strings: L10nsStrings = {
prefixAgo: 'hai',
prefixFromNow: 'dentro de',
suffixAgo: '',
suffixFromNow: '',
seconds: 'menos dun minuto',
minute: 'un minuto',
minutes: 'uns %d minutos',
hour: 'unha hora',
hours: '%d horas',
day: 'un día',
days: '%d días',
month: 'un mes',
months: '%d meses',
year: 'un ano',
years: '%d anos'
}
export default strings
| mit |
shoerob/BumbleTales | Tools/CRCompiler/OutputPathHandler.cpp | 448 | #include "OutputPathHandler.h"
#include "CompilerImpl.h"
#include "boost/algorithm/string.hpp"
using namespace CR;
using namespace CR::Compiler;
using namespace boost;
OutputPathHandler::OutputPathHandler(void)
{
}
OutputPathHandler::~OutputPathHandler(void)
{
}
void OutputPathHandler::HandleAttribute(const std::wstring &name,const std::wstring& value)
{
if(to_lower_copy(name) == L"path")
CompilerImpl::Instance().AddOutputPath(value);
}
| mit |
facebook/watchman | watchman/test/RingBufferTest.cpp | 939 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/portability/GTest.h>
#include "watchman/RingBuffer.h"
using namespace watchman;
TEST(RingBufferTest, writes_can_be_read) {
RingBuffer<int> rb{2};
rb.write(10);
rb.write(11);
auto result = rb.readAll();
EXPECT_EQ(2, result.size());
EXPECT_EQ(10, result[0]);
EXPECT_EQ(11, result[1]);
rb.write(12);
result = rb.readAll();
EXPECT_EQ(11, result[0]);
EXPECT_EQ(12, result[1]);
}
TEST(RingBufferTest, writes_can_be_cleared) {
RingBuffer<int> rb{10};
rb.write(3);
rb.write(4);
auto result = rb.readAll();
EXPECT_EQ(2, result.size());
EXPECT_EQ(3, result[0]);
EXPECT_EQ(4, result[1]);
rb.clear();
rb.write(5);
result = rb.readAll();
EXPECT_EQ(1, result.size());
EXPECT_EQ(5, result[0]);
}
| mit |
nass59/SiteAir | app/cache/dev/annotations/b87055e8ac5549b34041b908d34f5ca5cd63d695.cache.php | 382 | <?php return unserialize('a:3:{i:0;O:26:"Doctrine\\ORM\\Mapping\\Table":5:{s:4:"name";s:9:"air_image";s:6:"schema";N;s:7:"indexes";N;s:17:"uniqueConstraints";N;s:7:"options";a:0:{}}i:1;O:27:"Doctrine\\ORM\\Mapping\\Entity":2:{s:15:"repositoryClass";s:37:"Air\\BlogBundle\\Entity\\ImageRepository";s:8:"readOnly";b:0;}i:2;O:42:"Doctrine\\ORM\\Mapping\\HasLifecycleCallbacks":0:{}}'); | mit |
robdennis/ng-depthchart | tests/directiveSpec.js | 13499 | 'use strict';
describe('ng-depthchart', function() {
beforeEach(function() {
module('ng-depthchart');
});
var globalMatchers = {
matchesExpectedContent: function(expectedValuesByRowThenCell, table) {
table = table || this.actual;
var rows = table.find('tr');
// for-loops so we can return early
// don't collect header rows, so start at 1
if (rows.length - 1 !== expectedValuesByRowThenCell.length) {
return false;
}
for (var i=1; i<rows.length; i++) {
var cells = angular.element(rows[i]).find('td');
for (var j=0; j<cells.length; j++) {
var actual = angular.element(cells[j]).html();
var expected = expectedValuesByRowThenCell[i-1][j];
if (actual !== expected) {
this.message = function() {
return ("mismatched values at row "+(i-1)+" and column "+j+". '" +
angular.mock.dump(actual) + "' != '" +
angular.mock.dump(expected) + "'.");
};
return false;
}
}
}
return true;
}
};
beforeEach(function() {
this.addMatchers(globalMatchers);
});
describe('depth-chart dimensions and templates', function() {
var element, compile, scope;
var sameRows, sameRowsObjects, differentRows, differentRowsObjects;
beforeEach(function() {
this.addMatchers({
toMatchDimension: function(length, height) {
var notText; // used for crafting the right failure text later
scope.providedData = this.actual;
var table = angular.element('<div><depth-chart data="providedData"></depth-chart></div>');
compile(table)(scope);
// our table element has now been rendered
scope.$apply();
var rows = table.find('tr');
var actualHeight = rows.length;
var actualWidths = [];
angular.forEach(rows, function(row) {
// don't differentiate header rows from normal rows
var elementRow = angular.element(row);
actualWidths.push(elementRow.find('th').length +
elementRow.find('td').length);
});
notText = this.isNot ? '': 'not ';
this.message = function() {
return notText + 'all row-widths are equal: ' + angular.mock.dump(actualWidths);
};
for (var i=0; i<actualWidths.length; i++) {
// for-loop allows us to return from here if we need to short-circuit
if (actualWidths[i] !== actualWidths[0]) {
return false;
}
}
notText = 'to not have ';
this.message = function() {
return 'expected ' + notText + 'a ' + height+' row and ' + length + ' column table; ' +
"got " + actualHeight + " and " + actualWidths[0];
};
return actualHeight === height && actualWidths[0] === length;
},
toMatchContent: function(expectedValuesByRowThenCell, template) {
// this is going to assume that the dimensions match up with expectations
var templateParam = template ? ' display-template="template"' : '';
scope.providedData = this.actual;
scope.template = template;
var table = angular.element(
// only include the template param if it's defined
'<div><depth-chart data="providedData"'+ templateParam + '></depth-chart></div>'
);
compile(table)(scope);
scope.$apply();
return globalMatchers.matchesExpectedContent.apply(this, [expectedValuesByRowThenCell, table]);
}
});
});
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope;
compile = $compile;
sameRows = [
{header: 'stuff', data: ['foo', 'bar', 'baz']},
{header: 'stuff2', data: ['foo', 'bar', 'baz']}
];
sameRowsObjects = [
{header: 'stuff', data: [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}]},
{header: 'stuff2', data: [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}]}
];
differentRows = [
{header: 'stuff', data: ['foo', 'bar', 'baz', 'bax']},
{header: 'stuff2', data: ['foo', 'bar', 'baz']}
];
differentRowsObjects = [
{header: 'stuff', data: [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}, {name: 'bax'}]},
{header: 'stuff2', data: [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}]}
];
}));
it('can make a 1-column table', function() {
expect([sameRows[0]]).toMatchDimension(1, 4); // 3 rows plus a header row
});
it('can make a 2-column table with same lengths', function() {
expect(sameRows).toMatchDimension(2, 4);
});
it('can make a 2-column table with different lengths', function() {
expect(differentRows).toMatchDimension(2, 5);
});
it('defaults to showing the original value', function() {
expect(sameRows).toMatchContent([
['foo', 'foo'],
['bar', 'bar'],
['baz', 'baz']
]);
expect(differentRows).toMatchContent([
['foo', 'foo'],
['bar', 'bar'],
['baz', 'baz'],
['bax', ' ']
]);
});
it('can accept an arbitrary html string, with scope variables', function() {
expect(differentRowsObjects).toMatchContent([
['<b class="ng-binding">foo</b>', '<b class="ng-binding">foo</b>'],
['<b class="ng-binding">bar</b>', '<b class="ng-binding">bar</b>'],
['<b class="ng-binding">baz</b>', '<b class="ng-binding">baz</b>'],
['<b class="ng-binding">bax</b>', '<b class="ng-binding"></b>']
], '<b>{{item.name}}</b>');
});
it('can accept a template "unknown" scope variable', function() {
expect(sameRows).toMatchContent([
[' ', ' '],
[' ', ' '],
[' ', ' ']
], '{{ unknown || " " }}');
});
it("can accept a template that's just a the value", function() {
expect(sameRows).toMatchContent([
['foo', 'foo'],
['bar', 'bar'],
['baz', 'baz']
], '{{ item || " " }}');
});
it("can accept a template that's an attribute access", function() {
expect(sameRowsObjects).toMatchContent([
['foo', 'foo'],
['bar', 'bar'],
['baz', 'baz']
], '{{ item.name || " " }}');
expect(differentRowsObjects).toMatchContent([
['foo', 'foo'],
['bar', 'bar'],
['baz', 'baz'],
['bax', ' ']
], '{{ item.name || " " }}');
});
it("can accept a template that's an unknown attribute access", function() {
expect(sameRowsObjects).toMatchContent([
[' ', ' '],
[' ', ' '],
[' ', ' ']
], '{{ item.unknown || " " }}');
expect(differentRowsObjects).toMatchContent([
[' ', ' '],
[' ', ' '],
[' ', ' '],
[' ', ' ']
], '{{ item.unknown || " " }}');
});
});
describe('depth-chart custom classes', function() {
var element, compile, scope;
beforeEach(function() {
this.addMatchers({
toHaveClass: function(cls) {
this.message = function() {
return "Expected '" + angular.mock.dump(this.actual) + "' to have class '" + cls + "'.";
};
return angular.element(this.actual).hasClass(cls)
}
});
});
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope;
compile = $compile;
}));
it('can set custom classes', function() {
scope.providedData = [{header: 'stuff', data: [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}]}];
scope.classes = ['{{ item.name }}'];
var table = angular.element(
'<div><depth-chart data="providedData" additional-classes="classes"></depth-chart></div>'
);
compile(table)(scope);
scope.$apply();
var cells = table.find('td');
expect(cells[0]).toHaveClass('depth-chart-cell');
expect(cells[0]).not.toHaveClass('unknown');
expect(cells[0]).toHaveClass('foo');
expect(cells[0]).not.toHaveClass('bar');
expect(cells[0]).not.toHaveClass('baz');
expect(cells[1]).toHaveClass('depth-chart-cell');
expect(cells[1]).toHaveClass('bar');
expect(cells[1]).not.toHaveClass('foo');
expect(cells[1]).not.toHaveClass('baz');
expect(cells[2]).toHaveClass('depth-chart-cell');
expect(cells[2]).toHaveClass('baz');
expect(cells[2]).not.toHaveClass('foo');
expect(cells[2]).not.toHaveClass('bar');
});
});
describe('depth-chart scope updating', function() {
var compile, scope;
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope;
compile = $compile;
}));
it('can update with new information', function() {
var table = angular.element('<div><depth-chart data="providedData"></depth-chart></div>');
compile(table)(scope);
scope.providedData = [
{header: 'stuff', data: ['foo', 'bar', 'baz']},
{header: 'stuff2', data: ['foo', 'bar', 'baz']}
];
scope.$apply();
expect(table).matchesExpectedContent([
['foo', 'foo'],
['bar', 'bar'],
['baz', 'baz']
]);
scope.providedData = [
{header: 'stuff', data: ['foo', 'bar', 'baz', 'bax']},
{header: 'stuff2', data: ['foo', 'bar', 'baz']}
];
// there's new data now
scope.$apply();
expect(table).matchesExpectedContent([
['foo', 'foo'],
['bar', 'bar'],
['baz', 'baz'],
['bax', ' ']
])
})
});
describe('template functions', function() {
var compile, scope;
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope;
compile = $compile;
}));
it('can set a callback function that is used to render content', function() {
scope.providedData = [
{header: 'stuff', data: ['foo']}
];
scope.function = function(item) {
return 'mocked ' + item;
};
scope.template = '' +
'<div>' +
'<span id="toTest">{{templateFunction({item: item})}}</span>' +
'</div>';
var table = angular.element('' +
'<div><depth-chart data="providedData" template-function="function(item)" display-template="template"></depth-chart></div>'
);
compile(table)(scope);
scope.$apply();
expect(table.find('#toTest').text()).toBe('mocked foo');
});
it('can set a callback function that is used as a click handler', function() {
scope.providedData = [
{header: 'stuff', data: ['foo']}
];
scope.function = jasmine.createSpy('mockedClickHandler');
scope.template = '' +
'<div>' +
'<span>{{item}}</span>' +
'<button id="toTest" ng-click="templateFunction({test: item})">test</span>' +
'</div>';
var table = angular.element('' +
'<div><depth-chart data="providedData" template-function="function(test)" display-template="template"></depth-chart></div>'
);
compile(table)(scope);
scope.$apply();
expect(scope.function).not.toHaveBeenCalled();
table.find('#toTest').click();
expect(scope.function).toHaveBeenCalledWith('foo');
});
})
});
| mit |
mostofreddy/owncaptcha | examples/big.php | 859 | <?php
/**
* Big
*
* PHP version 5.4
*
* Copyright (c) 2014 Federico Lozada Mosto <[email protected]>
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*
* @category OwnCaptcha
* @package OwnCaptcha\Examples
* @author Federico Lozada Mosto <[email protected]>
* @copyright 2014 Federico Lozada Mosto <[email protected]>
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @link http://www.mostofreddy.com.ar
*/
require_once realpath(__DIR__."/../vendor")."/autoload.php";
session_start();
$adapter = new \owncaptcha\adapters\TextImage();
$adapter->config(
array(
'fontsize' => '40',
'lineweight' => 2
)
);
$captcha = new \owncaptcha\Captcha();
$captcha->adapter($adapter)
->build();
| mit |
slkasun/symfony2demo | src/Blog/ModelBundle/Entity/Comment.php | 2128 | <?php
namespace Blog\ModelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Comment
*
* @ORM\Table()
* @ORM\Entity
*/
class Comment extends Timestampable
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="author_name", type="string", length=100)
* @Assert\NotBlank
*/
private $authorName;
/**
* @var string
*
* @ORM\Column(name="body", type="text")
* @Assert\NotBlank
*/
private $body;
/**
* @var Post
*
* @ORM\ManyToOne(targetEntity="Post", inversedBy="comments")
* @ORM\JoinColumn(name="post_id", referencedColumnName="id", nullable=false)
* @Assert\NotBlank
*/
private $post;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get authorName
*
* @return string
*/
public function getAuthorName()
{
return $this->authorName;
}
/**
* Set authorName
*
* @param string $authorName
*
* @return Comment
*/
public function setAuthorName($authorName)
{
$this->authorName = $authorName;
return $this;
}
/**
* Get body
*
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* Set body
*
* @param string $body
*
* @return Comment
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Get post
*
* @return \Blog\ModelBundle\Entity\Post
*/
public function getPost()
{
return $this->post;
}
/**
* Set post
*
* @param \Blog\ModelBundle\Entity\Post $post
*
* @return Comment
*/
public function setPost(Post $post)
{
$this->post = $post;
return $this;
}
}
| mit |
uar-dejan-susic/movie_star_km | spec/views/movies/edit.html.slim_spec.rb | 140 | require 'rails_helper'
RSpec.describe "movies/edit.html.slim", type: :view do
pending "add some examples to (or delete) #{__FILE__}"
end
| mit |
VeloCloud/website-ui | app/containers/ProjectDashboardPage/dynamicContainers/TestContainerA/index.js | 1301 | /*
*
* TestContainerA
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { Button } from 'react-bootstrap';
import { createStructuredSelector } from 'reselect';
import makeSelectTestContainerA from './selectors';
import messages from './messages';
import { defaultAction } from './actions';
export class TestContainerA extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
// componentDidMount() {
// if (!this.props.init) {
// this.props.doInit();
// }
// }
render() {
return (
<div>
<FormattedMessage {...messages.header} />
<Button onClick={this.props.testSaga}> testSaga </Button>
</div>
);
}
}
TestContainerA.propTypes = {
// dispatch: PropTypes.func.isRequired,
testSaga: PropTypes.func.isRequired,
};
export default () => {
const mapStateToProps = createStructuredSelector({
TestContainerA: makeSelectTestContainerA(),
});
function mapDispatchToProps(dispatch) {
return {
// dispatch,
testSaga: () => dispatch(defaultAction()),
};
}
const DynamicTestContainerA = connect(mapStateToProps, mapDispatchToProps)(TestContainerA);
return (<DynamicTestContainerA />);
};
| mit |
drdaemos/department | MVCDepartment/App_Start/RouteConfig.cs | 582 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCDepartment
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} | mit |
rit-sse/node-api | models/membership.js | 2117 | import { DataTypes, Op } from 'sequelize';
import Moment from 'moment';
import { extendMoment } from 'moment-range';
import sequelize from '../config/sequelize';
import paginate from '../helpers/paginate';
import sorting from '../helpers/sorting';
const moment = extendMoment(Moment);
export default sequelize.define('memberships', {
reason: {
type: DataTypes.STRING,
allowNull: false,
},
committeeName: {
type: DataTypes.STRING,
},
// true = approved
// null = pending
// false = denied
approved: {
type: DataTypes.BOOLEAN,
},
startDate: {
type: DataTypes.DATE,
// TODO: A DATE field having 'false' as a defaultValue doesn't make sense.
// This should probably be "allowNull: 'false'"
defaultValue: false,
},
endDate: {
type: DataTypes.DATE,
// TODO: A DATE field having 'false' as a defaultValue doesn't make sense.
// This should probably be "allowNull: 'false'"
defaultValue: false,
},
}, {
defaultScopes: {
where: {
approved: true,
},
},
scopes: {
reason(reason) {
return { where: { reason } };
},
committee(committeeName) {
return { where: { committeeName } };
},
user(userDce) {
return { where: { userDce } };
},
approved(approved) {
return { where: { approved } };
},
between(range) {
const dates = moment.range(range);
return {
where: {
startDate: {
[Op.between]: [dates.start.toDate(), dates.end.toDate()],
},
},
};
},
active(date) {
return {
where: {
startDate: {
[Op.lte]: date,
},
endDate: {
[Op.gte]: date,
},
},
};
},
paginate,
orderBy(field, direction) {
return sorting(field, direction, [
'id',
'userDce',
'committeeName',
'startDate',
'endDate',
'reason',
'approved',
'createdAt',
'updatedAt',
]);
},
}, // TODO: Validate startDateBeforeEndDate like in 'models/event.js'
});
| mit |
scampersand/sonos-front | app/react-icons/fa/play.js | 399 | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaPlay extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m35.4 20.7l-29.6 16.5q-0.6 0.3-0.9 0t-0.4-0.8v-32.8q0-0.6 0.4-0.8t0.9 0l29.6 16.5q0.5 0.3 0.5 0.7t-0.5 0.7z"/></g>
</IconBase>
);
}
}
| mit |
AfricaChess/lichesshub | grandprix/migrations/0001_initial.py | 1791 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-28 04:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Player',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='PlayerScore',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rank', models.PositiveIntegerField()),
('points', models.PositiveIntegerField(default=0)),
('player', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='grandprix.Player')),
],
),
migrations.CreateModel(
name='Tournament',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('date', models.DateTimeField(default=django.utils.timezone.now)),
('synced', models.BooleanField(default=False)),
('error', models.BooleanField(default=False)),
],
),
migrations.AddField(
model_name='playerscore',
name='tournament',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='grandprix.Tournament'),
),
]
| mit |
lanceguyatt/fronter | gulpfile.babel.js/tasks/styles.js | 1153 | import gulp from 'gulp'
import { resolve } from 'path'
import browserSync from 'browser-sync'
import plumber from 'gulp-plumber'
import postcss from 'gulp-postcss'
import sourcemaps from 'gulp-sourcemaps'
// import gulpStylelint from 'gulp-stylelint';
import cleanCSS from 'gulp-clean-css'
import gutil from 'gulp-util'
import { isProduction, onError, paths } from '../../config'
const bs = browserSync.get('main')
const compile = done => {
gulp
.src(resolve(paths.styles.srcDir, '*.css'))
.pipe(sourcemaps.init())
.pipe(postcss())
.pipe(isProduction ? cleanCSS() : gutil.noop())
.pipe(plumber(onError))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.styles.buildDir))
.pipe(bs.stream())
done()
}
// gulp.task('styles:lint', () => {
// gulp.src(resolve(paths.styles.buildDir, '*.css')).pipe(
// gulpStylelint({
// reporters: [
// {
// formatter: 'string',
// console: true,
// },
// ],
// }),
// );
// });
const watch = done => {
gulp.watch(resolve(paths.styles.srcDir, '**', '*.css'), compile)
done()
}
export default {
compile,
watch,
}
| mit |
DreamHi/HiOneBrowser | src/modules/system/containers/RLogin.js | 393 | import { connect } from 'react-redux';
import { login } from '../actions/loginAction';
import Login from '../components/CLogin';
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {
onLogin: (name, pass) => {
dispatch(login({ name, pass }));
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Login);
| mit |
philipbrown/signature-php | tests/Guards/CheckTimestampTest.php | 1379 | <?php namespace PhilipBrown\Signature\Tests\Guards;
use PhilipBrown\Signature\Guards\CheckTimestamp;
class CheckTimestampTest extends \PHPUnit_Framework_TestCase
{
/** @var CheckTokenKey */
private $guard;
public function setUp()
{
$this->guard = new CheckTimestamp;
}
/** @test */
public function should_throw_exception_on_missing_timestamp()
{
$this->setExpectedException('PhilipBrown\Signature\Exceptions\SignatureTimestampException');
$this->guard->check([], [], 'auth_');
}
/** @test */
public function should_throw_exception_on_expired_timestamp()
{
$this->setExpectedException('PhilipBrown\Signature\Exceptions\SignatureTimestampException');
$timestamp = time() + 60 * 60;
$this->guard->check(['auth_timestamp' => $timestamp], [], 'auth_');
}
/** @test */
public function should_throw_exception_on_future_expired_timestamp()
{
$this->setExpectedException('PhilipBrown\Signature\Exceptions\SignatureTimestampException');
$timestamp = time() - 60 * 60;
$this->guard->check(['auth_timestamp' => $timestamp], [], 'auth_');
}
/** @test */
public function should_return_true_with_valid_timestamp()
{
$timestamp = time();
$this->guard->check(['auth_timestamp' => $timestamp], [], 'auth_');
}
}
| mit |
pzli/blog-demo | settings.js | 91 | module.exports = {
cookieSecret: 'myBlog',
db: 'blog',
host: 'localhost',
port: 27017
} | mit |
tgsstdio/GLSLSyntaxAST---Irony-based-GLSL-parser | ReferenceCompiler/ParseHelper.cpp | 227639 | //
//Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
//Copyright (C) 2012-2013 LunarG, Inc.
//
//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 3Dlabs Inc. Ltd. 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 THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS 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.
//
#include "ParseHelper.h"
#include "Scan.h"
#include "osinclude.h"
#include <stdarg.h>
#include <algorithm>
#include "preprocessor/PpContext.h"
extern int yyparse(glslang::TParseContext*);
namespace glslang {
TParseContext::TParseContext(TSymbolTable& symt, TIntermediate& interm, bool pb, int v, EProfile p, EShLanguage L, TInfoSink& is,
bool fc, EShMessages m) :
intermediate(interm), symbolTable(symt), infoSink(is), language(L),
version(v), profile(p), forwardCompatible(fc), messages(m),
contextPragma(true, false), loopNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0), statementNestingLevel(0),
postMainReturn(false),
tokensBeforeEOF(false), limits(resources.limits), currentScanner(0),
numErrors(0), parsingBuiltins(pb), afterEOF(false),
atomicUintOffsets(0), anyIndexLimits(false)
{
// ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
linkage = new TIntermAggregate;
// set all precision defaults to EpqNone, which is correct for all desktop types
// and for ES types that don't have defaults (thus getting an error on use)
for (int type = 0; type < EbtNumTypes; ++type)
defaultPrecision[type] = EpqNone;
for (int type = 0; type < maxSamplerIndex; ++type)
defaultSamplerPrecision[type] = EpqNone;
// replace with real defaults for those that have them
if (profile == EEsProfile) {
TSampler sampler;
sampler.set(EbtFloat, Esd2D);
defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
sampler.set(EbtFloat, EsdCube);
defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
sampler.set(EbtFloat, Esd2D);
sampler.external = true;
defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
switch (language) {
case EShLangFragment:
defaultPrecision[EbtInt] = EpqMedium;
defaultPrecision[EbtUint] = EpqMedium;
break;
default:
defaultPrecision[EbtInt] = EpqHigh;
defaultPrecision[EbtUint] = EpqHigh;
defaultPrecision[EbtFloat] = EpqHigh;
break;
}
defaultPrecision[EbtSampler] = EpqLow;
defaultPrecision[EbtAtomicUint] = EpqHigh;
}
globalUniformDefaults.clear();
globalUniformDefaults.layoutMatrix = ElmColumnMajor;
globalUniformDefaults.layoutPacking = ElpShared;
globalBufferDefaults.clear();
globalBufferDefaults.layoutMatrix = ElmColumnMajor;
globalBufferDefaults.layoutPacking = ElpShared;
globalInputDefaults.clear();
globalOutputDefaults.clear();
// "Shaders in the transform
// feedback capturing mode have an initial global default of
// layout(xfb_buffer = 0) out;"
if (language == EShLangVertex ||
language == EShLangTessControl ||
language == EShLangTessEvaluation ||
language == EShLangGeometry)
globalOutputDefaults.layoutXfbBuffer = 0;
if (language == EShLangGeometry)
globalOutputDefaults.layoutStream = 0;
}
TParseContext::~TParseContext()
{
delete [] atomicUintOffsets;
}
void TParseContext::setLimits(const TBuiltInResource& r)
{
resources = r;
anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
! limits.generalConstantMatrixVectorIndexing ||
! limits.generalSamplerIndexing ||
! limits.generalUniformIndexing ||
! limits.generalVariableIndexing ||
! limits.generalVaryingIndexing;
intermediate.setLimits(resources);
// "Each binding point tracks its own current default offset for
// inheritance of subsequent variables using the same binding. The initial state of compilation is that all
// binding points have an offset of 0."
atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
atomicUintOffsets[b] = 0;
}
//
// Parse an array of strings using yyparse, going through the
// preprocessor to tokenize the shader strings, then through
// the GLSL scanner.
//
// Returns true for successful acceptance of the shader, false if any errors.
//
bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
{
currentScanner = &input;
ppContext.setInput(input, versionWillBeError);
yyparse(this);
if (! parsingBuiltins)
finalErrorCheck();
return numErrors == 0;
}
// This is called from bison when it has a parse (syntax) error
void TParseContext::parserError(const char* s)
{
if (afterEOF) {
if (tokensBeforeEOF == 1)
error(getCurrentLoc(), "", "pre-mature EOF", s, "");
} else
error(getCurrentLoc(), "", "", s, "");
}
void TParseContext::handlePragma(TSourceLoc loc, const TVector<TString>& tokens)
{
if (pragmaCallback)
pragmaCallback(loc.line, tokens);
if (tokens.size() == 0)
return;
if (tokens[0].compare("optimize") == 0) {
if (tokens.size() != 4) {
error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
return;
}
if (tokens[1].compare("(") != 0) {
error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
return;
}
if (tokens[2].compare("on") == 0)
contextPragma.optimize = true;
else if (tokens[2].compare("off") == 0)
contextPragma.optimize = false;
else {
error(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
return;
}
if (tokens[3].compare(")") != 0) {
error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
return;
}
} else if (tokens[0].compare("debug") == 0) {
if (tokens.size() != 4) {
error(loc, "debug pragma syntax is incorrect", "#pragma", "");
return;
}
if (tokens[1].compare("(") != 0) {
error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
return;
}
if (tokens[2].compare("on") == 0)
contextPragma.debug = true;
else if (tokens[2].compare("off") == 0)
contextPragma.debug = false;
else {
error(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
return;
}
if (tokens[3].compare(")") != 0) {
error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
return;
}
}
}
///////////////////////////////////////////////////////////////////////
//
// Sub- vector and matrix fields
//
////////////////////////////////////////////////////////////////////////
//
// Look at a '.' field selector string and change it into offsets
// for a vector or scalar
//
// Returns true if there is no error.
//
bool TParseContext::parseVectorFields(TSourceLoc loc, const TString& compString, int vecSize, TVectorFields& fields)
{
fields.num = (int) compString.size();
if (fields.num > 4) {
error(loc, "illegal vector field selection", compString.c_str(), "");
return false;
}
enum {
exyzw,
ergba,
estpq,
} fieldSet[4];
for (int i = 0; i < fields.num; ++i) {
switch (compString[i]) {
case 'x':
fields.offsets[i] = 0;
fieldSet[i] = exyzw;
break;
case 'r':
fields.offsets[i] = 0;
fieldSet[i] = ergba;
break;
case 's':
fields.offsets[i] = 0;
fieldSet[i] = estpq;
break;
case 'y':
fields.offsets[i] = 1;
fieldSet[i] = exyzw;
break;
case 'g':
fields.offsets[i] = 1;
fieldSet[i] = ergba;
break;
case 't':
fields.offsets[i] = 1;
fieldSet[i] = estpq;
break;
case 'z':
fields.offsets[i] = 2;
fieldSet[i] = exyzw;
break;
case 'b':
fields.offsets[i] = 2;
fieldSet[i] = ergba;
break;
case 'p':
fields.offsets[i] = 2;
fieldSet[i] = estpq;
break;
case 'w':
fields.offsets[i] = 3;
fieldSet[i] = exyzw;
break;
case 'a':
fields.offsets[i] = 3;
fieldSet[i] = ergba;
break;
case 'q':
fields.offsets[i] = 3;
fieldSet[i] = estpq;
break;
default:
error(loc, "illegal vector field selection", compString.c_str(), "");
return false;
}
}
for (int i = 0; i < fields.num; ++i) {
if (fields.offsets[i] >= vecSize) {
error(loc, "vector field selection out of range", compString.c_str(), "");
return false;
}
if (i > 0) {
if (fieldSet[i] != fieldSet[i-1]) {
error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
return false;
}
}
}
return true;
}
///////////////////////////////////////////////////////////////////////
//
// Errors
//
////////////////////////////////////////////////////////////////////////
//
// Used to output syntax, parsing, and semantic errors.
//
void C_DECL TParseContext::error(TSourceLoc loc, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...)
{
const int maxSize = GlslangMaxTokenLength + 200;
char szExtraInfo[maxSize];
va_list marker;
va_start(marker, szExtraInfoFormat);
safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, marker);
infoSink.info.prefix(EPrefixError);
infoSink.info.location(loc);
infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
va_end(marker);
++numErrors;
}
void C_DECL TParseContext::warn(TSourceLoc loc, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...)
{
if (messages & EShMsgSuppressWarnings)
return;
const int maxSize = GlslangMaxTokenLength + 200;
char szExtraInfo[maxSize];
va_list marker;
va_start(marker, szExtraInfoFormat);
safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, marker);
infoSink.info.prefix(EPrefixWarning);
infoSink.info.location(loc);
infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
va_end(marker);
}
//
// Handle seeing a variable identifier in the grammar.
//
TIntermTyped* TParseContext::handleVariable(TSourceLoc loc, TSymbol* symbol, const TString* string)
{
TIntermTyped* node = 0;
// Error check for requiring specific extensions present.
if (symbol && symbol->getNumExtensions())
requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
if (symbol && symbol->isReadOnly()) {
// All shared things containing an implicitly sized array must be copied up
// on first use, so that all future references will share its array structure,
// so that editing the implicit size will effect all nodes consuming it,
// and so that editing the implicit size won't change the shared one.
//
// If this is a variable or a block, check it and all it contains, but if this
// is a member of an anonymous block, check the whole block, as the whole block
// will need to be copied up if it contains an implicitly-sized array.
if (symbol->getType().containsImplicitlySizedArray() || (symbol->getAsAnonMember() && symbol->getAsAnonMember()->getAnonContainer().getType().containsImplicitlySizedArray()))
makeEditable(symbol);
}
const TVariable* variable;
const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : 0;
if (anon) {
// It was a member of an anonymous container.
// The "getNumExtensions()" mechanism above doesn't yet work for block members
blockMemberExtensionCheck(loc, 0, *string);
// Create a subtree for its dereference.
variable = anon->getAnonContainer().getAsVariable();
TIntermTyped* container = intermediate.addSymbol(*variable, loc);
TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
if (node->getType().hiddenMember())
error(loc, "member of nameless block was not redeclared", string->c_str(), "");
} else {
// Not a member of an anonymous container.
// The symbol table search was done in the lexical phase.
// See if it was a variable.
variable = symbol ? symbol->getAsVariable() : 0;
if (symbol && ! variable)
error(loc, "variable name expected", string->c_str(), "");
// Recovery, if it wasn't found or was not a variable.
if (! variable)
variable = new TVariable(string, TType(EbtVoid));
if (variable->getType().getQualifier().storage == EvqConst)
node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
else
node = intermediate.addSymbol(*variable, loc);
}
if (variable->getType().getQualifier().isIo())
intermediate.addIoAccessed(*string);
return node;
}
//
// Handle seeing a base[index] dereference in the grammar.
//
TIntermTyped* TParseContext::handleBracketDereference(TSourceLoc loc, TIntermTyped* base, TIntermTyped* index)
{
TIntermTyped* result = 0;
int indexValue = 0;
if (index->getQualifier().storage == EvqConst) {
indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
checkIndex(loc, base->getType(), indexValue);
}
variableCheck(base);
if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
if (base->getAsSymbolNode())
error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
else
error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
} else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
return intermediate.foldDereference(base, indexValue, loc);
else {
// at least one of base and index is variable...
if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
handleIoResizeArrayAccess(loc, base);
if (index->getQualifier().storage == EvqConst) {
if (base->getType().isImplicitlySizedArray())
updateImplicitArraySize(loc, base, indexValue);
result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
} else {
if (base->getType().isImplicitlySizedArray()) {
if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
else
error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
}
if (base->getBasicType() == EbtBlock)
requireProfile(base->getLoc(), ~EEsProfile, "variable indexing block array");
else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader ouput array");
else if (base->getBasicType() == EbtSampler && version >= 130) {
const char* explanation = "variable indexing sampler array";
requireProfile(base->getLoc(), ECoreProfile | ECompatibilityProfile, explanation);
profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation);
}
result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
}
}
if (result == 0) {
// Insert dummy error-recovery result
result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
} else {
// Insert valid dereferenced result
TType newType(base->getType(), 0); // dereferenced type
if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
newType.getQualifier().storage = EvqConst;
else
newType.getQualifier().storage = EvqTemporary;
result->setType(newType);
if (anyIndexLimits)
handleIndexLimits(loc, base, index);
}
return result;
}
void TParseContext::checkIndex(TSourceLoc loc, const TType& type, int& index)
{
if (index < 0) {
error(loc, "", "[", "index out of range '%d'", index);
index = 0;
} else if (type.isArray()) {
if (type.isExplicitlySizedArray() && index >= type.getArraySize()) {
error(loc, "", "[", "array index out of range '%d'", index);
index = type.getArraySize() - 1;
}
} else if (type.isVector()) {
if (index >= type.getVectorSize()) {
error(loc, "", "[", "vector index out of range '%d'", index);
index = type.getVectorSize() - 1;
}
} else if (type.isMatrix()) {
if (index >= type.getMatrixCols()) {
error(loc, "", "[", "matrix index out of range '%d'", index);
index = type.getMatrixCols() - 1;
}
}
}
// for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
void TParseContext::handleIndexLimits(TSourceLoc /*loc*/, TIntermTyped* base, TIntermTyped* index)
{
if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
(! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
(! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
(! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
(! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
! base->getType().getQualifier().isPipeInput() &&
! base->getType().getQualifier().isPipeOutput() &&
base->getType().getQualifier().storage != EvqConst) ||
(! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
base->getType().getQualifier().isPipeOutput()))) {
// it's too early to know what the inductive variables are, save it for post processing
needsIndexLimitationChecking.push_back(index);
}
}
// Make a shared symbol have a non-shared version that can be edited by the current
// compile, such that editing its type will not change the shared version and will
// effect all nodes sharing it.
void TParseContext::makeEditable(TSymbol*& symbol)
{
// copyUp() does a deep copy of the type.
symbol = symbolTable.copyUp(symbol);
// Also, see if it's tied to IO resizing
if (isIoResizeArray(symbol->getType()))
ioArraySymbolResizeList.push_back(symbol);
// Also, save it in the AST for linker use.
intermediate.addSymbolLinkageNode(linkage, *symbol);
}
// Return true if this is a geometry shader input array or tessellation control output array.
bool TParseContext::isIoResizeArray(const TType& type) const
{
return type.isArray() &&
((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) ||
(language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch));
}
// If an array is not isIoResizeArray() but is an io array, make sure it has the right size
void TParseContext::fixIoArraySize(TSourceLoc loc, TType& type)
{
if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
return;
assert(! isIoResizeArray(type));
if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
return;
if (language == EShLangTessControl || language == EShLangTessEvaluation) {
if (type.getArraySize() != resources.maxPatchVertices) {
if (type.isExplicitlySizedArray())
error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
type.changeArraySize(resources.maxPatchVertices);
}
}
}
// Issue any errors if the non-array object is missing arrayness WRT
// shader I/O that has array requirements.
// All arrayness checking is handled in array paths, this is for
void TParseContext::ioArrayCheck(TSourceLoc loc, const TType& type, const TString& identifier)
{
if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
if (type.getQualifier().isArrayedIo(language))
error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
}
}
// Handle a dereference of a geometry shader input array or tessellation control output array.
// See ioArraySymbolResizeList comment in ParseHelper.h.
//
void TParseContext::handleIoResizeArrayAccess(TSourceLoc /*loc*/, TIntermTyped* base)
{
TIntermSymbol* symbolNode = base->getAsSymbolNode();
assert(symbolNode);
if (! symbolNode)
return;
// fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
if (symbolNode->getType().isImplicitlySizedArray()) {
int newSize = getIoArrayImplicitSize();
if (newSize)
symbolNode->getWritableType().changeArraySize(newSize);
}
}
// If there has been an input primitive declaration (geometry shader) or an output
// number of vertices declaration(tessellation shader), make sure all input array types
// match it in size. Types come either from nodes in the AST or symbols in the
// symbol table.
//
// Types without an array size will be given one.
// Types already having a size that is wrong will get an error.
//
void TParseContext::checkIoArraysConsistency(TSourceLoc loc, bool tailOnly)
{
int requiredSize = getIoArrayImplicitSize();
if (requiredSize == 0)
return;
const char* feature;
if (language == EShLangGeometry)
feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
else if (language == EShLangTessControl)
feature = "vertices";
else
feature = "unknown";
if (tailOnly) {
checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
return;
}
for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
}
int TParseContext::getIoArrayImplicitSize() const
{
if (language == EShLangGeometry)
return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
else if (language == EShLangTessControl)
return intermediate.getVertices();
else
return 0;
}
void TParseContext::checkIoArrayConsistency(TSourceLoc loc, int requiredSize, const char* feature, TType& type, const TString& name)
{
if (type.isImplicitlySizedArray())
type.changeArraySize(requiredSize);
else if (type.getArraySize() != requiredSize) {
if (language == EShLangGeometry)
error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
else if (language == EShLangTessControl)
error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
else
assert(0);
}
}
// Handle seeing a binary node with a math operation.
TIntermTyped* TParseContext::handleBinaryMath(TSourceLoc loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
{
rValueErrorCheck(loc, str, left->getAsTyped());
rValueErrorCheck(loc, str, right->getAsTyped());
TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
if (! result)
binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
return result;
}
// Handle seeing a unary node with a math operation.
TIntermTyped* TParseContext::handleUnaryMath(TSourceLoc loc, const char* str, TOperator op, TIntermTyped* childNode)
{
rValueErrorCheck(loc, str, childNode);
TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
if (result)
return result;
else
unaryOpError(loc, str, childNode->getCompleteString());
return childNode;
}
//
// Handle seeing a base.field dereference in the grammar.
//
TIntermTyped* TParseContext::handleDotDereference(TSourceLoc loc, TIntermTyped* base, const TString& field)
{
variableCheck(base);
//
// .length() can't be resolved until we later see the function-calling syntax.
// Save away the name in the AST for now. Processing is compeleted in
// handleLengthMethod().
//
if (field == "length") {
if (base->isArray()) {
profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, ".length");
profileRequires(loc, EEsProfile, 300, nullptr, ".length");
} else if (base->isVector() || base->isMatrix()) {
const char* feature = ".length() on vectors and matrices";
requireProfile(loc, ~EEsProfile, feature);
profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, feature);
} else {
error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString().c_str());
return base;
}
return intermediate.addMethod(base, TType(EbtInt), &field, loc);
}
// It's not .length() if we get to here.
if (base->isArray()) {
error(loc, "cannot apply to an array:", ".", field.c_str());
return base;
}
// It's neither an array nor .length() if we get here,
// leaving swizzles and struct/block dereferences.
TIntermTyped* result = base;
if (base->isVector() || base->isScalar()) {
if (base->isScalar()) {
const char* dotFeature = "scalar swizzle";
requireProfile(loc, ~EEsProfile, dotFeature);
profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, dotFeature);
}
TVectorFields fields;
if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
fields.num = 1;
fields.offsets[0] = 0;
}
if (base->isScalar()) {
if (fields.num == 1)
return result;
else {
TType type(base->getBasicType(), EvqTemporary, fields.num);
return addConstructor(loc, base, type, mapTypeToConstructorOp(type));
}
}
if (base->getType().getQualifier().storage == EvqConst)
result = intermediate.foldSwizzle(base, fields, loc);
else {
if (fields.num == 1) {
TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc);
result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
} else {
TString vectorString = field;
TIntermTyped* index = intermediate.addSwizzle(fields, loc);
result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int) vectorString.size()));
}
}
} else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
const TTypeList* fields = base->getType().getStruct();
bool fieldFound = false;
int member;
for (member = 0; member < (int)fields->size(); ++member) {
if ((*fields)[member].type->getFieldName() == field) {
fieldFound = true;
break;
}
}
if (fieldFound) {
if (base->getType().getQualifier().storage == EvqConst)
result = intermediate.foldDereference(base, member, loc);
else {
blockMemberExtensionCheck(loc, base, field);
TIntermTyped* index = intermediate.addConstantUnion(member, loc);
result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
result->setType(*(*fields)[member].type);
}
} else
error(loc, "no such field in structure", field.c_str(), "");
} else
error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
return result;
}
void TParseContext::blockMemberExtensionCheck(TSourceLoc loc, const TIntermTyped* /*base*/, const TString& field)
{
if (profile == EEsProfile && field == "gl_PointSize") {
if (language == EShLangGeometry)
requireExtensions(loc, Num_AEP_geometry_point_size, AEP_geometry_point_size, "gl_PointSize");
else if (language == EShLangTessControl || language == EShLangTessEvaluation)
requireExtensions(loc, Num_AEP_tessellation_point_size, AEP_tessellation_point_size, "gl_PointSize");
}
}
//
// Handle seeing a function declarator in the grammar. This is the precursor
// to recognizing a function prototype or function definition.
//
TFunction* TParseContext::handleFunctionDeclarator(TSourceLoc loc, TFunction& function, bool prototype)
{
// ES can't declare prototypes inside functions
if (! symbolTable.atGlobalLevel())
requireProfile(loc, ~EEsProfile, "local function declaration");
//
// Multiple declarations of the same function name are allowed.
//
// If this is a definition, the definition production code will check for redefinitions
// (we don't know at this point if it's a definition or not).
//
// Redeclarations (full signature match) are allowed. But, return types and parameter qualifiers must also match.
// - except ES 100, which only allows a single prototype
//
// ES 100 does not allow redefining, but does allow overloading of built-in functions.
// ES 300 does not allow redefining or overloading of built-in functions.
//
bool builtIn;
TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
if (symbol && symbol->getAsFunction() && builtIn)
requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
if (prevDec) {
if (prevDec->isPrototyped() && prototype)
profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function");
if (prevDec->getType() != function.getType())
error(loc, "overloaded functions must have the same return type", function.getType().getBasicTypeString().c_str(), "");
for (int i = 0; i < prevDec->getParamCount(); ++i) {
if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
}
}
arrayObjectCheck(loc, function.getType(), "array in function return type");
if (prototype) {
// All built-in functions are defined, even though they don't have a body.
// Count their prototype as a definition instead.
if (symbolTable.atBuiltInLevel())
function.setDefined();
else {
if (prevDec && ! builtIn)
symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
function.setPrototyped();
}
}
// This insert won't actually insert it if it's a duplicate signature, but it will still check for
// other forms of name collisions.
if (! symbolTable.insert(function))
error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
//
// If this is a redeclaration, it could also be a definition,
// in which case, we need to use the parameter names from this one, and not the one that's
// being redeclared. So, pass back this declaration, not the one in the symbol table.
//
return &function;
}
//
// Handle seeing the function prototype in front of a function definition in the grammar.
// The body is handled after this function returns.
//
TIntermAggregate* TParseContext::handleFunctionDefinition(TSourceLoc loc, TFunction& function)
{
currentCaller = function.getMangledName();
TSymbol* symbol = symbolTable.find(function.getMangledName());
TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
if (! prevDec)
error(loc, "can't find function", function.getName().c_str(), "");
// Note: 'prevDec' could be 'function' if this is the first time we've seen function
// as it would have just been put in the symbol table. Otherwise, we're looking up
// an earlier occurance.
if (prevDec && prevDec->isDefined()) {
// Then this function already has a body.
error(loc, "function already has a body", function.getName().c_str(), "");
}
if (prevDec && ! prevDec->isDefined()) {
prevDec->setDefined();
// Remember the return type for later checking for RETURN statements.
currentFunctionType = &(prevDec->getType());
} else
currentFunctionType = new TType(EbtVoid);
functionReturnsValue = false;
//
// Raise error message if main function takes any parameters or returns anything other than void
//
if (function.getName() == "main") {
if (function.getParamCount() > 0)
error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
if (function.getType().getBasicType() != EbtVoid)
error(loc, "", function.getType().getBasicTypeString().c_str(), "main function cannot return a value");
intermediate.addMainCount();
inMain = true;
} else
inMain = false;
//
// New symbol table scope for body of function plus its arguments
//
symbolTable.push();
//
// Insert parameters into the symbol table.
// If the parameter has no name, it's not an error, just don't insert it
// (could be used for unused args).
//
// Also, accumulate the list of parameters into the HIL, so lower level code
// knows where to find parameters.
//
TIntermAggregate* paramNodes = new TIntermAggregate;
for (int i = 0; i < function.getParamCount(); i++) {
TParameter& param = function[i];
if (param.name != 0) {
TVariable *variable = new TVariable(param.name, *param.type);
// Insert the parameters with name in the symbol table.
if (! symbolTable.insert(*variable))
error(loc, "redefinition", variable->getName().c_str(), "");
else {
// Transfer ownership of name pointer to symbol table.
param.name = 0;
// Add the parameter to the HIL
paramNodes = intermediate.growAggregate(paramNodes,
intermediate.addSymbol(*variable, loc),
loc);
}
} else
paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(0, "", *param.type, loc), loc);
}
intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
loopNestingLevel = 0;
statementNestingLevel = 0;
controlFlowNestingLevel = 0;
postMainReturn = false;
return paramNodes;
}
//
// Handle seeing function call syntax in the grammar, which could be any of
// - .length() method
// - constructor
// - a call to a built-in function mapped to an operator
// - a call to a built-in function that will remain a function call (e.g., texturing)
// - user function
// - subroutine call (not implemented yet)
//
TIntermTyped* TParseContext::handleFunctionCall(TSourceLoc loc, TFunction* function, TIntermNode* arguments)
{
TIntermTyped* result = 0;
TOperator op = function->getBuiltInOp();
if (op == EOpArrayLength)
result = handleLengthMethod(loc, function, arguments);
else if (op != EOpNull) {
//
// Then this should be a constructor.
// Don't go through the symbol table for constructors.
// Their parameters will be verified algorithmically.
//
TType type(EbtVoid); // use this to get the type back
if (! constructorError(loc, arguments, *function, op, type)) {
//
// It's a constructor, of type 'type'.
//
result = addConstructor(loc, arguments, type, op);
if (result == 0)
error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
}
} else {
//
// Find it in the symbol table.
//
const TFunction* fnCandidate;
bool builtIn;
fnCandidate = findFunction(loc, *function, builtIn);
if (fnCandidate) {
// This is a declared function that might map to
// - a built-in operator,
// - a built-in function not mapped to an operator, or
// - a user function.
// Error check for a function requiring specific extensions present.
if (builtIn && fnCandidate->getNumExtensions())
requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
if (arguments) {
// Make sure qualifications work for these arguments.
TIntermAggregate* aggregate = arguments->getAsAggregate();
for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
// At this early point there is a slight ambiguity between whether an aggregate 'arguments'
// is the single argument itself or its children are the arguments. Only one argument
// means take 'arguments' itself as the one argument.
TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
if (formalQualifier.storage == EvqOut || formalQualifier.storage == EvqInOut) {
if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped()))
error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", "");
}
TQualifier& argQualifier = arg->getAsTyped()->getQualifier();
if (argQualifier.isMemory()) {
const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
if (argQualifier.volatil && ! formalQualifier.volatil)
error(arguments->getLoc(), message, "volatile", "");
if (argQualifier.coherent && ! formalQualifier.coherent)
error(arguments->getLoc(), message, "coherent", "");
if (argQualifier.readonly && ! formalQualifier.readonly)
error(arguments->getLoc(), message, "readonly", "");
if (argQualifier.writeonly && ! formalQualifier.writeonly)
error(arguments->getLoc(), message, "writeonly", "");
}
// TODO 4.5 functionality: A shader will fail to compile
// if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
// shared variable. It is acceptable to pass an element of an array or a single component of a vector to the
// memargument of an atomic memory function, as long as the underlying array or vector is a buffer or
// shared variable.
}
// Convert 'in' arguments
addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node
}
op = fnCandidate->getBuiltInOp();
if (builtIn && op != EOpNull) {
// A function call mapped to a built-in operation.
checkLocation(loc, op);
result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType());
if (result == 0) {
error(arguments->getLoc(), " wrong operand type", "Internal Error",
"built in unary operator function. Type: %s",
static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
}
} else {
// This is a function call not mapped to built-in operator, but it could still be a built-in function
result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
TIntermAggregate* call = result->getAsAggregate();
call->setName(fnCandidate->getMangledName());
// this is how we know whether the given function is a built-in function or a user-defined function
// if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
// if builtIn == true, it's definitely a built-in function with EOpNull
if (! builtIn) {
call->setUserDefined();
intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
}
if (builtIn)
nonOpBuiltInCheck(loc, *fnCandidate, *call);
}
// Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
// Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
// Also, build the qualifier list for user function calls, which are always called with an aggregate.
if (result->getAsAggregate()) {
TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
qualifierList.push_back(qual);
}
result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
}
}
}
// generic error recovery
// TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
if (result == 0)
result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
return result;
}
// See if the operation is being done in an illegal location.
void TParseContext::checkLocation(TSourceLoc loc, TOperator op)
{
switch (op) {
case EOpBarrier:
if (language == EShLangTessControl) {
if (controlFlowNestingLevel > 0)
error(loc, "tessellation control barrier() cannot be placed within flow control", "", "");
if (! inMain)
error(loc, "tessellation control barrier() must be in main()", "", "");
else if (postMainReturn)
error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", "");
}
break;
default:
break;
}
}
// Finish processing object.length(). This started earlier in handleDotDereference(), where
// the ".length" part was recognized and semantically checked, and finished here where the
// function syntax "()" is recognized.
//
// Return resulting tree node.
TIntermTyped* TParseContext::handleLengthMethod(TSourceLoc loc, TFunction* function, TIntermNode* intermNode)
{
int length = 0;
if (function->getParamCount() > 0)
error(loc, "method does not accept any arguments", function->getName().c_str(), "");
else {
const TType& type = intermNode->getAsTyped()->getType();
if (type.isArray()) {
if (type.isRuntimeSizedArray()) {
// Create a unary op and let the back end handle it
return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
} else if (type.isImplicitlySizedArray()) {
if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
// We could be between a layout declaration that gives a built-in io array implicit size and
// a user redeclaration of that array, meaning we have to substitute its implicit size here
// without actually redeclaring the array. (It is an error to use a member before the
// redeclaration, but not an error to use the array name itself.)
const TString& name = intermNode->getAsSymbolNode()->getName();
if (name == "gl_in" || name == "gl_out")
length = getIoArrayImplicitSize();
}
if (length == 0) {
if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
else
error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
}
} else
length = type.getArraySize();
} else if (type.isMatrix())
length = type.getMatrixCols();
else if (type.isVector())
length = type.getVectorSize();
else {
// we should not get here, because earlier semantic checking should have prevented this path
error(loc, ".length()", "unexpected use of .length()", "");
}
}
if (length == 0)
length = 1;
return intermediate.addConstantUnion(length, loc);
}
//
// Add any needed implicit conversions for function-call arguments to input parameters.
//
void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
{
TIntermAggregate* aggregate = arguments->getAsAggregate();
// Process each argument's conversion
for (int i = 0; i < function.getParamCount(); ++i) {
// At this early point there is a slight ambiguity between whether an aggregate 'arguments'
// is the single argument itself or its children are the arguments. Only one argument
// means take 'arguments' itself as the one argument.
TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
if (*function[i].type != arg->getType()) {
if (function[i].type->getQualifier().isParamInput()) {
// In-qualified arguments just need an extra node added above the argument to
// convert to the correct type.
arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
if (arg) {
if (aggregate)
aggregate->getSequence()[i] = arg;
else
arguments = arg;
}
}
}
}
}
//
// Add any needed implicit output conversions for function-call arguments. This
// can require a new tree topology, complicated further by whether the function
// has a return value.
//
// Returns a node of a subtree that evaluates to the return value of the function.
//
TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
{
TIntermSequence& arguments = intermNode.getSequence();
// Will there be any output conversions?
bool outputConversions = false;
for (int i = 0; i < function.getParamCount(); ++i) {
if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().storage == EvqOut) {
outputConversions = true;
break;
}
}
if (! outputConversions)
return &intermNode;
// Setup for the new tree, if needed:
//
// Output conversions need a different tree topology.
// Out-qualified arguments need a temporary of the correct type, with the call
// followed by an assignment of the temporary to the original argument:
// void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
// ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
// Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
TIntermTyped* conversionTree = 0;
TVariable* tempRet = 0;
if (intermNode.getBasicType() != EbtVoid) {
// do the "tempRet = function(...), " bit from above
tempRet = makeInternalVariable("tempReturn", intermNode.getType());
TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
} else
conversionTree = &intermNode;
conversionTree = intermediate.makeAggregate(conversionTree);
// Process each argument's conversion
for (int i = 0; i < function.getParamCount(); ++i) {
if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
if (function[i].type->getQualifier().isParamOutput()) {
// Out-qualified arguments need to use the topology set up above.
// do the " ...(tempArg, ...), arg = tempArg" bit from above
TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
tempArg->getWritableType().getQualifier().makeTemporary();
TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
// replace the argument with another node for the same tempArg variable
arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
}
}
}
// Finalize the tree topology (see bigger comment above).
if (tempRet) {
// do the "..., tempRet" bit from above
TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
}
conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
return conversionTree;
}
//
// Do additional checking of built-in function calls that were not mapped
// to built-in operations (e.g., texturing functions).
//
// Assumes there has been a semantically correct match to a built-in function.
//
void TParseContext::nonOpBuiltInCheck(TSourceLoc loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
{
// built-in texturing functions get their return value precision from the precision of the sampler
if (fnCandidate.getType().getQualifier().precision == EpqNone &&
fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
callNode.getQualifier().precision = callNode.getAsAggregate()->getSequence()[0]->getAsTyped()->getQualifier().precision;
if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
TString featureString = fnCandidate.getName() + "(...)";
const char* feature = featureString.c_str();
profileRequires(loc, EEsProfile, 310, nullptr, feature);
int compArg = -1; // track which argument, if any, is the constant component argument
if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
// GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
profileRequires(loc, ~EEsProfile, 400, GL_ARB_texture_gather, feature);
else
profileRequires(loc, ~EEsProfile, 400, GL_ARB_gpu_shader5, feature);
if (! fnCandidate[0].type->getSampler().shadow)
compArg = 3;
} else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
profileRequires(loc, ~EEsProfile, 400, GL_ARB_gpu_shader5, feature);
if (! fnCandidate[0].type->getSampler().shadow)
compArg = 3;
// check for constant offsets
int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
error(loc, "must be a compile-time constant:", feature, "offsets argument");
} else if (fnCandidate.getName().compare("textureGather") == 0) {
// More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
// otherwise, need GL_ARB_texture_gather.
if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
profileRequires(loc, ~EEsProfile, 400, GL_ARB_gpu_shader5, feature);
if (! fnCandidate[0].type->getSampler().shadow)
compArg = 2;
} else
profileRequires(loc, ~EEsProfile, 400, GL_ARB_texture_gather, feature);
}
if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
if (value < 0 || value > 3)
error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
} else
error(loc, "must be a compile-time constant:", feature, "component argument");
}
} else {
// this is only for functions not starting "textureGather"...
if (fnCandidate.getName().find("Offset") != TString::npos) {
// Handle texture-offset limits checking
int arg = -1;
if (fnCandidate.getName().compare("textureOffset") == 0)
arg = 2;
else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
arg = 3;
else if (fnCandidate.getName().compare("textureProjOffset") == 0)
arg = 2;
else if (fnCandidate.getName().compare("textureLodOffset") == 0)
arg = 3;
else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
arg = 3;
else if (fnCandidate.getName().compare("textureGradOffset") == 0)
arg = 4;
else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
arg = 4;
if (arg > 0) {
if (! callNode.getSequence()[arg]->getAsConstantUnion())
error(loc, "argument must be compile-time constant", "texel offset", "");
else {
const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
for (int c = 0; c < type.getVectorSize(); ++c) {
int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
}
}
}
}
}
}
// GL_ARB_shader_texture_image_samples
if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
profileRequires(loc, ~EEsProfile, 450, GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
if (imageType.getQualifier().layoutFormat != ElfR32i && imageType.getQualifier().layoutFormat != ElfR32ui)
error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
} else if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0)
error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
}
}
//
// Handle seeing a built-in constructor in a grammar production.
//
TFunction* TParseContext::handleConstructorCall(TSourceLoc loc, const TPublicType& publicType)
{
TType type(publicType);
type.getQualifier().precision = EpqNone;
if (type.isArray()) {
profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "arrayed constructor");
profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor");
}
TOperator op = mapTypeToConstructorOp(type);
if (op == EOpNull) {
error(loc, "cannot construct this type", type.getBasicString(), "");
op = EOpConstructFloat;
TType errorType(EbtFloat);
type.shallowCopy(errorType);
}
TString empty("");
return new TFunction(&empty, type, op);
}
//
// Given a type, find what operation would fully construct it.
//
TOperator TParseContext::mapTypeToConstructorOp(const TType& type) const
{
if (type.isStruct())
return EOpConstructStruct;
TOperator op = EOpNull;
switch (type.getBasicType()) {
case EbtFloat:
if (type.isMatrix()) {
switch (type.getMatrixCols()) {
case 2:
switch (type.getMatrixRows()) {
case 2: op = EOpConstructMat2x2; break;
case 3: op = EOpConstructMat2x3; break;
case 4: op = EOpConstructMat2x4; break;
default: break; // some compilers want this
}
break;
case 3:
switch (type.getMatrixRows()) {
case 2: op = EOpConstructMat3x2; break;
case 3: op = EOpConstructMat3x3; break;
case 4: op = EOpConstructMat3x4; break;
default: break; // some compilers want this
}
break;
case 4:
switch (type.getMatrixRows()) {
case 2: op = EOpConstructMat4x2; break;
case 3: op = EOpConstructMat4x3; break;
case 4: op = EOpConstructMat4x4; break;
default: break; // some compilers want this
}
break;
default: break; // some compilers want this
}
} else {
switch(type.getVectorSize()) {
case 1: op = EOpConstructFloat; break;
case 2: op = EOpConstructVec2; break;
case 3: op = EOpConstructVec3; break;
case 4: op = EOpConstructVec4; break;
default: break; // some compilers want this
}
}
break;
case EbtDouble:
if (type.getMatrixCols()) {
switch (type.getMatrixCols()) {
case 2:
switch (type.getMatrixRows()) {
case 2: op = EOpConstructDMat2x2; break;
case 3: op = EOpConstructDMat2x3; break;
case 4: op = EOpConstructDMat2x4; break;
default: break; // some compilers want this
}
break;
case 3:
switch (type.getMatrixRows()) {
case 2: op = EOpConstructDMat3x2; break;
case 3: op = EOpConstructDMat3x3; break;
case 4: op = EOpConstructDMat3x4; break;
default: break; // some compilers want this
}
break;
case 4:
switch (type.getMatrixRows()) {
case 2: op = EOpConstructDMat4x2; break;
case 3: op = EOpConstructDMat4x3; break;
case 4: op = EOpConstructDMat4x4; break;
default: break; // some compilers want this
}
break;
}
} else {
switch(type.getVectorSize()) {
case 1: op = EOpConstructDouble; break;
case 2: op = EOpConstructDVec2; break;
case 3: op = EOpConstructDVec3; break;
case 4: op = EOpConstructDVec4; break;
default: break; // some compilers want this
}
}
break;
case EbtInt:
switch(type.getVectorSize()) {
case 1: op = EOpConstructInt; break;
case 2: op = EOpConstructIVec2; break;
case 3: op = EOpConstructIVec3; break;
case 4: op = EOpConstructIVec4; break;
default: break; // some compilers want this
}
break;
case EbtUint:
switch(type.getVectorSize()) {
case 1: op = EOpConstructUint; break;
case 2: op = EOpConstructUVec2; break;
case 3: op = EOpConstructUVec3; break;
case 4: op = EOpConstructUVec4; break;
default: break; // some compilers want this
}
break;
case EbtBool:
switch(type.getVectorSize()) {
case 1: op = EOpConstructBool; break;
case 2: op = EOpConstructBVec2; break;
case 3: op = EOpConstructBVec3; break;
case 4: op = EOpConstructBVec4; break;
default: break; // some compilers want this
}
break;
default:
break;
}
return op;
}
//
// Same error message for all places assignments don't work.
//
void TParseContext::assignError(TSourceLoc loc, const char* op, TString left, TString right)
{
error(loc, "", op, "cannot convert from '%s' to '%s'",
right.c_str(), left.c_str());
}
//
// Same error message for all places unary operations don't work.
//
void TParseContext::unaryOpError(TSourceLoc loc, const char* op, TString operand)
{
error(loc, " wrong operand type", op,
"no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
op, operand.c_str());
}
//
// Same error message for all binary operations don't work.
//
void TParseContext::binaryOpError(TSourceLoc loc, const char* op, TString left, TString right)
{
error(loc, " wrong operand types:", op,
"no operation '%s' exists that takes a left-hand operand of type '%s' and "
"a right operand of type '%s' (or there is no acceptable conversion)",
op, left.c_str(), right.c_str());
}
//
// A basic type of EbtVoid is a key that the name string was seen in the source, but
// it was not found as a variable in the symbol table. If so, give the error
// message and insert a dummy variable in the symbol table to prevent future errors.
//
void TParseContext::variableCheck(TIntermTyped*& nodePtr)
{
TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
if (! symbol)
return;
if (symbol->getType().getBasicType() == EbtVoid) {
error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
// Add to symbol table to prevent future error messages on the same name
TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
symbolTable.insert(*fakeVariable);
// substitute a symbol node for this new variable
nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
} else {
switch (symbol->getQualifier().storage) {
case EvqPointCoord:
profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord");
break;
default: break; // some compilers want this
}
}
}
//
// Both test and if necessary, spit out an error, to see if the node is really
// an l-value that can be operated on this way.
//
// Returns true if the was an error.
//
bool TParseContext::lValueErrorCheck(TSourceLoc loc, const char* op, TIntermTyped* node)
{
TIntermBinary* binaryNode = node->getAsBinaryNode();
if (binaryNode) {
bool errorReturn;
switch(binaryNode->getOp()) {
case EOpIndexDirect:
case EOpIndexIndirect:
case EOpIndexDirectStruct:
return lValueErrorCheck(loc, op, binaryNode->getLeft());
case EOpVectorSwizzle:
errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
if (!errorReturn) {
int offset[4] = {0,0,0,0};
TIntermTyped* rightNode = binaryNode->getRight();
TIntermAggregate *aggrNode = rightNode->getAsAggregate();
for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
p != aggrNode->getSequence().end(); p++) {
int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
offset[value]++;
if (offset[value] > 1) {
error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
return true;
}
}
}
return errorReturn;
default:
break;
}
error(loc, " l-value required", op, "", "");
return true;
}
const char* symbol = 0;
TIntermSymbol* symNode = node->getAsSymbolNode();
if (symNode != 0)
symbol = symNode->getName().c_str();
const char* message = 0;
switch (node->getQualifier().storage) {
case EvqConst: message = "can't modify a const"; break;
case EvqConstReadOnly: message = "can't modify a const"; break;
case EvqVaryingIn: message = "can't modify shader input"; break;
case EvqInstanceId: message = "can't modify gl_InstanceID"; break;
case EvqVertexId: message = "can't modify gl_VertexID"; break;
case EvqFace: message = "can't modify gl_FrontFace"; break;
case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
case EvqUniform: message = "can't modify a uniform"; break;
case EvqBuffer:
if (node->getQualifier().readonly)
message = "can't modify a readonly buffer";
break;
case EvqFragDepth:
// "In addition, it is an error to statically write to gl_FragDepth in the fragment shader."
if (profile == EEsProfile && intermediate.getEarlyFragmentTests())
message = "can't modify gl_FragDepth if using early_fragment_tests";
break;
default:
//
// Type that can't be written to?
//
switch (node->getBasicType()) {
case EbtSampler:
message = "can't modify a sampler";
break;
case EbtAtomicUint:
message = "can't modify an atomic_uint";
break;
case EbtVoid:
message = "can't modify void";
break;
default:
break;
}
}
if (message == 0 && binaryNode == 0 && symNode == 0) {
error(loc, " l-value required", op, "", "");
return true;
}
//
// Everything else is okay, no error.
//
if (message == 0)
return false;
//
// If we get here, we have an error and a message.
//
if (symNode)
error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
else
error(loc, " l-value required", op, "(%s)", message);
return true;
}
// Test for and give an error if the node can't be read from.
void TParseContext::rValueErrorCheck(TSourceLoc loc, const char* op, TIntermTyped* node)
{
if (! node)
return;
TIntermBinary* binaryNode = node->getAsBinaryNode();
if (binaryNode) {
switch(binaryNode->getOp()) {
case EOpIndexDirect:
case EOpIndexIndirect:
case EOpIndexDirectStruct:
case EOpVectorSwizzle:
rValueErrorCheck(loc, op, binaryNode->getLeft());
default:
break;
}
return;
}
TIntermSymbol* symNode = node->getAsSymbolNode();
if (symNode && symNode->getQualifier().writeonly)
error(loc, "can't read from writeonly object: ", op, symNode->getName().c_str());
}
//
// Both test, and if necessary spit out an error, to see if the node is really
// a constant.
//
void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
{
if (node->getQualifier().storage != EvqConst)
error(node->getLoc(), "constant expression required", token, "");
}
//
// Both test, and if necessary spit out an error, to see if the node is really
// an integer.
//
void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
{
if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
return;
error(node->getLoc(), "scalar integer expression required", token, "");
}
//
// Both test, and if necessary spit out an error, to see if we are currently
// globally scoped.
//
void TParseContext::globalCheck(TSourceLoc loc, const char* token)
{
if (! symbolTable.atGlobalLevel())
error(loc, "not allowed in nested scope", token, "");
}
//
// Reserved errors for GLSL.
//
void TParseContext::reservedErrorCheck(TSourceLoc loc, const TString& identifier)
{
// "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
// declared in a shader; this results in a compile-time error."
if (! symbolTable.atBuiltInLevel()) {
if (builtInName(identifier))
error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
// "In addition, all identifiers containing two consecutive underscores (__) are
// reserved; using such a name does not itself result in an error, but may result
// in undefined behavior."
if (identifier.find("__") != TString::npos)
warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
}
}
//
// Reserved errors for the preprocessor.
//
void TParseContext::reservedPpErrorCheck(TSourceLoc loc, const char* identifier, const char* op)
{
// "All macro names containing two consecutive underscores ( __ ) are reserved;
// defining such a name does not itself result in an error, but may result in
// undefined behavior. All macro names prefixed with "GL_" ("GL" followed by a
// single underscore) are also reserved, and defining such a name results in a
// compile-time error."
if (strncmp(identifier, "GL_", 3) == 0)
error(loc, "names beginning with \"GL_\" can't be (un)defined:", op, identifier);
else if (strstr(identifier, "__") != 0) {
if (profile == EEsProfile && version >= 300 &&
(strcmp(identifier, "__LINE__") == 0 ||
strcmp(identifier, "__FILE__") == 0 ||
strcmp(identifier, "__VERSION__") == 0))
error(loc, "predefined names can't be (un)defined:", op, identifier);
else
warn(loc, "names containing consecutive underscores are reserved:", op, identifier);
}
}
//
// See if this version/profile allows use of the line-continuation character '\'.
//
// Returns true if a line continuation should be done.
//
bool TParseContext::lineContinuationCheck(TSourceLoc loc, bool endOfComment)
{
const char* message = "line continuation";
bool lineContinuationAllowed = (profile == EEsProfile && version >= 300) ||
(profile != EEsProfile && (version >= 420 || extensionsTurnedOn(1, &GL_ARB_shading_language_420pack)));
if (endOfComment) {
if (lineContinuationAllowed)
warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
else
warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
return lineContinuationAllowed;
}
if (messages & EShMsgRelaxedErrors) {
if (! lineContinuationAllowed)
warn(loc, "not allowed in this version", message, "");
return true;
} else {
profileRequires(loc, EEsProfile, 300, nullptr, message);
profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, message);
}
return lineContinuationAllowed;
}
bool TParseContext::builtInName(const TString& identifier)
{
return identifier.compare(0, 3, "gl_") == 0;
}
//
// Make sure there is enough data and not too many arguments provided to the
// constructor to build something of the type of the constructor. Also returns
// the type of the constructor.
//
// Returns true if there was an error in construction.
//
bool TParseContext::constructorError(TSourceLoc loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
{
type.shallowCopy(function.getType());
bool constructingMatrix = false;
switch(op) {
case EOpConstructMat2x2:
case EOpConstructMat2x3:
case EOpConstructMat2x4:
case EOpConstructMat3x2:
case EOpConstructMat3x3:
case EOpConstructMat3x4:
case EOpConstructMat4x2:
case EOpConstructMat4x3:
case EOpConstructMat4x4:
case EOpConstructDMat2x2:
case EOpConstructDMat2x3:
case EOpConstructDMat2x4:
case EOpConstructDMat3x2:
case EOpConstructDMat3x3:
case EOpConstructDMat3x4:
case EOpConstructDMat4x2:
case EOpConstructDMat4x3:
case EOpConstructDMat4x4:
constructingMatrix = true;
break;
default:
break;
}
//
// Note: It's okay to have too many components available, but not okay to have unused
// arguments. 'full' will go to true when enough args have been seen. If we loop
// again, there is an extra argument, so 'overfull' will become true.
//
int size = 0;
bool constType = true;
bool full = false;
bool overFull = false;
bool matrixInMatrix = false;
bool arrayArg = false;
for (int i = 0; i < function.getParamCount(); ++i) {
size += function[i].type->computeNumComponents();
if (constructingMatrix && function[i].type->isMatrix())
matrixInMatrix = true;
if (full)
overFull = true;
if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
full = true;
if (function[i].type->getQualifier().storage != EvqConst)
constType = false;
if (function[i].type->isArray())
arrayArg = true;
}
if (constType)
type.getQualifier().storage = EvqConst;
if (type.isArray()) {
if (type.isImplicitlySizedArray()) {
// auto adapt the constructor type to the number of arguments
type.changeArraySize(function.getParamCount());
} else if (type.getArraySize() != function.getParamCount()) {
error(loc, "array constructor needs one argument per array element", "constructor", "");
return true;
}
}
if (arrayArg && op != EOpConstructStruct) {
error(loc, "constructing from a non-dereferenced array", "constructor", "");
return true;
}
if (matrixInMatrix && ! type.isArray()) {
profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix");
// "If a matrix argument is given to a matrix constructor,
// it is a compile-time error to have any other arguments."
if (function.getParamCount() > 1)
error(loc, "matrix constructed from matrix can only have one argument", "constructor", "");
return false;
}
if (overFull) {
error(loc, "too many arguments", "constructor", "");
return true;
}
if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
return true;
}
if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
(op == EOpConstructStruct && size < type.computeNumComponents())) {
error(loc, "not enough data provided for construction", "constructor", "");
return true;
}
TIntermTyped* typed = node->getAsTyped();
if (typed == 0) {
error(loc, "constructor argument does not have a type", "constructor", "");
return true;
}
if (op != EOpConstructStruct && typed->getBasicType() == EbtSampler) {
error(loc, "cannot convert a sampler", "constructor", "");
return true;
}
if (op != EOpConstructStruct && typed->getBasicType() == EbtAtomicUint) {
error(loc, "cannot convert an atomic_uint", "constructor", "");
return true;
}
if (typed->getBasicType() == EbtVoid) {
error(loc, "cannot convert a void", "constructor", "");
return true;
}
return false;
}
// Checks to see if a void variable has been declared and raise an error message for such a case
//
// returns true in case of an error
//
bool TParseContext::voidErrorCheck(TSourceLoc loc, const TString& identifier, const TBasicType basicType)
{
if (basicType == EbtVoid) {
error(loc, "illegal use of type 'void'", identifier.c_str(), "");
return true;
}
return false;
}
// Checks to see if the node (for the expression) contains a scalar boolean expression or not
void TParseContext::boolCheck(TSourceLoc loc, const TIntermTyped* type)
{
if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
error(loc, "boolean expression expected", "", "");
}
// This function checks to see if the node (for the expression) contains a scalar boolean expression or not
void TParseContext::boolCheck(TSourceLoc loc, const TPublicType& pType)
{
if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
error(loc, "boolean expression expected", "", "");
}
void TParseContext::samplerCheck(TSourceLoc loc, const TType& type, const TString& identifier)
{
if (type.getQualifier().storage == EvqUniform)
return;
if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler))
error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform)
error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
}
void TParseContext::atomicUintCheck(TSourceLoc loc, const TType& type, const TString& identifier)
{
if (type.getQualifier().storage == EvqUniform)
return;
if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
}
//
// Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
//
void TParseContext::globalQualifierFixCheck(TSourceLoc loc, TQualifier& qualifier)
{
// move from parameter/unknown qualifiers to pipeline in/out qualifiers
switch (qualifier.storage) {
case EvqIn:
profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs");
profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs");
qualifier.storage = EvqVaryingIn;
break;
case EvqOut:
profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs");
profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs");
qualifier.storage = EvqVaryingOut;
break;
case EvqInOut:
qualifier.storage = EvqVaryingIn;
error(loc, "cannot use 'inout' at global scope", "", "");
break;
default:
break;
}
invariantCheck(loc, qualifier);
}
//
// Check a full qualifier and type (no variable yet) at global level.
//
void TParseContext::globalQualifierTypeCheck(TSourceLoc loc, const TQualifier& qualifier, const TPublicType& publicType)
{
if (! symbolTable.atGlobalLevel())
return;
if (qualifier.isMemory() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer)
error(loc, "memory qualifiers cannot be used on this type", "", "");
if (qualifier.storage == EvqBuffer && publicType.basicType != EbtBlock)
error(loc, "buffers can be declared only as blocks", "buffer", "");
if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
return;
// now, knowing it is a shader in/out, do all the in/out semantic checks
if (publicType.basicType == EbtBool) {
error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
return;
}
if (publicType.basicType == EbtInt || publicType.basicType == EbtUint || publicType.basicType == EbtDouble) {
profileRequires(loc, EEsProfile, 300, nullptr, "shader input/output");
if (! qualifier.flat) {
if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
}
}
if (qualifier.patch && qualifier.isInterpolation())
error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
if (qualifier.storage == EvqVaryingIn) {
switch (language) {
case EShLangVertex:
if (publicType.basicType == EbtStruct) {
error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
return;
}
if (publicType.arraySizes) {
requireProfile(loc, ~EEsProfile, "vertex input arrays");
profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
}
if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
error(loc, "vertex input cannot be further qualified", "", "");
break;
case EShLangTessControl:
if (qualifier.patch)
error(loc, "can only use on output in tessellation-control shader", "patch", "");
break;
case EShLangTessEvaluation:
break;
case EShLangGeometry:
break;
case EShLangFragment:
if (publicType.userDef) {
profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input");
profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input");
if (publicType.userDef->containsStructure())
requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure");
if (publicType.userDef->containsArray())
requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array");
}
break;
case EShLangCompute:
if (! symbolTable.atBuiltInLevel())
error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
break;
default:
break;
}
} else {
// qualifier.storage == EvqVaryingOut
switch (language) {
case EShLangVertex:
if (publicType.userDef) {
profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output");
profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output");
if (publicType.userDef->containsStructure())
requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure");
if (publicType.userDef->containsArray())
requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array");
}
break;
case EShLangTessControl:
break;
case EShLangTessEvaluation:
if (qualifier.patch)
error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
break;
case EShLangGeometry:
break;
case EShLangFragment:
profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output");
if (publicType.basicType == EbtStruct) {
error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
return;
}
if (publicType.matrixRows > 0) {
error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
return;
}
break;
case EShLangCompute:
error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
break;
default:
break;
}
}
}
//
// Merge characteristics of the 'src' qualifier into the 'dst'.
// If there is duplication, issue error messages, unless 'force'
// is specified, which means to just override default settings.
//
// Also, when force is false, it will be assumed that 'src' follows
// 'dst', for the purpose of error checking order for versions
// that require specific orderings of qualifiers.
//
void TParseContext::mergeQualifiers(TSourceLoc loc, TQualifier& dst, const TQualifier& src, bool force)
{
// Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
if (src.isAuxiliary() && dst.isAuxiliary())
error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
// Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
if (src.isInterpolation() && dst.isInterpolation())
error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective)", "", "");
// Ordering
if (! force && ((profile != EEsProfile && version < 420) ||
(profile == EEsProfile && version < 310))
&& ! extensionsTurnedOn(1, &GL_ARB_shading_language_420pack)) {
// non-function parameters
if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
error(loc, "invariant qualifier must appear first", "", "");
else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
error(loc, "precision qualifier must appear as last qualifier", "", "");
// function parameters
if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
error(loc, "in/out must appear before const", "", "");
}
// Storage qualification
if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
dst.storage = src.storage;
else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
(dst.storage == EvqOut && src.storage == EvqIn))
dst.storage = EvqInOut;
else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
(dst.storage == EvqConst && src.storage == EvqIn))
dst.storage = EvqConstReadOnly;
else if (src.storage != EvqTemporary &&
src.storage != EvqGlobal)
error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
// Precision qualifiers
if (! force && src.precision != EpqNone && dst.precision != EpqNone)
error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
if (dst.precision == EpqNone || (force && src.precision != EpqNone))
dst.precision = src.precision;
// Layout qualifiers
mergeObjectLayoutQualifiers(dst, src, false);
// individual qualifiers
bool repeated = false;
#define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
MERGE_SINGLETON(invariant);
MERGE_SINGLETON(centroid);
MERGE_SINGLETON(smooth);
MERGE_SINGLETON(flat);
MERGE_SINGLETON(nopersp);
MERGE_SINGLETON(patch);
MERGE_SINGLETON(sample);
MERGE_SINGLETON(coherent);
MERGE_SINGLETON(volatil);
MERGE_SINGLETON(restrict);
MERGE_SINGLETON(readonly);
MERGE_SINGLETON(writeonly);
if (repeated)
error(loc, "replicated qualifiers", "", "");
}
void TParseContext::setDefaultPrecision(TSourceLoc loc, TPublicType& publicType, TPrecisionQualifier qualifier)
{
TBasicType basicType = publicType.basicType;
if (basicType == EbtSampler) {
defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
return; // all is well
}
if (basicType == EbtInt || basicType == EbtFloat) {
if (publicType.isScalar()) {
defaultPrecision[basicType] = qualifier;
if (basicType == EbtInt)
defaultPrecision[EbtUint] = qualifier;
return; // all is well
}
}
if (basicType == EbtAtomicUint) {
if (qualifier != EpqHigh)
error(loc, "can only apply highp to atomic_uint", "precision", "");
return;
}
error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
}
// used to flatten the sampler type space into a single dimension
// correlates with the declaration of defaultSamplerPrecision[]
int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
{
int arrayIndex = sampler.arrayed ? 1 : 0;
int shadowIndex = sampler.shadow ? 1 : 0;
int externalIndex = sampler.external ? 1 : 0;
return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
}
TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
{
if (publicType.basicType == EbtSampler)
return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
else
return defaultPrecision[publicType.basicType];
}
void TParseContext::precisionQualifierCheck(TSourceLoc loc, TBasicType baseType, TQualifier& qualifier)
{
// Built-in symbols are allowed some ambiguous precisions, to be pinned down
// later by context.
if (profile != EEsProfile || parsingBuiltins)
return;
if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh)
error(loc, "atomic counters can only be highp", "atomic_uint", "");
if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) {
if (qualifier.precision == EpqNone) {
if (messages & EShMsgRelaxedErrors)
warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'");
else
error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "");
qualifier.precision = EpqMedium;
defaultPrecision[baseType] = EpqMedium;
}
} else if (qualifier.precision != EpqNone)
error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), "");
}
void TParseContext::parameterTypeCheck(TSourceLoc loc, TStorageQualifier qualifier, const TType& type)
{
if ((qualifier == EvqOut || qualifier == EvqInOut) && (type.getBasicType() == EbtSampler || type.getBasicType() == EbtAtomicUint))
error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
}
bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
{
if (type.getBasicType() == basicType)
return true;
if (type.getBasicType() == EbtStruct) {
const TTypeList& structure = *type.getStruct();
for (unsigned int i = 0; i < structure.size(); ++i) {
if (containsFieldWithBasicType(*structure[i].type, basicType))
return true;
}
}
return false;
}
//
// Do size checking for an array type's size.
//
void TParseContext::arraySizeCheck(TSourceLoc loc, TIntermTyped* expr, int& size)
{
TIntermConstantUnion* constant = expr->getAsConstantUnion();
if (constant == 0 || (constant->getBasicType() != EbtInt && constant->getBasicType() != EbtUint)) {
error(loc, "array size must be a constant integer expression", "", "");
size = 1;
return;
}
size = constant->getConstArray()[0].getIConst();
if (size <= 0) {
error(loc, "array size must be a positive integer", "", "");
size = 1;
return;
}
}
//
// See if this qualifier can be an array.
//
// Returns true if there is an error.
//
bool TParseContext::arrayQualifierError(TSourceLoc loc, const TQualifier& qualifier)
{
if (qualifier.storage == EvqConst) {
profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "const array");
profileRequires(loc, EEsProfile, 300, nullptr, "const array");
}
if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
requireProfile(loc, ~EEsProfile, "vertex input arrays");
profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays");
}
return false;
}
//
// See if this qualifier and type combination can be an array.
// Assumes arrayQualifierError() was also called to catch the type-invariant tests.
//
// Returns true if there is an error.
//
bool TParseContext::arrayError(TSourceLoc loc, const TType& type)
{
if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) {
if (type.isArrayOfArrays())
requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output");
else if (type.getArraySize() && type.isStruct())
requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output");
}
if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) {
if (type.isArrayOfArrays())
requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input");
else if (type.getArraySize() && type.isStruct())
requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input");
}
return false;
}
//
// Require array to have size
//
void TParseContext::arraySizeRequiredCheck(TSourceLoc loc, int size)
{
if (size == 0)
error(loc, "array size required", "", "");
}
void TParseContext::structArrayCheck(TSourceLoc /*loc*/, const TType& type)
{
const TTypeList& structure = *type.getStruct();
for (int m = 0; m < (int)structure.size(); ++m) {
const TType& member = *structure[m].type;
if (member.isArray() && ! member.isExplicitlySizedArray())
arraySizeRequiredCheck(structure[m].loc, 0);
}
}
void TParseContext::arrayUnsizedCheck(TSourceLoc loc, const TQualifier& qualifier, int size, bool initializer)
{
// desktop always allows unsized variable arrays,
// ES always allows them if there is an initializer present to get the size from
if (parsingBuiltins || profile != EEsProfile || initializer)
return;
// for ES, if size isn't coming from an initializer, it has to be explicitly declared now,
// with very few exceptions
switch (language) {
case EShLangGeometry:
if (qualifier.storage == EvqVaryingIn)
if (extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader))
return;
break;
case EShLangTessControl:
if ( qualifier.storage == EvqVaryingIn ||
(qualifier.storage == EvqVaryingOut && ! qualifier.patch))
if (extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
return;
break;
case EShLangTessEvaluation:
if ((qualifier.storage == EvqVaryingIn && ! qualifier.patch) ||
qualifier.storage == EvqVaryingOut)
if (extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader))
return;
break;
default:
break;
}
arraySizeRequiredCheck(loc, size);
}
void TParseContext::arrayDimError(TSourceLoc loc)
{
requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "arrays of arrays");
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, "arrays of arrays");
profileRequires(loc, EEsProfile, 310, nullptr, "arrays of arrays");
}
void TParseContext::arrayDimCheck(TSourceLoc loc, TArraySizes* sizes1, TArraySizes* sizes2)
{
if ((sizes1 && sizes2) ||
(sizes1 && sizes1->isArrayOfArrays()) ||
(sizes2 && sizes2->isArrayOfArrays()))
arrayDimError(loc);
}
void TParseContext::arrayDimCheck(TSourceLoc loc, const TType* type, TArraySizes* sizes2)
{
if ((type && type->isArray() && sizes2) ||
(sizes2 && sizes2->isArrayOfArrays()))
arrayDimError(loc);
}
//
// Do all the semantic checking for declaring or redeclaring an array, with and
// without a size, and make the right changes to the symbol table.
//
// size == 0 means no specified size.
//
void TParseContext::declareArray(TSourceLoc loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration)
{
if (! symbol) {
bool currentScope;
symbol = symbolTable.find(identifier, nullptr, ¤tScope);
if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
// bad shader (errors already reported) trying to redeclare a built-in name as an array
return;
}
if (symbol == 0 || ! currentScope) {
//
// Successfully process a new definition.
// (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
//
symbol = new TVariable(&identifier, type);
symbolTable.insert(*symbol);
newDeclaration = true;
if (! symbolTable.atBuiltInLevel()) {
if (isIoResizeArray(type)) {
ioArraySymbolResizeList.push_back(symbol);
checkIoArraysConsistency(loc, true);
} else
fixIoArraySize(loc, symbol->getWritableType());
}
return;
}
if (symbol->getAsAnonMember()) {
error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
symbol = 0;
return;
}
}
//
// Process a redeclaration.
//
if (! symbol) {
error(loc, "array variable name expected", identifier.c_str(), "");
return;
}
// redeclareBuiltinVariable() should have already done the copyUp()
TType& existingType = symbol->getWritableType();
if (! existingType.isArray()) {
error(loc, "redeclaring non-array as array", identifier.c_str(), "");
return;
}
if (existingType.isExplicitlySizedArray()) {
// be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
if (! (isIoResizeArray(type) && existingType.getArraySize() == type.getArraySize()))
error(loc, "redeclaration of array with size", identifier.c_str(), "");
return;
}
if (! existingType.sameElementType(type)) {
error(loc, "redeclaration of array with a different type", identifier.c_str(), "");
return;
}
arrayLimitCheck(loc, identifier, type.getArraySize());
existingType.updateArraySizes(type);
if (isIoResizeArray(type))
checkIoArraysConsistency(loc);
}
void TParseContext::updateImplicitArraySize(TSourceLoc loc, TIntermNode *node, int index)
{
// maybe there is nothing to do...
TIntermTyped* typedNode = node->getAsTyped();
if (typedNode->getType().getImplicitArraySize() > index)
return;
// something to do...
// Figure out what symbol to lookup, as we will use its type to edit for the size change,
// as that type will be shared through shallow copies for future references.
TSymbol* symbol = 0;
int blockIndex = -1;
const TString* lookupName = 0;
if (node->getAsSymbolNode())
lookupName = &node->getAsSymbolNode()->getName();
else if (node->getAsBinaryNode()) {
const TIntermBinary* deref = node->getAsBinaryNode();
// This has to be the result of a block dereference, unless it's bad shader code
// If it's a uniform block, then an error will be issued elsewhere, but
// return early now to avoid crashing later in this function.
if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock ||
deref->getLeft()->getType().getQualifier().storage == EvqUniform ||
deref->getRight()->getAsConstantUnion() == 0)
return;
blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
if (IsAnonymous(*lookupName))
lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
}
// Lookup the symbol, should only fail if shader code is incorrect
symbol = symbolTable.find(*lookupName);
if (symbol == 0)
return;
if (symbol->getAsFunction()) {
error(loc, "array variable name expected", symbol->getName().c_str(), "");
return;
}
symbol->getWritableType().setImplicitArraySize(index + 1);
}
//
// Enforce non-initializer type/qualifier rules.
//
void TParseContext::nonInitConstCheck(TSourceLoc loc, TString& identifier, TType& type)
{
//
// Make the qualifier make sense, given that there is an initializer.
//
if (type.getQualifier().storage == EvqConst ||
type.getQualifier().storage == EvqConstReadOnly) {
type.getQualifier().storage = EvqTemporary;
error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
}
}
//
// See if the identifier is a built-in symbol that can be redeclared, and if so,
// copy the symbol table's read-only built-in variable to the current
// global level, where it can be modified based on the passed in type.
//
// Returns 0 if no redeclaration took place; meaning a normal declaration still
// needs to occur for it, not necessarily an error.
//
// Returns a redeclared and type-modified variable if a redeclarated occurred.
//
TSymbol* TParseContext::redeclareBuiltinVariable(TSourceLoc loc, const TString& identifier, const TQualifier& qualifier, const TShaderQualifiers& publicType, bool& newDeclaration)
{
if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
return 0;
bool nonEsRedecls = (profile != EEsProfile && (version >= 130 || identifier == "gl_TexCoord"));
bool esRedecls = (profile == EEsProfile && extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks));
if (! esRedecls && ! nonEsRedecls)
return 0;
// Special case when using GL_ARB_separate_shader_objects
bool ssoPre150 = false; // means the only reason this variable is redeclared is due to this combination
if (profile != EEsProfile && version <= 140 && extensionsTurnedOn(1, &GL_ARB_separate_shader_objects)) {
if (identifier == "gl_Position" ||
identifier == "gl_PointSize" ||
identifier == "gl_ClipVertex" ||
identifier == "gl_FogFragCoord")
ssoPre150 = true;
}
// Potentially redeclaring a built-in variable...
if (ssoPre150 ||
(identifier == "gl_FragDepth" && ((nonEsRedecls && version >= 420) || esRedecls)) ||
(identifier == "gl_FragCoord" && ((nonEsRedecls && version >= 150) || esRedecls)) ||
identifier == "gl_ClipDistance" ||
identifier == "gl_FrontColor" ||
identifier == "gl_BackColor" ||
identifier == "gl_FrontSecondaryColor" ||
identifier == "gl_BackSecondaryColor" ||
identifier == "gl_SecondaryColor" ||
(identifier == "gl_Color" && language == EShLangFragment) ||
identifier == "gl_TexCoord") {
// Find the existing symbol, if any.
bool builtIn;
TSymbol* symbol = symbolTable.find(identifier, &builtIn);
// If the symbol was not found, this must be a version/profile/stage
// that doesn't have it.
if (! symbol)
return 0;
// If it wasn't at a built-in level, then it's already been redeclared;
// that is, this is a redeclaration of a redeclaration; reuse that initial
// redeclaration. Otherwise, make the new one.
if (builtIn) {
// Copy the symbol up to make a writable version
makeEditable(symbol);
newDeclaration = true;
}
// Now, modify the type of the copy, as per the type of the current redeclaration.
TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
if (ssoPre150) {
if (intermediate.inIoAccessed(identifier))
error(loc, "cannot redeclare after use", identifier.c_str(), "");
if (qualifier.hasLayout())
error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex && qualifier.storage != EvqVaryingOut) ||
(language == EShLangFragment && qualifier.storage != EvqVaryingIn))
error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
if (! qualifier.smooth)
error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
} else if (identifier == "gl_FrontColor" ||
identifier == "gl_BackColor" ||
identifier == "gl_FrontSecondaryColor" ||
identifier == "gl_BackSecondaryColor" ||
identifier == "gl_SecondaryColor" ||
identifier == "gl_Color") {
symbolQualifier.flat = qualifier.flat;
symbolQualifier.smooth = qualifier.smooth;
symbolQualifier.nopersp = qualifier.nopersp;
if (qualifier.hasLayout())
error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
} else if (identifier == "gl_TexCoord" ||
identifier == "gl_ClipDistance") {
if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
symbolQualifier.storage != qualifier.storage)
error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
} else if (identifier == "gl_FragCoord") {
if (intermediate.inIoAccessed("gl_FragCoord"))
error(loc, "cannot redeclare after use", "gl_FragCoord", "");
if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
qualifier.isMemory() || qualifier.isAuxiliary())
error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
if (qualifier.storage != EvqVaryingIn)
error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() ||
publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
if (publicType.pixelCenterInteger)
intermediate.setPixelCenterInteger();
if (publicType.originUpperLeft)
intermediate.setOriginUpperLeft();
} else if (identifier == "gl_FragDepth") {
if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
qualifier.isMemory() || qualifier.isAuxiliary())
error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
if (qualifier.storage != EvqVaryingOut)
error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
if (publicType.layoutDepth != EldNone) {
if (intermediate.inIoAccessed("gl_FragDepth"))
error(loc, "cannot redeclare after use", "gl_FragDepth", "");
if (! intermediate.setDepth(publicType.layoutDepth))
error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
}
}
// TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
return symbol;
}
return 0;
}
//
// Either redeclare the requested block, or give an error message why it can't be done.
//
// TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
void TParseContext::redeclareBuiltinBlock(TSourceLoc loc, TTypeList& newTypeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes)
{
const char* feature = "built-in block redeclaration";
profileRequires(loc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment") {
error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
return;
}
// Redeclaring a built-in block...
if (instanceName && ! builtInName(*instanceName)) {
error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
return;
}
// Blocks with instance names are easy to find, lookup the instance name,
// Anonymous blocks need to be found via a member.
bool builtIn;
TSymbol* block;
if (instanceName)
block = symbolTable.find(*instanceName, &builtIn);
else
block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
// If the block was not found, this must be a version/profile/stage
// that doesn't have it, or the instance name is wrong.
const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
if (! block) {
error(loc, "no declaration found for redeclaration", errorName, "");
return;
}
// Built-in blocks cannot be redeclared more than once, which if happened,
// we'd be finding the already redeclared one here, rather than the built in.
if (! builtIn) {
error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
return;
}
// Copy the block to make a writable version, to insert into the block table after editing.
block = symbolTable.copyUpDeferredInsert(block);
if (block->getType().getBasicType() != EbtBlock) {
error(loc, "cannot redeclare a non block as a block", errorName, "");
return;
}
// Edit and error check the container against the redeclaration
// - remove unused members
// - ensure remaining qualifiers/types match
TType& type = block->getWritableType();
TTypeList::iterator member = type.getWritableStruct()->begin();
size_t numOriginalMembersFound = 0;
while (member != type.getStruct()->end()) {
// look for match
bool found = false;
TTypeList::const_iterator newMember;
TSourceLoc memberLoc;
memberLoc.init();
for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
if (member->type->getFieldName() == newMember->type->getFieldName()) {
found = true;
memberLoc = newMember->loc;
break;
}
}
if (found) {
++numOriginalMembersFound;
// - ensure match between redeclared members' types
// - check for things that can't be changed
// - update things that can be changed
TType& oldType = *member->type;
const TType& newType = *newMember->type;
if (! newType.sameElementType(oldType))
error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
if (oldType.isArray() != newType.isArray())
error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
else if (! oldType.sameArrayness(newType) && oldType.isExplicitlySizedArray())
error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
else if (newType.isArray())
arrayLimitCheck(loc, member->type->getFieldName(), newType.getArraySize());
if (newType.getQualifier().isMemory())
error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
if (newType.getQualifier().hasLayout())
error(memberLoc, "cannot add layout to redeclared block member", member->type->getFieldName().c_str(), "");
if (newType.getQualifier().patch)
error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
oldType.getQualifier().centroid = newType.getQualifier().centroid;
oldType.getQualifier().sample = newType.getQualifier().sample;
oldType.getQualifier().invariant = newType.getQualifier().invariant;
oldType.getQualifier().smooth = newType.getQualifier().smooth;
oldType.getQualifier().flat = newType.getQualifier().flat;
oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
// go to next member
++member;
} else {
// For missing members of anonymous blocks that have been redeclared,
// hide the original (shared) declaration.
// Instance-named blocks can just have the member removed.
if (instanceName)
member = type.getWritableStruct()->erase(member);
else {
member->type->hideMember();
++member;
}
}
}
if (numOriginalMembersFound < newTypeList.size())
error(loc, "block redeclaration has extra members", blockName.c_str(), "");
if (type.isArray() != (arraySizes != 0))
error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
else if (type.isArray()) {
if (type.isExplicitlySizedArray() && arraySizes->getSize() == 0)
error(loc, "block already declared with size, can't redeclare as implicitly-sized", blockName.c_str(), "");
else if (type.isExplicitlySizedArray() && type.getArraySize() != arraySizes->getSize())
error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
else if (type.isImplicitlySizedArray() && arraySizes->getSize() > 0)
type.changeArraySize(arraySizes->getSize());
}
symbolTable.insert(*block);
// Check for general layout qualifier errors
layoutObjectCheck(loc, *block);
// Tracking for implicit sizing of array
if (isIoResizeArray(block->getType())) {
ioArraySymbolResizeList.push_back(block);
checkIoArraysConsistency(loc, true);
} else if (block->getType().isArray())
fixIoArraySize(loc, block->getWritableType());
// Save it in the AST for linker use.
intermediate.addSymbolLinkageNode(linkage, *block);
}
void TParseContext::paramCheckFix(TSourceLoc loc, const TStorageQualifier& qualifier, TType& type)
{
switch (qualifier) {
case EvqConst:
case EvqConstReadOnly:
type.getQualifier().storage = EvqConstReadOnly;
break;
case EvqIn:
case EvqOut:
case EvqInOut:
type.getQualifier().storage = qualifier;
break;
case EvqGlobal:
case EvqTemporary:
type.getQualifier().storage = EvqIn;
break;
default:
type.getQualifier().storage = EvqIn;
error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
break;
}
}
void TParseContext::paramCheckFix(TSourceLoc loc, const TQualifier& qualifier, TType& type)
{
if (qualifier.isMemory()) {
type.getQualifier().volatil = qualifier.volatil;
type.getQualifier().coherent = qualifier.coherent;
type.getQualifier().readonly = qualifier.readonly;
type.getQualifier().writeonly = qualifier.writeonly;
type.getQualifier().restrict = qualifier.restrict;
}
if (qualifier.isAuxiliary() ||
qualifier.isInterpolation())
error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
if (qualifier.hasLayout())
error(loc, "cannot use layout qualifiers on a function parameter", "", "");
if (qualifier.invariant)
error(loc, "cannot use invariant qualifier on a function parameter", "", "");
paramCheckFix(loc, qualifier.storage, type);
}
void TParseContext::nestedBlockCheck(TSourceLoc loc)
{
if (structNestingLevel > 0)
error(loc, "cannot nest a block definition inside a structure or block", "", "");
++structNestingLevel;
}
void TParseContext::nestedStructCheck(TSourceLoc loc)
{
if (structNestingLevel > 0)
error(loc, "cannot nest a structure definition inside a structure or block", "", "");
++structNestingLevel;
}
void TParseContext::arrayObjectCheck(TSourceLoc loc, const TType& type, const char* op)
{
// Some versions don't allow comparing arrays or structures containing arrays
if (type.containsArray()) {
profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, op);
profileRequires(loc, EEsProfile, 300, nullptr, op);
}
}
void TParseContext::opaqueCheck(TSourceLoc loc, const TType& type, const char* op)
{
if (containsFieldWithBasicType(type, EbtSampler))
error(loc, "can't use with samplers or structs containing samplers", op, "");
}
void TParseContext::structTypeCheck(TSourceLoc /*loc*/, TPublicType& publicType)
{
const TTypeList& typeList = *publicType.userDef->getStruct();
// fix and check for member storage qualifiers and types that don't belong within a structure
for (unsigned int member = 0; member < typeList.size(); ++member) {
TQualifier& memberQualifier = typeList[member].type->getQualifier();
TSourceLoc memberLoc = typeList[member].loc;
if (memberQualifier.isAuxiliary() ||
memberQualifier.isInterpolation() ||
(memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
if (memberQualifier.isMemory())
error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
if (memberQualifier.hasLayout()) {
error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
memberQualifier.clearLayout();
}
if (memberQualifier.invariant)
error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
}
}
//
// See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
//
// "The loop index has type int or float.
//
// "The for statement has the form:
// for ( init-declaration ; condition ; expression )
// init-declaration has the form: type-specifier identifier = constant-expression
// condition has the form: loop-index relational_operator constant-expression
// where relational_operator is one of: > >= < <= == or !=
// expression [sic] has one of the following forms:
// loop-index++
// loop-index--
// loop-index += constant-expression
// loop-index -= constant-expression
//
// The body is handled in an AST traversal.
//
void TParseContext::inductiveLoopCheck(TSourceLoc loc, TIntermNode* init, TIntermLoop* loop)
{
// loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
bool badInit = false;
if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1)
badInit = true;
TIntermBinary* binaryInit = 0;
if (! badInit) {
// get the declaration assignment
binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
if (! binaryInit)
badInit = true;
}
if (badInit) {
error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
return;
}
// loop index must be type int or float
if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
return;
}
// init is the form "loop-index = constant"
if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
return;
}
// get the unique id of the loop index
int loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
inductiveLoopIds.insert(loopIndex);
// condition's form must be "loop-index relational-operator constant-expression"
bool badCond = ! loop->getTest();
if (! badCond) {
TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
badCond = ! binaryCond;
if (! badCond) {
switch (binaryCond->getOp()) {
case EOpGreaterThan:
case EOpGreaterThanEqual:
case EOpLessThan:
case EOpLessThanEqual:
case EOpEqual:
case EOpNotEqual:
break;
default:
badCond = true;
}
}
if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
! binaryCond->getRight()->getAsConstantUnion()))
badCond = true;
}
if (badCond) {
error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
return;
}
// loop-index++
// loop-index--
// loop-index += constant-expression
// loop-index -= constant-expression
bool badTerminal = ! loop->getTerminal();
if (! badTerminal) {
TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
if (unaryTerminal || binaryTerminal) {
switch(loop->getTerminal()->getAsOperator()->getOp()) {
case EOpPostDecrement:
case EOpPostIncrement:
case EOpAddAssign:
case EOpSubAssign:
break;
default:
badTerminal = true;
}
} else
badTerminal = true;
if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
! binaryTerminal->getRight()->getAsConstantUnion()))
badTerminal = true;
if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
badTerminal = true;
}
if (badTerminal) {
error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
return;
}
// the body
inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
}
// Do limit checks against for all built-in arrays.
void TParseContext::arrayLimitCheck(TSourceLoc loc, const TString& identifier, int size)
{
if (identifier.compare("gl_TexCoord") == 0)
limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
else if (identifier.compare("gl_ClipDistance") == 0)
limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
}
// See if the provided value is less than the symbol indicated by limit,
// which should be a constant in the symbol table.
void TParseContext::limitCheck(TSourceLoc loc, int value, const char* limit, const char* feature)
{
TSymbol* symbol = symbolTable.find(limit);
assert(symbol->getAsVariable());
const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
assert(! constArray.empty());
if (value >= constArray[0].getIConst())
error(loc, "must be less than", feature, "%s (%d)", limit, constArray[0].getIConst());
}
//
// Do any additional error checking, etc., once we know the parsing is done.
//
void TParseContext::finalErrorCheck()
{
// Check on array indexes for ES 2.0 (version 100) limitations.
for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
// Check for stages that are enabled by extension.
// Can't do this at the beginning, it is chicken and egg to add a stage by
// extension.
// Stage-specific features were correctly tested for already, this is just
// about the stage itself.
switch (language) {
case EShLangGeometry:
if (profile == EEsProfile && version == 310)
requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders");
break;
case EShLangTessControl:
case EShLangTessEvaluation:
if (profile == EEsProfile && version == 310)
requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders");
else if (profile != EEsProfile && version < 400)
requireExtensions(getCurrentLoc(), 1, &GL_ARB_tessellation_shader, "tessellation shaders");
break;
case EShLangCompute:
if (profile != EEsProfile && version < 430)
requireExtensions(getCurrentLoc(), 1, &GL_ARB_compute_shader, "tessellation shaders");
break;
default:
break;
}
}
//
// Layout qualifier stuff.
//
// Put the id's layout qualification into the public type, for qualifiers not having a number set.
// This is before we know any type information for error checking.
void TParseContext::setLayoutQualifier(TSourceLoc loc, TPublicType& publicType, TString& id)
{
std::transform(id.begin(), id.end(), id.begin(), ::tolower);
if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
publicType.qualifier.layoutMatrix = ElmColumnMajor;
return;
}
if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
publicType.qualifier.layoutMatrix = ElmRowMajor;
return;
}
if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
publicType.qualifier.layoutPacking = ElpPacked;
return;
}
if (id == TQualifier::getLayoutPackingString(ElpShared)) {
publicType.qualifier.layoutPacking = ElpShared;
return;
}
if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
publicType.qualifier.layoutPacking = ElpStd140;
return;
}
if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, "std430");
profileRequires(loc, EEsProfile, 310, nullptr, "std430");
publicType.qualifier.layoutPacking = ElpStd430;
return;
}
for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
if (id == TQualifier::getLayoutFormatString(format)) {
if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
(format > ElfEsIntGuard && format < ElfIntGuard) ||
(format > ElfEsUintGuard && format < ElfCount))
requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, GL_ARB_shader_image_load_store, "image load store");
profileRequires(loc, EEsProfile, 310, GL_ARB_shader_image_load_store, "image load store");
publicType.qualifier.layoutFormat = format;
return;
}
}
if (language == EShLangGeometry || language == EShLangTessEvaluation) {
if (id == TQualifier::getGeometryString(ElgTriangles)) {
publicType.shaderQualifiers.geometry = ElgTriangles;
return;
}
if (language == EShLangGeometry) {
if (id == TQualifier::getGeometryString(ElgPoints)) {
publicType.shaderQualifiers.geometry = ElgPoints;
return;
}
if (id == TQualifier::getGeometryString(ElgLineStrip)) {
publicType.shaderQualifiers.geometry = ElgLineStrip;
return;
}
if (id == TQualifier::getGeometryString(ElgLines)) {
publicType.shaderQualifiers.geometry = ElgLines;
return;
}
if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
return;
}
if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
return;
}
if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
publicType.shaderQualifiers.geometry = ElgTriangleStrip;
return;
}
} else {
assert(language == EShLangTessEvaluation);
// input primitive
if (id == TQualifier::getGeometryString(ElgTriangles)) {
publicType.shaderQualifiers.geometry = ElgTriangles;
return;
}
if (id == TQualifier::getGeometryString(ElgQuads)) {
publicType.shaderQualifiers.geometry = ElgQuads;
return;
}
if (id == TQualifier::getGeometryString(ElgIsolines)) {
publicType.shaderQualifiers.geometry = ElgIsolines;
return;
}
// vertex spacing
if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
publicType.shaderQualifiers.spacing = EvsEqual;
return;
}
if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
publicType.shaderQualifiers.spacing = EvsFractionalEven;
return;
}
if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
publicType.shaderQualifiers.spacing = EvsFractionalOdd;
return;
}
// triangle order
if (id == TQualifier::getVertexOrderString(EvoCw)) {
publicType.shaderQualifiers.order = EvoCw;
return;
}
if (id == TQualifier::getVertexOrderString(EvoCcw)) {
publicType.shaderQualifiers.order = EvoCcw;
return;
}
// point mode
if (id == "point_mode") {
publicType.shaderQualifiers.pointMode = true;
return;
}
}
}
if (language == EShLangFragment) {
if (id == "origin_upper_left") {
requireProfile(loc, ECoreProfile | ECompatibilityProfile, "origin_upper_left");
publicType.shaderQualifiers.originUpperLeft = true;
return;
}
if (id == "pixel_center_integer") {
requireProfile(loc, ECoreProfile | ECompatibilityProfile, "pixel_center_integer");
publicType.shaderQualifiers.pixelCenterInteger = true;
return;
}
if (id == "early_fragment_tests") {
profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, GL_ARB_shader_image_load_store, "early_fragment_tests");
profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests");
publicType.shaderQualifiers.earlyFragmentTests = true;
return;
}
for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
if (id == TQualifier::getLayoutDepthString(depth)) {
requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier");
publicType.shaderQualifiers.layoutDepth = depth;
return;
}
}
}
error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
}
// Put the id's layout qualifier value into the public type, for qualifiers having a number set.
// This is before we know any type information for error checking.
void TParseContext::setLayoutQualifier(TSourceLoc loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
{
const char* feature = "layout-id value";
const char* nonLiteralFeature = "non-literal layout-id value";
integerCheck(node, feature);
const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
int value;
if (constUnion) {
value = constUnion->getConstArray()[0].getIConst();
if (! constUnion->isLiteral()) {
requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, nonLiteralFeature);
}
} else {
// grammar should have give out the error message
value = 0;
}
if (value < 0) {
error(loc, "cannot be negative", feature, "");
return;
}
std::transform(id.begin(), id.end(), id.begin(), ::tolower);
if (id == "offset") {
const char* feature = "uniform offset";
requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
const char* exts[2] = { GL_ARB_enhanced_layouts, GL_ARB_shader_atomic_counters };
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
profileRequires(loc, EEsProfile, 310, nullptr, feature);
publicType.qualifier.layoutOffset = value;
return;
} else if (id == "align") {
const char* feature = "uniform buffer-member align";
requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, feature);
// "The specified alignment must be a power of 2, or a compile-time error results."
if (! IsPow2(value))
error(loc, "must be a power of 2", "align", "");
else
publicType.qualifier.layoutAlign = value;
return;
} else if (id == "location") {
profileRequires(loc, EEsProfile, 300, nullptr, "location");
const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
if ((unsigned int)value >= TQualifier::layoutLocationEnd)
error(loc, "location is too large", id.c_str(), "");
else
publicType.qualifier.layoutLocation = value;
return;
} else if (id == "set") {
if ((unsigned int)value >= TQualifier::layoutSetEnd)
error(loc, "set is too large", id.c_str(), "");
else
publicType.qualifier.layoutSet = value;
return;
} else if (id == "binding") {
profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, "binding");
profileRequires(loc, EEsProfile, 310, nullptr, "binding");
if ((unsigned int)value >= TQualifier::layoutBindingEnd)
error(loc, "binding is too large", id.c_str(), "");
else
publicType.qualifier.layoutBinding = value;
return;
} else if (id == "component") {
requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, "component");
if ((unsigned)value >= TQualifier::layoutComponentEnd)
error(loc, "component is too large", id.c_str(), "");
else
publicType.qualifier.layoutComponent = value;
return;
} else if (id.compare(0, 4, "xfb_") == 0) {
// "Any shader making any static use (after preprocessing) of any of these
// *xfb_* qualifiers will cause the shader to be in a transform feedback
// capturing mode and hence responsible for describing the transform feedback
// setup."
intermediate.setXfbMode();
const char* feature = "transform feedback qualifier";
requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, feature);
if (id == "xfb_buffer") {
// "It is a compile-time error to specify an *xfb_buffer* that is greater than
// the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
if (value >= resources.maxTransformFeedbackBuffers)
error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
if (value >= TQualifier::layoutXfbBufferEnd)
error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
else
publicType.qualifier.layoutXfbBuffer = value;
return;
} else if (id == "xfb_offset") {
if (value >= TQualifier::layoutXfbOffsetEnd)
error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
else
publicType.qualifier.layoutXfbOffset = value;
return;
} else if (id == "xfb_stride") {
// "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
// implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents);
else if (value >= TQualifier::layoutXfbStrideEnd)
error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
if (value < TQualifier::layoutXfbStrideEnd)
publicType.qualifier.layoutXfbStride = value;
return;
}
}
switch (language) {
case EShLangVertex:
break;
case EShLangTessControl:
if (id == "vertices") {
publicType.shaderQualifiers.vertices = value;
return;
}
break;
case EShLangTessEvaluation:
break;
case EShLangGeometry:
if (id == "invocations") {
profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations");
publicType.shaderQualifiers.invocations = value;
return;
}
if (id == "max_vertices") {
publicType.shaderQualifiers.vertices = value;
if (value > resources.maxGeometryOutputVertices)
error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
return;
}
if (id == "stream") {
requireProfile(loc, ~EEsProfile, "selecting output stream");
publicType.qualifier.layoutStream = value;
return;
}
break;
case EShLangFragment:
if (id == "index") {
requireProfile(loc, ECompatibilityProfile | ECoreProfile, "index layout qualifier on fragment output");
const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
publicType.qualifier.layoutIndex = value;
return;
}
break;
case EShLangCompute:
if (id == "local_size_x") {
publicType.shaderQualifiers.localSize[0] = value;
return;
}
if (id == "local_size_y") {
publicType.shaderQualifiers.localSize[1] = value;
return;
}
if (id == "local_size_z") {
publicType.shaderQualifiers.localSize[2] = value;
return;
}
break;
default:
break;
}
error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
}
// Merge any layout qualifier information from src into dst, leaving everything else in dst alone
//
// "More than one layout qualifier may appear in a single declaration.
// Additionally, the same layout-qualifier-name can occur multiple times
// within a layout qualifier or across multiple layout qualifiers in the
// same declaration. When the same layout-qualifier-name occurs
// multiple times, in a single declaration, the last occurrence overrides
// the former occurrence(s). Further, if such a layout-qualifier-name
// will effect subsequent declarations or other observable behavior, it
// is only the last occurrence that will have any effect, behaving as if
// the earlier occurrence(s) within the declaration are not present.
// This is also true for overriding layout-qualifier-names, where one
// overrides the other (e.g., row_major vs. column_major); only the last
// occurrence has any effect."
//
void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
{
if (src.hasMatrix())
dst.layoutMatrix = src.layoutMatrix;
if (src.hasPacking())
dst.layoutPacking = src.layoutPacking;
if (src.hasStream())
dst.layoutStream = src.layoutStream;
if (src.hasFormat())
dst.layoutFormat = src.layoutFormat;
if (src.hasXfbBuffer())
dst.layoutXfbBuffer = src.layoutXfbBuffer;
if (src.hasAlign())
dst.layoutAlign = src.layoutAlign;
if (! inheritOnly) {
if (src.hasLocation())
dst.layoutLocation = src.layoutLocation;
if (src.hasComponent())
dst.layoutComponent = src.layoutComponent;
if (src.hasIndex())
dst.layoutIndex = src.layoutIndex;
if (src.hasOffset())
dst.layoutOffset = src.layoutOffset;
if (src.hasSet())
dst.layoutSet = src.layoutSet;
if (src.layoutBinding != TQualifier::layoutBindingEnd)
dst.layoutBinding = src.layoutBinding;
if (src.hasXfbStride())
dst.layoutXfbStride = src.layoutXfbStride;
if (src.hasXfbOffset())
dst.layoutXfbOffset = src.layoutXfbOffset;
}
}
// Do error layout error checking given a full variable/block declaration.
void TParseContext::layoutObjectCheck(TSourceLoc loc, const TSymbol& symbol)
{
const TType& type = symbol.getType();
const TQualifier& qualifier = type.getQualifier();
// first, cross check WRT to just the type
layoutTypeCheck(loc, type);
// now, any remaining error checking based on the object itself
if (qualifier.hasAnyLocation()) {
switch (qualifier.storage) {
case EvqUniform:
case EvqBuffer:
if (symbol.getAsVariable() == 0)
error(loc, "can only be used on variable declaration", "location", "");
break;
default:
break;
}
}
// Check packing and matrix
if (qualifier.hasUniformLayout()) {
switch (qualifier.storage) {
case EvqUniform:
case EvqBuffer:
if (type.getBasicType() != EbtBlock) {
if (qualifier.hasMatrix())
error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
if (qualifier.hasPacking())
error(loc, "cannot specify packing on a variable declaration", "layout", "");
// "The offset qualifier can only be used on block members of blocks..."
if (qualifier.hasOffset() && type.getBasicType() != EbtAtomicUint)
error(loc, "cannot specify on a variable declaration", "offset", "");
// "The align qualifier can only be used on blocks or block members..."
if (qualifier.hasAlign())
error(loc, "cannot specify on a variable declaration", "align", "");
}
break;
default:
// these were already filtered by layoutTypeCheck() (or its callees)
break;
}
}
}
// Do layout error checking with respect to a type.
void TParseContext::layoutTypeCheck(TSourceLoc loc, const TType& type)
{
const TQualifier& qualifier = type.getQualifier();
// first, intra layout qualifier-only error checking
layoutQualifierCheck(loc, qualifier);
// now, error checking combining type and qualifier
if (qualifier.hasAnyLocation()) {
if (qualifier.hasLocation()) {
if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
error(loc, "too large for fragment output", "location", "");
}
}
if (qualifier.hasComponent()) {
// "It is a compile-time error if this sequence of components gets larger than 3."
if (qualifier.layoutComponent + type.getVectorSize() > 4)
error(loc, "type overflows the available 4 components", "component", "");
// "It is a compile-time error to apply the component qualifier to a matrix, a structure, a block, or an array containing any of these."
if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
error(loc, "cannot apply to a matrix, structure, or block", "component", "");
}
switch (qualifier.storage) {
case EvqVaryingIn:
case EvqVaryingOut:
if (type.getBasicType() == EbtBlock)
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, "location qualifier on in/out block");
break;
case EvqUniform:
case EvqBuffer:
break;
default:
error(loc, "can only appy to uniform, buffer, in, or out storage qualifiers", "location", "");
break;
}
bool typeCollision;
int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
if (repeated >= 0 && ! typeCollision)
error(loc, "overlapping use of location", "location", "%d", repeated);
// "fragment-shader outputs ... if two variables are placed within the same
// location, they must have the same underlying type (floating-point or integer)"
if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput())
error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated);
}
if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
int repeated = intermediate.addXfbBufferOffset(type);
if (repeated >= 0)
error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
// "The offset must be a multiple of the size of the first component of the first
// qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate
// containing a double, the offset must also be a multiple of 8..."
if (type.containsBasicType(EbtDouble) && ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
error(loc, "type contains double; xfb_offset must be a multiple of 8", "xfb_offset", "");
else if (! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
error(loc, "must be a multiple of size of first component", "xfb_offset", "");
}
if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
}
if (qualifier.hasBinding()) {
// Binding checking, from the spec:
//
// "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
// equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
// error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
// an array of size N, all elements of the array from binding through binding + N 1 must be within this
// range."
//
if (type.getBasicType() != EbtSampler && type.getBasicType() != EbtBlock && type.getBasicType() != EbtAtomicUint)
error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
if (type.getBasicType() == EbtSampler) {
int lastBinding = qualifier.layoutBinding;
if (type.isArray())
lastBinding += type.getArraySize();
if (lastBinding >= resources.maxCombinedTextureImageUnits)
error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
}
if (type.getBasicType() == EbtAtomicUint) {
if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
return;
}
}
}
// atomic_uint
if (type.getBasicType() == EbtAtomicUint) {
if (! type.getQualifier().hasBinding())
error(loc, "layout(binding=X) is required", "atomic_uint", "");
}
// "The offset qualifier can only be used on block members of blocks..."
if (qualifier.hasOffset()) {
if (type.getBasicType() == EbtBlock)
error(loc, "only applies to block members, not blocks", "offset", "");
}
// Image format
if (qualifier.hasFormat()) {
if (! type.isImage())
error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
else {
if (type.getSampler().type == EbtFloat && qualifier.layoutFormat > ElfFloatGuard)
error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
if (type.getSampler().type == EbtInt && (qualifier.layoutFormat < ElfFloatGuard || qualifier.layoutFormat > ElfIntGuard))
error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
if (type.getSampler().type == EbtUint && qualifier.layoutFormat < ElfIntGuard)
error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
if (profile == EEsProfile) {
// "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must
// specify either memory qualifier readonly or the memory qualifier writeonly."
if (! (qualifier.layoutFormat == ElfR32f || qualifier.layoutFormat == ElfR32i || qualifier.layoutFormat == ElfR32ui)) {
if (! qualifier.readonly && ! qualifier.writeonly)
error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
}
}
}
} else if (type.isImage() && ! qualifier.writeonly)
error(loc, "image variables not declared 'writeonly' must have a format layout qualifier", "", "");
}
// Do layout error checking that can be done within a layout qualifier proper, not needing to know
// if there are blocks, atomic counters, variables, etc.
void TParseContext::layoutQualifierCheck(TSourceLoc loc, const TQualifier& qualifier)
{
if (qualifier.storage == EvqShared && qualifier.hasLayout())
error(loc, "cannot apply layout qualifiers to a shared variable", "shared", "");
// "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
if (qualifier.hasComponent() && ! qualifier.hasLocation())
error(loc, "must specify 'location' to use 'component'", "component", "");
if (qualifier.hasAnyLocation()) {
// "As with input layout qualifiers, all shaders except compute shaders
// allow *location* layout qualifiers on output variable declarations,
// output block declarations, and output block member declarations."
switch (qualifier.storage) {
case EvqVaryingIn:
{
const char* feature = "location qualifier on input";
if (profile == EEsProfile && version < 310)
requireStage(loc, EShLangVertex, feature);
else
requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
if (language == EShLangVertex) {
const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
profileRequires(loc, EEsProfile, 300, nullptr, feature);
} else {
profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
profileRequires(loc, EEsProfile, 310, nullptr, feature);
}
break;
}
case EvqVaryingOut:
{
const char* feature = "location qualifier on output";
if (profile == EEsProfile && version < 310)
requireStage(loc, EShLangFragment, feature);
else
requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
if (language == EShLangFragment) {
const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
profileRequires(loc, EEsProfile, 300, nullptr, feature);
} else {
profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
profileRequires(loc, EEsProfile, 310, nullptr, feature);
}
break;
}
case EvqUniform:
case EvqBuffer:
{
const char* feature = "location qualifier on uniform or buffer";
requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature);
profileRequires(loc, EEsProfile, 310, nullptr, feature);
break;
}
default:
break;
}
if (qualifier.hasIndex()) {
if (qualifier.storage != EvqVaryingOut)
error(loc, "can only be used on an output", "index", "");
if (! qualifier.hasLocation())
error(loc, "can only be used with an explicit location", "index", "");
}
}
if (qualifier.hasBinding()) {
if (! qualifier.isUniformOrBuffer())
error(loc, "requires uniform or buffer storage qualifier", "binding", "");
}
if (qualifier.hasStream()) {
if (qualifier.storage != EvqVaryingOut)
error(loc, "can only be used on an output", "stream", "");
}
if (qualifier.hasXfb()) {
if (qualifier.storage != EvqVaryingOut)
error(loc, "can only be used on an output", "xfb layout qualifier", "");
}
if (qualifier.hasUniformLayout()) {
if (! qualifier.isUniformOrBuffer()) {
if (qualifier.hasMatrix() || qualifier.hasPacking())
error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
if (qualifier.hasOffset() || qualifier.hasAlign())
error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
}
}
}
// For places that can't have shader-level layout qualifiers
void TParseContext::checkNoShaderLayouts(TSourceLoc loc, const TShaderQualifiers& shaderQualifiers)
{
const char* message = "can only apply to a standalone qualifier";
if (shaderQualifiers.geometry != ElgNone)
error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
if (shaderQualifiers.invocations > 0)
error(loc, message, "invocations", "");
if (shaderQualifiers.vertices > 0) {
if (language == EShLangGeometry)
error(loc, message, "max_vertices", "");
else if (language == EShLangTessControl)
error(loc, message, "vertices", "");
else
assert(0);
}
for (int i = 0; i < 3; ++i) {
if (shaderQualifiers.localSize[i] > 1)
error(loc, message, "local_size", "");
}
}
// Correct and/or advance an object's offset layout qualifier.
void TParseContext::fixOffset(TSourceLoc loc, TSymbol& symbol)
{
const TQualifier& qualifier = symbol.getType().getQualifier();
if (symbol.getType().getBasicType() == EbtAtomicUint) {
if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
// Set the offset
int offset;
if (qualifier.hasOffset())
offset = qualifier.layoutOffset;
else
offset = atomicUintOffsets[qualifier.layoutBinding];
symbol.getWritableType().getQualifier().layoutOffset = offset;
// Check for overlap
int numOffsets = 4;
if (symbol.getType().isArray())
numOffsets *= symbol.getType().getArraySize();
int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
if (repeated >= 0)
error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
// Bump the default offset
atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
}
}
}
//
// Look up a function name in the symbol table, and make sure it is a function.
//
// Return the function symbol if found, otherwise 0.
//
const TFunction* TParseContext::findFunction(TSourceLoc loc, const TFunction& call, bool& builtIn)
{
const TFunction* function = 0;
if (symbolTable.isFunctionNameVariable(call.getName())) {
error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
return 0;
}
if (profile == EEsProfile || version < 120)
function = findFunctionExact(loc, call, builtIn);
else if (version < 400)
function = findFunction120(loc, call, builtIn);
else
function = findFunction400(loc, call, builtIn);
return function;
}
// Function finding algorithm for ES and desktop 110.
const TFunction* TParseContext::findFunctionExact(TSourceLoc loc, const TFunction& call, bool& builtIn)
{
TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
if (symbol == 0) {
error(loc, "no matching overloaded function found", call.getName().c_str(), "");
return 0;
}
return symbol->getAsFunction();
}
// Function finding algorithm for desktop versions 120 through 330.
const TFunction* TParseContext::findFunction120(TSourceLoc loc, const TFunction& call, bool& builtIn)
{
// first, look for an exact match
TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
if (symbol)
return symbol->getAsFunction();
// exact match not found, look through a list of overloaded functions of the same name
// "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
// on input parameters (in or inout or default) must have a conversion from the calling argument type to the
// formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
// from the formal parameter type to the calling argument type. When argument conversions are used to find
// a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
// more than one function."
const TFunction* candidate = 0;
TVector<TFunction*> candidateList;
symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
for (TVector<TFunction*>::const_iterator it = candidateList.begin(); it != candidateList.end(); ++it) {
const TFunction& function = *(*it);
// to even be a potential match, number of arguments has to match
if (call.getParamCount() != function.getParamCount())
continue;
bool possibleMatch = true;
for (int i = 0; i < function.getParamCount(); ++i) {
// same types is easy
if (*function[i].type == *call[i].type)
continue;
// We have a mismatch in type, see if it is implicitly convertible
if (function[i].type->isArray() || call[i].type->isArray() ||
! function[i].type->sameElementShape(*call[i].type))
possibleMatch = false;
else {
// do direction-specific checks for conversion of basic type
if (function[i].type->getQualifier().isParamInput()) {
if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
possibleMatch = false;
}
if (function[i].type->getQualifier().isParamOutput()) {
if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
possibleMatch = false;
}
}
if (! possibleMatch)
break;
}
if (possibleMatch) {
if (candidate) {
// our second match, meaning ambiguity
error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
} else
candidate = &function;
}
}
if (candidate == 0)
error(loc, "no matching overloaded function found", call.getName().c_str(), "");
return candidate;
}
// Function finding algorithm for desktop version 400 and above.
const TFunction* TParseContext::findFunction400(TSourceLoc loc, const TFunction& call, bool& builtIn)
{
// TODO: 4.00 functionality: findFunction400()
return findFunction120(loc, call, builtIn);
}
// When a declaration includes a type, but not a variable name, it can be
// to establish defaults.
void TParseContext::declareTypeDefaults(TSourceLoc loc, const TPublicType& publicType)
{
if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding() && publicType.qualifier.hasOffset()) {
if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
error(loc, "atomic_uint binding is too large", "binding", "");
return;
}
atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
return;
}
if (publicType.qualifier.hasLayout())
warn(loc, "useless application of layout qualifier", "layout", "");
}
//
// Do everything necessary to handle a variable (non-block) declaration.
// Either redeclaring a variable, or making a new one, updating the symbol
// table, and all error checking.
//
// Returns a subtree node that computes an initializer, if needed.
// Returns 0 if there is no code to execute for initialization.
//
TIntermNode* TParseContext::declareVariable(TSourceLoc loc, TString& identifier, const TPublicType& publicType, TArraySizes* arraySizes, TIntermTyped* initializer)
{
TType type(publicType);
if (voidErrorCheck(loc, identifier, type.getBasicType()))
return 0;
if (initializer)
rValueErrorCheck(loc, "initializer", initializer);
else
nonInitConstCheck(loc, identifier, type);
samplerCheck(loc, type, identifier);
atomicUintCheck(loc, type, identifier);
if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.layoutDepth != EldNone)
error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
// Check for redeclaration of built-ins and/or attempting to declare a reserved name
bool newDeclaration = false; // true if a new entry gets added to the symbol table
TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers, newDeclaration);
if (! symbol)
reservedErrorCheck(loc, identifier);
inheritGlobalDefaults(type.getQualifier());
// Declare the variable
if (arraySizes || type.isArray()) {
// Arrayness is potentially coming both from the type and from the
// variable: "int[] a[];" or just one or the other.
// For now, arrays of arrays aren't supported, so it's just one or the
// other. Move it to the type, so all arrayness is part of the type.
arrayDimCheck(loc, &type, arraySizes);
if (arraySizes)
type.setArraySizes(arraySizes);
arrayUnsizedCheck(loc, type.getQualifier(), type.getArraySize(), initializer != nullptr);
if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type))
declareArray(loc, identifier, type, symbol, newDeclaration);
if (initializer) {
profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "initializer");
profileRequires(loc, EEsProfile, 300, nullptr, "initializer");
}
} else {
// non-array case
if (! symbol)
symbol = declareNonArray(loc, identifier, type, newDeclaration);
else if (type != symbol->getType())
error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
}
if (! symbol)
return 0;
// Deal with initializer
TIntermNode* initNode = 0;
if (symbol && initializer) {
TVariable* variable = symbol->getAsVariable();
if (! variable) {
error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
return 0;
}
initNode = executeInitializer(loc, initializer, variable);
}
// look for errors in layout qualifier use
layoutObjectCheck(loc, *symbol);
fixOffset(loc, *symbol);
// see if it's a linker-level object to track
if (newDeclaration && symbolTable.atGlobalLevel())
intermediate.addSymbolLinkageNode(linkage, *symbol);
return initNode;
}
// Pick up global defaults from the provide global defaults into dst.
void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
{
if (dst.storage == EvqVaryingOut) {
if (! dst.hasStream() && language == EShLangGeometry)
dst.layoutStream = globalOutputDefaults.layoutStream;
if (! dst.hasXfbBuffer())
dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
}
}
//
// Make an internal-only variable whose name is for debug purposes only
// and won't be searched for. Callers will only use the return value to use
// the variable, not the name to look it up. It is okay if the name
// is the same as other names; there won't be any conflict.
//
TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
{
TString* nameString = new TString(name);
TVariable* variable = new TVariable(nameString, type);
symbolTable.makeInternalVariable(*variable);
return variable;
}
//
// Declare a non-array variable, the main point being there is no redeclaration
// for resizing allowed.
//
// Return the successfully declared variable.
//
TVariable* TParseContext::declareNonArray(TSourceLoc loc, TString& identifier, TType& type, bool& newDeclaration)
{
// make a new variable
TVariable* variable = new TVariable(&identifier, type);
ioArrayCheck(loc, type, identifier);
// add variable to symbol table
if (! symbolTable.insert(*variable)) {
error(loc, "redefinition", variable->getName().c_str(), "");
return 0;
} else {
newDeclaration = true;
return variable;
}
}
//
// Handle all types of initializers from the grammar.
//
// Returning 0 just means there is no code to execute to handle the
// initializer, which will, for example, be the case for constant initializers.
//
TIntermNode* TParseContext::executeInitializer(TSourceLoc loc, TIntermTyped* initializer, TVariable* variable)
{
//
// Identifier must be of type constant, a global, or a temporary, and
// starting at version 120, desktop allows uniforms to have initializers.
//
TStorageQualifier qualifier = variable->getType().getQualifier().storage;
if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
(qualifier == EvqUniform && profile != EEsProfile && version >= 120))) {
error(loc, " cannot initialize this type of qualifier ", variable->getType().getStorageQualifierString(), "");
return 0;
}
arrayObjectCheck(loc, variable->getType(), "array initializer");
//
// If the initializer was from braces { ... }, we convert the whole subtree to a
// constructor-style subtree, allowing the rest of the code to operate
// identically for both kinds of initializers.
//
initializer = convertInitializerList(loc, variable->getType(), initializer);
if (! initializer) {
// error recovery; don't leave const without constant values
if (qualifier == EvqConst)
variable->getWritableType().getQualifier().storage = EvqTemporary;
return 0;
}
// Fix arrayness if variable is unsized, getting size from the initializer
if (initializer->getType().isArray() && initializer->getType().isExplicitlySizedArray() &&
variable->getType().isImplicitlySizedArray())
variable->getWritableType().changeArraySize(initializer->getType().getArraySize());
// Uniform and global consts require a constant initializer
if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
variable->getWritableType().getQualifier().storage = EvqTemporary;
return 0;
}
if (qualifier == EvqConst && symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) {
error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
variable->getWritableType().getQualifier().storage = EvqTemporary;
return 0;
}
// Const variables require a constant initializer, depending on version
if (qualifier == EvqConst) {
if (initializer->getType().getQualifier().storage != EvqConst) {
const char* initFeature = "non-constant initializer";
requireProfile(loc, ~EEsProfile, initFeature);
profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, initFeature);
variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
qualifier = EvqConstReadOnly;
}
} else {
// Non-const global variables in ES need a const initializer.
//
// "In declarations of global variables with no storage qualifier or with a const
// qualifier any initializer must be a constant expression."
if (symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) {
const char* initFeature = "non-constant global initializer";
if (messages & EShMsgRelaxedErrors)
warn(loc, "not allowed in this version", initFeature, "");
else
requireProfile(loc, ~EEsProfile, initFeature);
}
}
if (qualifier == EvqConst || qualifier == EvqUniform) {
// Compile-time tagging of the variable with it's constant value...
initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
if (! initializer || ! initializer->getAsConstantUnion() || variable->getType() != initializer->getType()) {
error(loc, "non-matching or non-convertible constant type for const initializer",
variable->getType().getStorageQualifierString(), "");
variable->getWritableType().getQualifier().storage = EvqTemporary;
return 0;
}
variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
} else {
// normal assigning of a value to a variable...
TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
TIntermNode* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
if (! initNode)
assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
return initNode;
}
return 0;
}
//
// Reprocess any initializer-list { ... } parts of the initializer.
// Need to heirarchically assign correct types and implicit
// conversions. Will do this mimicking the same process used for
// creating a constructor-style initializer, ensuring we get the
// same form.
//
TIntermTyped* TParseContext::convertInitializerList(TSourceLoc loc, const TType& type, TIntermTyped* initializer)
{
// Will operate recursively. Once a subtree is found that is constructor style,
// everything below it is already good: Only the "top part" of the initializer
// can be an initializer list, where "top part" can extend for several (or all) levels.
// see if we have bottomed out in the tree within the initializer-list part
TIntermAggregate* initList = initializer->getAsAggregate();
if (! initList || initList->getOp() != EOpNull)
return initializer;
// Of the initializer-list set of nodes, need to process bottom up,
// so recurse deep, then process on the way up.
// Go down the tree here...
if (type.isArray()) {
// The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
// Later on, initializer execution code will deal with array size logic.
TType arrayType;
arrayType.shallowCopy(type);
arrayType.setArraySizes(type);
arrayType.changeArraySize((int)initList->getSequence().size());
TType elementType(arrayType, 0); // dereferenced type
for (size_t i = 0; i < initList->getSequence().size(); ++i) {
initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
if (initList->getSequence()[i] == 0)
return 0;
}
return addConstructor(loc, initList, arrayType, mapTypeToConstructorOp(arrayType));
} else if (type.isStruct()) {
if (type.getStruct()->size() != initList->getSequence().size()) {
error(loc, "wrong number of structure members", "initializer list", "");
return 0;
}
for (size_t i = 0; i < type.getStruct()->size(); ++i) {
initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
if (initList->getSequence()[i] == 0)
return 0;
}
} else if (type.isMatrix()) {
if (type.getMatrixCols() != (int)initList->getSequence().size()) {
error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
return 0;
}
TType vectorType(type, 0); // dereferenced type
for (int i = 0; i < type.getMatrixCols(); ++i) {
initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
if (initList->getSequence()[i] == 0)
return 0;
}
} else if (type.isVector()) {
if (type.getVectorSize() != (int)initList->getSequence().size()) {
error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
return 0;
}
} else {
error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
return 0;
}
// now that the subtree is processed, process this node
return addConstructor(loc, initList, type, mapTypeToConstructorOp(type));
}
//
// Test for the correctness of the parameters passed to various constructor functions
// and also convert them to the right data type, if allowed and required.
//
// Returns 0 for an error or the constructed node (aggregate or typed) for no error.
//
TIntermTyped* TParseContext::addConstructor(TSourceLoc loc, TIntermNode* node, const TType& type, TOperator op)
{
if (node == 0 || node->getAsTyped() == 0)
return 0;
rValueErrorCheck(loc, "constructor", node->getAsTyped());
TIntermAggregate* aggrNode = node->getAsAggregate();
TTypeList::const_iterator memberTypes;
if (op == EOpConstructStruct)
memberTypes = type.getStruct()->begin();
TType elementType;
elementType.shallowCopy(type);
if (type.isArray())
elementType.dereference();
bool singleArg;
if (aggrNode) {
if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1)
singleArg = true;
else
singleArg = false;
} else
singleArg = true;
TIntermTyped *newNode;
if (singleArg) {
// If structure constructor or array constructor is being called
// for only one parameter inside the structure, we need to call constructStruct function once.
if (type.isArray())
newNode = constructStruct(node, elementType, 1, node->getLoc());
else if (op == EOpConstructStruct)
newNode = constructStruct(node, *(*memberTypes).type, 1, node->getLoc());
else
newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
if (newNode && (type.isArray() || op == EOpConstructStruct))
newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
return newNode;
}
//
// Handle list of arguments.
//
TIntermSequence &sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
// if the structure constructor contains more than one parameter, then construct
// each parameter
int paramCount = 0; // keeps a track of the constructor parameter number being checked
// for each parameter to the constructor call, check to see if the right type is passed or convert them
// to the right type if possible (and allowed).
// for structure constructors, just check if the right type is passed, no conversion is allowed.
for (TIntermSequence::iterator p = sequenceVector.begin();
p != sequenceVector.end(); p++, paramCount++) {
if (type.isArray())
newNode = constructStruct(*p, elementType, paramCount+1, node->getLoc());
else if (op == EOpConstructStruct)
newNode = constructStruct(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
else
newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
if (newNode)
*p = newNode;
else
return 0;
}
TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
return constructor;
}
// Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
// for the parameter to the constructor (passed to this function). Essentially, it converts
// the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
// float, then float is converted to int.
//
// Returns 0 for an error or the constructed node.
//
TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, TSourceLoc loc, bool subset)
{
TIntermTyped* newNode;
TOperator basicOp;
//
// First, convert types as needed.
//
switch (op) {
case EOpConstructVec2:
case EOpConstructVec3:
case EOpConstructVec4:
case EOpConstructMat2x2:
case EOpConstructMat2x3:
case EOpConstructMat2x4:
case EOpConstructMat3x2:
case EOpConstructMat3x3:
case EOpConstructMat3x4:
case EOpConstructMat4x2:
case EOpConstructMat4x3:
case EOpConstructMat4x4:
case EOpConstructFloat:
basicOp = EOpConstructFloat;
break;
case EOpConstructDVec2:
case EOpConstructDVec3:
case EOpConstructDVec4:
case EOpConstructDMat2x2:
case EOpConstructDMat2x3:
case EOpConstructDMat2x4:
case EOpConstructDMat3x2:
case EOpConstructDMat3x3:
case EOpConstructDMat3x4:
case EOpConstructDMat4x2:
case EOpConstructDMat4x3:
case EOpConstructDMat4x4:
case EOpConstructDouble:
basicOp = EOpConstructDouble;
break;
case EOpConstructIVec2:
case EOpConstructIVec3:
case EOpConstructIVec4:
case EOpConstructInt:
basicOp = EOpConstructInt;
break;
case EOpConstructUVec2:
case EOpConstructUVec3:
case EOpConstructUVec4:
case EOpConstructUint:
basicOp = EOpConstructUint;
break;
case EOpConstructBVec2:
case EOpConstructBVec3:
case EOpConstructBVec4:
case EOpConstructBool:
basicOp = EOpConstructBool;
break;
default:
error(loc, "unsupported construction", "", "");
return 0;
}
newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
if (newNode == 0) {
error(loc, "can't convert", "constructor", "");
return 0;
}
//
// Now, if there still isn't an operation to do the construction, and we need one, add one.
//
// Otherwise, skip out early.
if (subset || (newNode != node && newNode->getType() == type))
return newNode;
// setAggregateOperator will insert a new node for the constructor, as needed.
return intermediate.setAggregateOperator(newNode, op, type, loc);
}
// This function tests for the type of the parameters to the structures constructors. Raises
// an error message if the expected type does not match the parameter passed to the constructor.
//
// Returns 0 for an error or the input node itself if the expected and the given parameter types match.
//
TIntermTyped* TParseContext::constructStruct(TIntermNode* node, const TType& type, int paramCount, TSourceLoc loc)
{
TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
if (! converted || converted->getType() != type) {
error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
return 0;
}
return converted;
}
//
// Do everything needed to add an interface block.
//
void TParseContext::declareBlock(TSourceLoc loc, TTypeList& typeList, const TString* instanceName, TArraySizes* arraySizes)
{
blockStageIoCheck(loc, currentBlockQualifier);
if (arraySizes)
arrayUnsizedCheck(loc, currentBlockQualifier, arraySizes->getSize(), false);
arrayDimCheck(loc, arraySizes, 0);
// fix and check for member storage qualifiers and types that don't belong within a block
for (unsigned int member = 0; member < typeList.size(); ++member) {
TType& memberType = *typeList[member].type;
TQualifier& memberQualifier = memberType.getQualifier();
TSourceLoc memberLoc = typeList[member].loc;
globalQualifierFixCheck(memberLoc, memberQualifier);
if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
memberQualifier.storage = currentBlockQualifier.storage;
if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
if (memberType.isRuntimeSizedArray() && member < typeList.size() - 1)
error(memberLoc, "only the last member of a buffer block can be run-time sized", memberType.getFieldName().c_str(), "");
if (memberType.isImplicitlySizedArray())
requireProfile(memberLoc, ~EEsProfile, "implicitly-sized array in a block");
if (memberQualifier.hasOffset()) {
requireProfile(memberLoc, ~EEsProfile, "offset on block member");
profileRequires(memberLoc, ~EEsProfile, 440, GL_ARB_enhanced_layouts, "offset on block member");
}
TBasicType basicType = memberType.getBasicType();
if (basicType == EbtSampler)
error(memberLoc, "member of block cannot be a sampler type", typeList[member].type->getFieldName().c_str(), "");
}
// This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will
// do all the rest.
if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
return;
}
// Not a redeclaration of a built-in; check that all names are user names.
reservedErrorCheck(loc, *blockName);
if (instanceName)
reservedErrorCheck(loc, *instanceName);
for (unsigned int member = 0; member < typeList.size(); ++member)
reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
// Make default block qualification, and adjust the member qualifications
TQualifier defaultQualification;
switch (currentBlockQualifier.storage) {
case EvqUniform: defaultQualification = globalUniformDefaults; break;
case EvqBuffer: defaultQualification = globalBufferDefaults; break;
case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
default: defaultQualification.clear(); break;
}
// fix and check for member layout qualifiers
mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true);
// "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
// "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
if (currentBlockQualifier.hasAlign() || currentBlockQualifier.hasAlign()) {
if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430) {
error(loc, "can only be used with std140 or std430 layout packing", "offset/align", "");
defaultQualification.layoutAlign = -1;
}
}
bool memberWithLocation = false;
bool memberWithoutLocation = false;
for (unsigned int member = 0; member < typeList.size(); ++member) {
TQualifier& memberQualifier = typeList[member].type->getQualifier();
TSourceLoc memberLoc = typeList[member].loc;
if (memberQualifier.hasStream()) {
if (defaultQualification.layoutStream != memberQualifier.layoutStream)
error(memberLoc, "member cannot contradict block", "stream", "");
}
// "This includes a block's inheritance of the
// current global default buffer, a block member's inheritance of the block's
// buffer, and the requirement that any *xfb_buffer* declared on a block
// member must match the buffer inherited from the block."
if (memberQualifier.hasXfbBuffer()) {
if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
}
if (memberQualifier.hasPacking())
error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
if (memberQualifier.hasLocation()) {
const char* feature = "location on block member";
switch (currentBlockQualifier.storage) {
case EvqVaryingIn:
case EvqVaryingOut:
requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature);
profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, feature);
profileRequires(memberLoc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature);
memberWithLocation = true;
break;
default:
error(memberLoc, "can only use in an in/out block", feature, "");
break;
}
} else
memberWithoutLocation = true;
if (memberQualifier.hasAlign()) {
if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430)
error(memberLoc, "can only be used with std140 or std430 layout packing", "align", "");
}
TQualifier newMemberQualification = defaultQualification;
mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
memberQualifier = newMemberQualification;
}
// Process the members
fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
fixBlockXfbOffsets(currentBlockQualifier, typeList);
fixBlockUniformOffsets(currentBlockQualifier, typeList);
for (unsigned int member = 0; member < typeList.size(); ++member)
layoutTypeCheck(typeList[member].loc, *typeList[member].type);
// reverse merge, so that currentBlockQualifier now has all layout information
// (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true);
//
// Build and add the interface block as a new type named 'blockName'
//
TType blockType(&typeList, *blockName, currentBlockQualifier);
if (arraySizes)
blockType.setArraySizes(arraySizes);
else
ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
//
// Don't make a user-defined type out of block name; that will cause an error
// if the same block name gets reused in a different interface.
//
// "Block names have no other use within a shader
// beyond interface matching; it is a compile-time error to use a block name at global scope for anything
// other than as a block name (e.g., use of a block name for a global variable name or function name is
// currently reserved)."
//
// Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
// whose type is EbtBlock, but without all the structure; that will come from the type
// the instances point to.
//
TType blockNameType(EbtBlock, blockType.getQualifier().storage);
TVariable* blockNameVar = new TVariable(blockName, blockNameType);
if (! symbolTable.insert(*blockNameVar)) {
TSymbol* existingName = symbolTable.find(*blockName);
if (existingName->getType().getBasicType() == EbtBlock) {
if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
return;
}
} else {
error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
return;
}
}
// Add the variable, as anonymous or named instanceName.
// Make an anonymous variable if no name was provided.
if (! instanceName)
instanceName = NewPoolTString("");
TVariable& variable = *new TVariable(instanceName, blockType);
if (! symbolTable.insert(variable)) {
if (*instanceName == "")
error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
else
error(loc, "block instance name redefinition", variable.getName().c_str(), "");
return;
}
// Check for general layout qualifier errors
layoutObjectCheck(loc, variable);
if (isIoResizeArray(blockType)) {
ioArraySymbolResizeList.push_back(&variable);
checkIoArraysConsistency(loc, true);
} else
fixIoArraySize(loc, variable.getWritableType());
// Save it in the AST for linker use.
intermediate.addSymbolLinkageNode(linkage, variable);
}
// Do all block-declaration checking regarding the combination of in/out/uniform/buffer
// with a particular stage.
void TParseContext::blockStageIoCheck(TSourceLoc loc, const TQualifier& qualifier)
{
switch (qualifier.storage) {
case EvqUniform:
profileRequires(loc, EEsProfile, 300, nullptr, "uniform block");
profileRequires(loc, ENoProfile, 140, nullptr, "uniform block");
if (currentBlockQualifier.layoutPacking == ElpStd430)
requireProfile(loc, ~EEsProfile, "std430 on a uniform block");
break;
case EvqBuffer:
requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, "buffer block");
profileRequires(loc, EEsProfile, 310, nullptr, "buffer block");
break;
case EvqVaryingIn:
profileRequires(loc, ~EEsProfile, 150, GL_ARB_separate_shader_objects, "input block");
// It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader
// "Compute shaders do not permit user-defined input variables..."
requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|EShLangFragmentMask), "input block");
if (language == EShLangFragment)
profileRequires(loc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block");
break;
case EvqVaryingOut:
profileRequires(loc, ~EEsProfile, 150, GL_ARB_separate_shader_objects, "output block");
requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask), "output block");
// ES 310 can have a block before shader_io is turned on, so skip this test for built-ins
if (language == EShLangVertex && ! parsingBuiltins)
profileRequires(loc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block");
break;
default:
error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
return;
}
}
//
// "For a block, this process applies to the entire block, or until the first member
// is reached that has a location layout qualifier. When a block member is declared with a location
// qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
// declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
// until the next member declared with a location qualifier. The values used for locations do not have to be
// declared in increasing order."
void TParseContext::fixBlockLocations(TSourceLoc loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
{
// "If a block has no block-level location layout qualifier, it is required that either all or none of its members
// have a location layout qualifier, or a compile-time error results."
if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
else {
if (memberWithLocation) {
// remove any block-level location and make it per *every* member
int nextLocation = 0; // by the rule above, initial value is not relevant
if (qualifier.hasAnyLocation()) {
nextLocation = qualifier.layoutLocation;
qualifier.layoutLocation = TQualifier::layoutLocationEnd;
if (qualifier.hasComponent()) {
// "It is a compile-time error to apply the *component* qualifier to a ... block"
error(loc, "cannot apply to a block", "component", "");
}
if (qualifier.hasIndex()) {
error(loc, "cannot apply to a block", "index", "");
}
}
for (unsigned int member = 0; member < typeList.size(); ++member) {
TQualifier& memberQualifier = typeList[member].type->getQualifier();
TSourceLoc memberLoc = typeList[member].loc;
if (! memberQualifier.hasLocation()) {
if (nextLocation >= TQualifier::layoutLocationEnd)
error(memberLoc, "location is too large", "location", "");
memberQualifier.layoutLocation = nextLocation;
memberQualifier.layoutComponent = 0;
}
nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type);
}
}
}
}
void TParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
{
// "If a block is qualified with xfb_offset, all its
// members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
// members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
// offsets."
if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
return;
int nextOffset = qualifier.layoutXfbOffset;
for (unsigned int member = 0; member < typeList.size(); ++member) {
TQualifier& memberQualifier = typeList[member].type->getQualifier();
bool containsDouble = false;
int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
// see if we need to auto-assign an offset to this member
if (! memberQualifier.hasXfbOffset()) {
// "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
if (containsDouble)
RoundToPow2(nextOffset, 8);
memberQualifier.layoutXfbOffset = nextOffset;
} else
nextOffset = memberQualifier.layoutXfbOffset;
nextOffset += memberSize;
}
// The above gave all block members an offset, so we can take it off the block now,
// which will avoid double counting the offset usage.
qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
}
// Calculate and save the offset of each block member, using the recursively
// defined block offset rules and the user-provided offset and align.
//
// Also, compute and save the total size of the block. For the block's size, arrayness
// is not taken into account, as each element is backed by a separate buffer.
//
void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList)
{
if (! qualifier.isUniformOrBuffer())
return;
if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
return;
int offset = 0;
int memberSize;
for (unsigned int member = 0; member < typeList.size(); ++member) {
TQualifier& memberQualifier = typeList[member].type->getQualifier();
TSourceLoc memberLoc = typeList[member].loc;
// "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, qualifier.layoutPacking == ElpStd140);
if (memberQualifier.hasOffset()) {
// "The specified offset must be a multiple
// of the base alignment of the type of the block member it qualifies, or a compile-time error results."
if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
// "It is a compile-time error to specify an offset that is smaller than the offset of the previous
// member in the block or that lies within the previous member of the block"
if (memberQualifier.layoutOffset < offset)
error(memberLoc, "cannot lie in previous members", "offset", "");
// "The offset qualifier forces the qualified member to start at or after the specified
// integral-constant expression, which will be its byte offset from the beginning of the buffer.
// "The actual offset of a member is computed as
// follows: If offset was declared, start with that offset, otherwise start with the next available offset."
offset = std::max(offset, memberQualifier.layoutOffset);
}
// "The actual alignment of a member will be the greater of the specified align alignment and the standard
// (e.g., std140) base alignment for the member's type."
if (memberQualifier.hasAlign())
memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
// "If the resulting offset is not a multiple of the actual alignment,
// increase it to the first offset that is a multiple of
// the actual alignment."
RoundToPow2(offset, memberAlignment);
typeList[member].type->getQualifier().layoutOffset = offset;
offset += memberSize;
}
}
// For an identifier that is already declared, add more qualification to it.
void TParseContext::addQualifierToExisting(TSourceLoc loc, TQualifier qualifier, const TString& identifier)
{
TSymbol* symbol = symbolTable.find(identifier);
if (! symbol) {
error(loc, "identifier not previously declared", identifier.c_str(), "");
return;
}
if (symbol->getAsFunction()) {
error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
return;
}
if (qualifier.isAuxiliary() ||
qualifier.isMemory() ||
qualifier.isInterpolation() ||
qualifier.hasLayout() ||
qualifier.storage != EvqTemporary ||
qualifier.precision != EpqNone) {
error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
return;
}
// For read-only built-ins, add a new symbol for holding the modified qualifier.
// This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
if (symbol->isReadOnly())
symbol = symbolTable.copyUp(symbol);
if (qualifier.invariant) {
if (intermediate.inIoAccessed(identifier))
error(loc, "cannot change qualification after use", "invariant", "");
symbol->getWritableType().getQualifier().invariant = true;
invariantCheck(loc, symbol->getType().getQualifier());
} else
warn(loc, "unknown requalification", "", "");
}
void TParseContext::addQualifierToExisting(TSourceLoc loc, TQualifier qualifier, TIdentifierList& identifiers)
{
for (unsigned int i = 0; i < identifiers.size(); ++i)
addQualifierToExisting(loc, qualifier, *identifiers[i]);
}
void TParseContext::invariantCheck(TSourceLoc loc, const TQualifier& qualifier)
{
if (! qualifier.invariant)
return;
bool pipeOut = qualifier.isPipeOutput();
bool pipeIn = qualifier.isPipeInput();
if (version >= 300 || (profile != EEsProfile && version >= 420)) {
if (! pipeOut)
error(loc, "can only apply to an output", "invariant", "");
} else {
if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", "");
}
}
//
// Updating default qualifier for the case of a declaration with just a qualifier,
// no type, block, or identifier.
//
void TParseContext::updateStandaloneQualifierDefaults(TSourceLoc loc, const TPublicType& publicType)
{
if (publicType.shaderQualifiers.vertices) {
assert(language == EShLangTessControl || language == EShLangGeometry);
const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
if (publicType.qualifier.storage != EvqVaryingOut)
error(loc, "can only apply to 'out'", id, "");
if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
error(loc, "cannot change previously set layout value", id, "");
if (language == EShLangTessControl)
checkIoArraysConsistency(loc);
}
if (publicType.shaderQualifiers.invocations) {
if (publicType.qualifier.storage != EvqVaryingIn)
error(loc, "can only apply to 'in'", "invocations", "");
if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
error(loc, "cannot change previously set layout value", "invocations", "");
}
if (publicType.shaderQualifiers.geometry != ElgNone) {
if (publicType.qualifier.storage == EvqVaryingIn) {
switch (publicType.shaderQualifiers.geometry) {
case ElgPoints:
case ElgLines:
case ElgLinesAdjacency:
case ElgTriangles:
case ElgTrianglesAdjacency:
case ElgQuads:
case ElgIsolines:
if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
if (language == EShLangGeometry)
checkIoArraysConsistency(loc);
} else
error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
break;
default:
error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
}
} else if (publicType.qualifier.storage == EvqVaryingOut) {
switch (publicType.shaderQualifiers.geometry) {
case ElgPoints:
case ElgLineStrip:
case ElgTriangleStrip:
if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
break;
default:
error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
}
} else
error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
}
if (publicType.shaderQualifiers.spacing != EvsNone) {
if (publicType.qualifier.storage == EvqVaryingIn) {
if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
} else
error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
}
if (publicType.shaderQualifiers.order != EvoNone) {
if (publicType.qualifier.storage == EvqVaryingIn) {
if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
} else
error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
}
if (publicType.shaderQualifiers.pointMode) {
if (publicType.qualifier.storage == EvqVaryingIn)
intermediate.setPointMode();
else
error(loc, "can only apply to 'in'", "point_mode", "");
}
for (int i = 0; i < 3; ++i) {
if (publicType.shaderQualifiers.localSize[i] > 1) {
if (publicType.qualifier.storage == EvqVaryingIn) {
if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
error(loc, "cannot change previously set size", "local_size", "");
else {
int max = 0;
switch (i) {
case 0: max = resources.maxComputeWorkGroupSizeX; break;
case 1: max = resources.maxComputeWorkGroupSizeY; break;
case 2: max = resources.maxComputeWorkGroupSizeZ; break;
default: break;
}
if (intermediate.getLocalSize(i) > (unsigned int)max)
error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
// Fix the existing constant gl_WorkGroupSize with this new information.
bool builtIn;
TSymbol* symbol = symbolTable.find("gl_WorkGroupSize", &builtIn);
if (builtIn)
makeEditable(symbol);
TVariable* workGroupSize = symbol->getAsVariable();
workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
}
} else
error(loc, "can only apply to 'in'", "local_size", "");
}
}
if (publicType.shaderQualifiers.earlyFragmentTests) {
if (publicType.qualifier.storage == EvqVaryingIn)
intermediate.setEarlyFragmentTests();
else
error(loc, "can only apply to 'in'", "early_fragment_tests", "");
}
const TQualifier& qualifier = publicType.qualifier;
if (qualifier.isAuxiliary() ||
qualifier.isMemory() ||
qualifier.isInterpolation() ||
qualifier.precision != EpqNone)
error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
// "The offset qualifier can only be used on block members of blocks..."
// "The align qualifier can only be used on blocks or block members..."
if (qualifier.hasOffset() ||
qualifier.hasAlign())
error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
layoutQualifierCheck(loc, qualifier);
switch (qualifier.storage) {
case EvqUniform:
if (qualifier.hasMatrix())
globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
if (qualifier.hasPacking())
globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
break;
case EvqBuffer:
if (qualifier.hasMatrix())
globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
if (qualifier.hasPacking())
globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
break;
case EvqVaryingIn:
break;
case EvqVaryingOut:
if (qualifier.hasStream())
globalOutputDefaults.layoutStream = qualifier.layoutStream;
if (qualifier.hasXfbBuffer())
globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
}
break;
default:
error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
return;
}
if (qualifier.hasBinding())
error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
if (qualifier.hasAnyLocation())
error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
if (qualifier.hasXfbOffset())
error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
}
//
// Take the sequence of statements that has been built up since the last case/default,
// put it on the list of top-level nodes for the current (inner-most) switch statement,
// and follow that by the case/default we are on now. (See switch topology comment on
// TIntermSwitch.)
//
void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
{
TIntermSequence* switchSequence = switchSequenceStack.back();
if (statements) {
if (switchSequence->size() == 0)
error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
statements->setOperator(EOpSequence);
switchSequence->push_back(statements);
}
if (branchNode) {
// check all previous cases for the same label (or both are 'default')
for (unsigned int s = 0; s < switchSequence->size(); ++s) {
TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
if (prevBranch) {
TIntermTyped* prevExpression = prevBranch->getExpression();
TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
if (prevExpression == 0 && newExpression == 0)
error(branchNode->getLoc(), "duplicate label", "default", "");
else if (prevExpression != 0 &&
newExpression != 0 &&
prevExpression->getAsConstantUnion() &&
newExpression->getAsConstantUnion() &&
prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
error(branchNode->getLoc(), "duplicated value", "case", "");
}
}
switchSequence->push_back(branchNode);
}
}
//
// Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
// into a switch node.
//
TIntermNode* TParseContext::addSwitch(TSourceLoc loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
{
profileRequires(loc, EEsProfile, 300, nullptr, "switch statements");
profileRequires(loc, ENoProfile, 130, nullptr, "switch statements");
wrapupSwitchSubsequence(lastStatements, nullptr);
if (expression == 0 ||
(expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
error(loc, "condition must be a scalar integer expression", "switch", "");
// If there is nothing to do, drop the switch but still execute the expression
TIntermSequence* switchSequence = switchSequenceStack.back();
if (switchSequence->size() == 0)
return expression;
if (lastStatements == 0)
warn(loc, "last case/default label not followed by statements", "switch", "");
TIntermAggregate* body = new TIntermAggregate(EOpSequence);
body->getSequence() = *switchSequenceStack.back();
body->setLoc(loc);
TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
switchNode->setLoc(loc);
return switchNode;
}
void TParseContext::notifyVersion(int line, int version, const char* type_string)
{
if (versionCallback) {
versionCallback(line, version, type_string);
}
}
void TParseContext::notifyErrorDirective(int line, const char* error_message)
{
if (errorCallback) {
errorCallback(line, error_message);
}
}
void TParseContext::notifyLineDirective(int line, bool has_source, int source)
{
if (lineCallback) {
lineCallback(line, has_source, source);
}
}
} // end namespace glslang
| mit |
jf198932/platform | isriding.Web/Controllers/Chart/UserChartController.cs | 4018 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Abp.Domain.Uow;
using Abp.Web.Models;
using isriding.School;
using isriding.User;
using isriding.Web.Extension.Fliter;
using isriding.Web.Models.Chart;
namespace isriding.Web.Controllers.Chart
{
public class UserChartController : Controller
{
private readonly IUserReadRepository _useRepository;
private readonly ISchoolReadRepository _schoolRepository;
public UserChartController(IUserReadRepository useRepository, ISchoolReadRepository schoolRepository)
{
_useRepository = useRepository;
_schoolRepository = schoolRepository;
}
// GET: UserChart
public ActionResult Index()
{
return RedirectToAction("UserChartBar");
}
[AdminLayout]
public ActionResult UserChartBar()
{
var model = new UserChartSearchModel();
PrepareUserChartModel(model);
return View(model);
}
[DontWrapResult, UnitOfWork]
public virtual ActionResult GetUserChartData(int School_id, int Year, int Month)
{
var user = _useRepository.GetAll();
if (School_id > 0)
{
user = user.Where(t => t.School_id == School_id);
}
else
{
var sessionschoolids = Session["SchoolIds"] as List<int>;
if (sessionschoolids != null && sessionschoolids.Count > 0)
{
user = user.Where(t => sessionschoolids.Contains((int)t.School_id));
}
}
var userlist = user.ToList();
var now = DateTime.Now;
List<string> months = new List<string>();
List<int> datars = new List<int>();
List<int> datacs = new List<int>();
if (Month > 0)
{
int days = DateTime.DaysInMonth(Year, Month);
for (int i = 1; i <= days; i++)
{
var time = new DateTime(Year, Month, i);
months.Add(time.ToString("MM-dd"));
datars.Add(userlist.Count(t => DateTime.Parse(t.Created_at.ToString()).ToString("yyyy/MM/dd") == time.ToString("yyyy/MM/dd")));
datacs.Add(userlist.Count(t => DateTime.Parse(t.Created_at.ToString()).ToString("yyyy/MM/dd") == time.ToString("yyyy/MM/dd") && t.Certification == 3));
}
}
else
{
for (int i = 1; i <= 12; i++)
{
var time = new DateTime(Year, i, 1);
months.Add(i + "月");
datars.Add(userlist.Count(t => DateTime.Parse(t.Created_at.ToString()).ToString("yyyy/MM") == time.ToString("yyyy/MM")));
datacs.Add(userlist.Count(t => DateTime.Parse(t.Created_at.ToString()).ToString("yyyy/MM") == time.ToString("yyyy/MM") && t.Certification == 3));
}
}
return Json(new { months = months, datars = datars, datacs = datacs}, JsonRequestBehavior.AllowGet);
}
[NonAction, UnitOfWork]
protected virtual void PrepareUserChartModel(UserChartSearchModel model)
{
if (model == null)
throw new ArgumentNullException("model");
var list = _schoolRepository.GetAll();
var sessionschoolids = Session["SchoolIds"] as List<int>;
if (sessionschoolids != null && sessionschoolids.Count > 0)
{
list = list.Where(t => sessionschoolids.Contains(t.Id));
}
var schoollist = list.Select(b => new SelectListItem { Text = b.Name, Value = b.Id.ToString() });
model.SchoolList.AddRange(schoollist);
model.SchoolList.Insert(0, new SelectListItem { Text = "---请选择---", Value = "0" });
}
}
} | mit |
wangjeaf/ckstyle-node | ckstyle/plugins/FED2DoNotSetStyleForTagOnly.js | 1183 | var base = require('../base');
var ERROR_LEVEL = base.ERROR_LEVEL;
var Class = base.Class;
var RuleSetChecker = base.RuleSetChecker;
var helper = require('./helper');
module.exports = global.FEDDoNotSetStyleForTagOnly = new Class(RuleSetChecker, function () {
this.__init__ = function (self) {
self.id = 'no-style-for-tag';
self.errorLevel = ERROR_LEVEL.ERROR;
self.errorMsg = 'should not set style for html tag in "${selector}"';
}
this.check = function (self, ruleSet, config) {
var selector = ruleSet.selector.toLowerCase();
if (selector.indexOf('@media') != -1)
return true;
if (selector.indexOf('@-moz-document') != -1)
return true;
var selectors = selector.split(',');
for (var i = 0, l = selectors.length; i < l; i++) {
var s = selectors[i].trim();
if (helper.isHTMLTag(s))
return false
}
return true
}
this.__doc__ = {
"summary":"不要为html tag设置样式",
"desc":"除了重置 CSS(如Reset.css) 的相关设置,其他代码一律不允许为html tag设置样式。"
}
})
| mit |
fschaefer/Probability.js | Probability.js | 1941 | /*
* Probability.js: Call JavaScript functions by probability.
*
* Copyright (c) 2012 Florian Schäfer ([email protected])
* Released under MIT license.
*
* Version: 0.0.1
*
*/
(function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.Probability = factory();
}
})(this, function () {
var toString = Object.prototype.toString,
slice = Array.prototype.slice;
function Probability() {
var i = 0,
l = 0,
probas = [],
functions = [],
sum = 0,
args = toString.call(arguments[0]) === '[object Array]' ? arguments[0] : slice.call(arguments);
args.push({
p: 0,
f: function () {}
});
for (i = 0, l = args.length; i < l; i++) {
var p = Math.abs(parseFloat(args[i].p)),
f = args[i].f;
if (isNaN(p) || typeof f !== 'function') {
throw new TypeError('Probability.js: Invalid probability object in argument ' + i + '.');
}
if (/%/.test(args[i].p)) {
p = p / 100.0;
}
sum += p;
if (sum > 1.0) {
throw new TypeError('Probability.js: Probability exceeds "1.0" (=100%) in argument ' + i + ': p="' + p + '" (=' + p * 100 + '%), sum="' + sum + '" (=' + sum * 100 + '%).');
}
probas[i] = sum;
functions[i] = f;
}
return function probabilitilized() {
var random = Math.random();
for (i = 0, l = probas.length - 1; i < l && random >= probas[i]; i++) {
/* intentionally left empty */
}
return functions[i].apply(this, arguments);
};
}
return Probability;
});
| mit |
linde002/gstandaard-bundle | Model/GsOngewensteGroepenQuery.php | 213 | <?php
namespace PharmaIntelligence\GstandaardBundle\Model;
use PharmaIntelligence\GstandaardBundle\Model\om\BaseGsOngewensteGroepenQuery;
class GsOngewensteGroepenQuery extends BaseGsOngewensteGroepenQuery
{
}
| mit |
rmfisher/fx-animation-editor | src/main/java/animator/component/property/color/ColorEditorComponent.java | 3266 | package animator.component.property.color;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import animator.component.property.color.picker.ColorPickerComponent;
import animator.component.property.control.InterpolatorButtonComponent;
import javax.inject.Inject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ColorEditorComponent {
private static final String FXML_NAME = "ColorEditorComponent.fxml";
private static final Color FX_ACCENT = Color.web("#0096C9");
private final ColorGraphic fillGraphic = new ColorGraphic();
private final ColorGraphic strokeGraphic = new ColorGraphic();
private final InterpolatorButtonComponent interpolatorButton = new InterpolatorButtonComponent();
private final List<ColorGraphic> standardColors = new ArrayList<>();
private final ColorEditorPresenter presenter;
private final ColorPickerComponent colorPicker;
@FXML
private VBox root;
@FXML
private HBox indicatorBox;
@FXML
private Label fillButton;
@FXML
private Label strokeButton;
@FXML
private HBox standardColorsBox;
@Inject
public ColorEditorComponent(ColorEditorPresenter presenter, ColorPickerComponent colorPicker) {
this.presenter = presenter;
this.colorPicker = colorPicker;
loadFxml();
initUi();
initPresenter();
}
public Region getRoot() {
return root;
}
public InterpolatorButtonComponent getInterpolatorButton() {
return interpolatorButton;
}
public ColorEditorModel getModel() {
return presenter.getModel();
}
Label getFillButton() {
return fillButton;
}
Label getStrokeButton() {
return strokeButton;
}
ColorGraphic getFillGraphic() {
return fillGraphic;
}
ColorGraphic getStrokeGraphic() {
return strokeGraphic;
}
ColorPickerComponent getColorPicker() {
return colorPicker;
}
List<ColorGraphic> getStandardColors() {
return standardColors;
}
private void loadFxml() {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(FXML_NAME));
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException ignored) {
}
}
private void initUi() {
fillButton.setGraphic(fillGraphic.getRoot());
strokeButton.setGraphic(strokeGraphic.getRoot());
indicatorBox.getChildren().add(interpolatorButton);
root.getChildren().add(1, colorPicker.getRoot());
addStandardColor(null, true);
addStandardColor(Color.BLACK, false);
addStandardColor(Color.WHITE, true);
addStandardColor(FX_ACCENT, false);
}
private void addStandardColor(Color color, boolean showBorder) {
ColorGraphic graphic = new ColorGraphic(color, showBorder);
standardColors.add(graphic);
standardColorsBox.getChildren().add(graphic.getRoot());
}
private void initPresenter() {
presenter.setView(this);
}
}
| mit |
killvung/fb-front | src/app/mock-heroes.ts | 842 | import { Hero } from './hero';
export const HEROES: Hero[] = [
{ id: 11, name: 'Mr. Nsice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' },
{ id: 11, name: 'Mr. Nsice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
];
// Stress test
// var heroes:Array<Hero> = [{id:0, name:'asd'}];
// for(var i = 1; i < 100000; i++){
// heroes.push({id:i, name:'hero' + i});
// }
// export const HEROES = heroes
| mit |
uxcore/uxcore | lib/Splitter/style.js | 396 | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
return _style.default;
}
});
var _style = _interopRequireDefault(require("uxcore-splitter/style"));
module.exports = exports.default; | mit |
ruby/rubyspec | library/socket/ancillarydata/cmsg_is_spec.rb | 1045 | require_relative '../spec_helper'
with_feature :ancillary_data do
describe 'Socket::AncillaryData#cmsg_is?' do
describe 'using :INET, :IP, :TTL as the family, level, and type' do
before do
@data = Socket::AncillaryData.new(:INET, :IP, :TTL, '')
end
it 'returns true when comparing with IPPROTO_IP and IP_TTL' do
@data.cmsg_is?(Socket::IPPROTO_IP, Socket::IP_TTL).should == true
end
it 'returns true when comparing with :IP and :TTL' do
@data.cmsg_is?(:IP, :TTL).should == true
end
with_feature :pktinfo do
it 'returns false when comparing with :IP and :PKTINFO' do
@data.cmsg_is?(:IP, :PKTINFO).should == false
end
end
it 'returns false when comparing with :SOCKET and :RIGHTS' do
@data.cmsg_is?(:SOCKET, :RIGHTS).should == false
end
it 'raises SocketError when comparing with :IPV6 and :RIGHTS' do
lambda { @data.cmsg_is?(:IPV6, :RIGHTS) }.should raise_error(SocketError)
end
end
end
end
| mit |
jimmy-loyola/Chess | ChessApp/SquareView.cpp | 796 | #include "stdafx.h"
#include "SquareView.h"
SquareView::SquareView(Square* sqr)
: CRect()
{
square = sqr;
}
SquareView::~SquareView()
{
}
void SquareView::setRGB(Square::Color c)
{
switch (c)
{
case Square::BLACK:
colorRef = RGB_BLACK;
break;
case Square::WHITE:
colorRef = RGB_WHITE;
break;
case Square::CLICKED:
colorRef = RGB_CLICKED;
break;
case Square::KILL:
colorRef = RGB_KILL;
break;
case Square::ACTIVE:
colorRef = (square->getOriginalColor() == Square::WHITE)
? RGB_ACTIVE_WHITE : RGB_ACTIVE_BLACK;
break;
}
}
void SquareView::setRGB()
{
setRGB(square->getColor());
}
COLORREF SquareView::getRGB() const
{
return colorRef;
}
CRect SquareView::getRect() const
{
return static_cast<CRect>(this);
}
/*** EOF ***/ | mit |
mattbalmer/mb-strings | dist/mb-strings.min.js | 584 | /*
* mb-strings v0.2.1
* Provides helper functions related to the String object.
* (c) 2014 Matt Balmer <[email protected]> http://mattbalmer.com
* License: MIT
*/
!function(){var a=function(a){var b=Array.prototype.slice.call(arguments,1);if("object"==typeof b[0]){var c=b[0];return a.replace(/{(.+?)}/g,function(a,b){return"undefined"==typeof c[b]?a:c[b]})}return a.replace(/{(\d+)}/g,function(a,c){return"undefined"!=typeof b[c]?b[c]:a})};"undefined"!=typeof module&&"undefined"!=typeof module.exports?module.exports=a:(window.mb=window.mb||{},window.mb.formatString=a)}(); | mit |
bryanemanuel/Codetrotters | Day 8/users.js | 919 | var express = require('express');
var router = express.Router();
const {User} = require("../models");
/* GET users listing. */
router.get('/', function(req, res, next) {
User.findAll().then((users) => {
res.render("users_list", { data: users});
});
});
router.post('/create', function(req, res, next) {
const {name, last} = req.body;
User.create({firstName: name, lastName: last}).then((user) => {
res.render("users_details", {data: user});
});
});
router.get('/create', function(req, res, next) {
res.render("users_create");
});
router.post('/edit', function(req, res, next) {
const {name, last} = req.body;
User.edit({firstName: name, lastName: last}).then((user) => {
res.render("users_details", {data: user});
});
});
router.get('/:id', function(req, res, next) {
console.log(User.users);
res.render("users_details", {
data: User[`/:id`],
});
});
module.exports = router;
| mit |
guon/pole-mock | test/scripts/test_ajax.js | 523 | define(['ajax'], function(ajax) {
return function() {
module('Test Ajax');
asyncTest('ajax getJSON', function() {
ajax.getJSON('data/mock-config.json', function(response) {
ok(response, '使用AJAX获取json数据');
start();
});
});
asyncTest('ajax getScript', function() {
ajax.getScript('data/getscript.jsonp');
});
};
});
function callback1(response) {
ok(response, 'test JSONP');
start();
}; | mit |
osorubeki-fujita/odpt_tokyo_metro | lib/tokyo_metro/required/all/factory/convert/customize/api/station_facility.rb | 110 | class TokyoMetro::Required::All::Factory::Convert::Customize::Api::StationFacility < TokyoMetro::Required
end
| mit |
atupal/oj | urioj/contests/36/b.cpp | 646 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int maxn = 1100;
int vis[maxn];
int a[maxn];
int b[maxn];
int m, k;
void solve() {
int cnt = 0;
int ans = 0;
memset(vis, 0, sizeof(vis));
for (int i = 0; i < k; ++ i) {
ans += a[ b[i] ];
if (!vis[b[i]]) {
vis[b[i]] = 1;
cnt++;
if (cnt == m) {
printf("%d\n", ans);
return;
}
}
}
printf("-1\n");
}
int main() {
while (scanf("%d %d", &m, &k) != EOF) {
for (int i = 1; i <= m; ++ i) {
scanf("%d", a+i);
}
for (int i = 0; i < k; ++ i) {
scanf("%d", b+i);
}
solve();
}
return 0;
}
| mit |
jagrutkosti/plagUI | src/main/webapp/app/blocks/config/uib-pagination.config.js | 631 | (function() {
'use strict';
angular
.module('plagUiApp')
.config(paginationConfig);
paginationConfig.$inject = ['uibPaginationConfig', 'paginationConstants'];
function paginationConfig(uibPaginationConfig, paginationConstants) {
uibPaginationConfig.itemsPerPage = paginationConstants.itemsPerPage;
uibPaginationConfig.maxSize = 5;
uibPaginationConfig.boundaryLinks = true;
uibPaginationConfig.firstText = '«';
uibPaginationConfig.previousText = '‹';
uibPaginationConfig.nextText = '›';
uibPaginationConfig.lastText = '»';
}
})();
| mit |
branscha/lib-scripty | src/test/java/branscha/scripty/spec/map/ArrayIndexMappingTest.java | 2299 | /* ******************************************************************************
* The MIT License
* Copyright (c) 2012 Bruno Ranschaert
* lib-scripty
*
* 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.
******************************************************************************/
package branscha.scripty.spec.map;
import org.junit.Test;
import static junit.framework.TestCase.fail;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
public class ArrayIndexMappingTest {
@Test
public void map_Good()
throws ArgMappingException {
final Object[] args = {0, 1, 2, 3, 4, 5};
for (int i = 0; i < args.length; i++) {
ArgMapping aim = new ArrayIndexMapping(i);
assertEquals(i, aim.map(null, null, args));
}
}
@Test
public void map_Bad() {
final Object[] args = {0, 1, 2, 3, 4, 5};
ArgMapping aim = new ArrayIndexMapping(100);
try {
aim.map(null, null, args);
fail("Mapper should have failed.");
}
catch (ArgMappingException e) {
assertThat(e.getMessage(), containsString("ArrayIndexMapping/010"));
}
}
} | mit |
sdmccoy/portfolio | src/lib/projects.js | 3457 | import * as devIcon from './dev-icons.js';
import musicMonkeyPhoto from '../../assets/project-photo-musicmonkey-medium.png';
import eSkatePhoto from '../../assets/project-photo-eskate-medium.png';
import yaketyakPhoto from '../../assets/project-photo-yaketyak-medium.png';
export const projects = [
{
name: 'Yaketyak',
photo: yaketyakPhoto,
websiteURL: 'http://yaketyak.com/',
description: 'Yaketyak was created within a two week solo sprint for a client to gain proof of concept of the Sendbird Chat API capabilities. Scope for MVP was discussed which included Create, Read, Update, and Destroy operations on profiles, chat channels, and individual messages. The client required the stack to match their in-house languages, frameworks, and libraries. This included React for the interface, Redux for state management, Material UI and Sass for style, and Webpack for compiling. Additionally, the client requested a user navigation tracking system, with the tool being up to my discretion, to be implemented and stored in state. We met, virtually, twice a week for status updates and new features or changes.',
featureOne: 'React-Tracking library implemented for user navigation and event tracking.',
featureTwo: 'Redux utilized to manage the state of the application.',
featureThree: 'Material UI was implemented to mimick the client\'s branding.',
devIcons: [devIcon.reactIcon, devIcon.reduxIcon, devIcon.materialIcon, devIcon.sassIcon, devIcon.webpackIcon],
},
{
name: 'E-Skate',
photo: eSkatePhoto,
websiteURL: 'http://e-skate.tech/',
description: 'E-Skate is an eCommerce site built to expand the clients customer reach and share. I provided the client with a separate admin interface, upon authorization, to control their inventory with create, update, or delete operations on their products. Since the client is in their beginning growth stage, I implemented the ability to change their store logo, contact information, and social media in case any rebranding takes place during their growth.',
featureOne: 'Full-Stack application with admin interface allowing CRUD operations on items and store settings.',
featureTwo: 'Image assets stored in AWS S3 while all other data stored in mLab using mongoDB.',
featureThree: 'Redux utilized for app state management for shopping cart and admin authorization.',
devIcons: [devIcon.nodeIcon, devIcon.reactIcon, devIcon.sassIcon, devIcon.mongoDBIcon, devIcon.webpackIcon],
},
{
name: 'Music Monkey',
photo: musicMonkeyPhoto,
websiteURL: 'http://musicmonkey.rocks/',
description: 'Music Monkey simplifies the process for music lovers to narrow down their search for concert events they would like to attend. Based on the users input of location and time range, Sparkle Monkey will plot the events on a Google map that is easily navigated. If maps aren\'t your jam, pun intended, click on the list view for easy scrolling. Both interfaces allow the user to click through to purchase tickets at the 3rd party vendor.',
featureOne: 'Full-Stack application using the Ticketmaster API for event resources.',
featureTwo: 'Utilized Google Maps & Spiderfy API\'s to plot the data for easy viewing.',
featureThree: 'Accessibility integrations include multiple map color modes and Chrome Vox dication.',
devIcons: [devIcon.JSIcon, devIcon.nodeIcon, devIcon.jQueryIcon, devIcon.HTML5Icon, devIcon.CSS3Icon],
},
];
| mit |
php-coveralls/php-coveralls | tests/Bundle/CoverallsBundle/Api/JobsTest.php | 18332 | <?php
namespace PhpCoveralls\Tests\Bundle\CoverallsBundle\Api;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use PhpCoveralls\Bundle\CoverallsBundle\Api\Jobs;
use PhpCoveralls\Bundle\CoverallsBundle\Collector\CiEnvVarsCollector;
use PhpCoveralls\Bundle\CoverallsBundle\Collector\CloverXmlCoverageCollector;
use PhpCoveralls\Bundle\CoverallsBundle\Config\Configuration;
use PhpCoveralls\Bundle\CoverallsBundle\Entity\JsonFile;
use PhpCoveralls\Tests\ProjectTestCase;
/**
* @covers \PhpCoveralls\Bundle\CoverallsBundle\Api\Jobs
* @covers \PhpCoveralls\Bundle\CoverallsBundle\Api\CoverallsApi
*
* @author Kitamura Satoshi <[email protected]>
*/
class JobsTest extends ProjectTestCase
{
// getJsonFile()
/**
* @test
*/
public function shouldNotHaveJsonFileOnConstruction()
{
$object = $this->createJobsNeverSendOnDryRun();
$this->assertNull($object->getJsonFile());
}
// setJsonFile()
/**
* @test
*/
public function shouldSetJsonFile()
{
$jsonFile = $this->collectJsonFile();
$object = $this->createJobsNeverSendOnDryRun()->setJsonFile($jsonFile);
$this->assertSame($jsonFile, $object->getJsonFile());
}
// getConfiguration()
/**
* @test
*/
public function shouldReturnConfiguration()
{
$config = $this->createConfiguration();
$object = new Jobs($config);
$this->assertSame($config, $object->getConfiguration());
}
// getHttpClient()
/**
* @test
*/
public function shouldNotHaveHttpClientOnConstructionWithoutHttpClient()
{
$config = $this->createConfiguration();
$object = new Jobs($config);
$this->assertNull($object->getHttpClient());
}
/**
* @test
*/
public function shouldHaveHttpClientOnConstructionWithHttpClient()
{
$config = $this->createConfiguration();
$client = $this->createAdapterMockNeverCalled();
$object = new Jobs($config, $client);
$this->assertSame($client, $object->getHttpClient());
}
// setHttpClient()
/**
* @test
*/
public function shouldSetHttpClient()
{
$config = $this->createConfiguration();
$client = $this->createAdapterMockNeverCalled();
$object = new Jobs($config);
$object->setHttpClient($client);
$this->assertSame($client, $object->getHttpClient());
}
// collectCloverXml()
/**
* @test
*/
public function shouldCollectCloverXml()
{
$this->makeProjectDir(null, $this->logsDir);
$xml = $this->getCloverXml();
file_put_contents($this->cloverXmlPath, $xml);
$config = $this->createConfiguration();
$object = new Jobs($config);
$same = $object->collectCloverXml();
// return $this
$this->assertSame($same, $object);
return $object;
}
/**
* @test
* @depends shouldCollectCloverXml
*
* @param Jobs $object
*
* @return JsonFile
*/
public function shouldHaveJsonFileAfterCollectCloverXml(Jobs $object)
{
$jsonFile = $object->getJsonFile();
$this->assertNotNull($jsonFile);
$sourceFiles = $jsonFile->getSourceFiles();
$this->assertCount(4, $sourceFiles);
return $jsonFile;
}
/**
* @test
* @depends shouldHaveJsonFileAfterCollectCloverXml
*
* @param JsonFile $jsonFile
*/
public function shouldNotHaveGitAfterCollectCloverXml(JsonFile $jsonFile)
{
$git = $jsonFile->getGit();
$this->assertNull($git);
}
/**
* @test
*/
public function shouldCollectCloverXmlExcludingNoStatementsFiles()
{
$this->makeProjectDir(null, $this->logsDir);
$xml = $this->getCloverXml();
file_put_contents($this->cloverXmlPath, $xml);
$config = $this->createConfiguration()->setExcludeNoStatements(true);
$object = new Jobs($config);
$same = $object->collectCloverXml();
// return $this
$this->assertSame($same, $object);
return $object;
}
/**
* @test
* @depends shouldCollectCloverXmlExcludingNoStatementsFiles
*
* @param Jobs $object
*
* @return JsonFile
*/
public function shouldHaveJsonFileAfterCollectCloverXmlExcludingNoStatementsFiles(Jobs $object)
{
$jsonFile = $object->getJsonFile();
$this->assertNotNull($jsonFile);
$sourceFiles = $jsonFile->getSourceFiles();
$this->assertCount(2, $sourceFiles);
return $jsonFile;
}
// collectGitInfo()
/**
* @test
* @depends shouldCollectCloverXml
*
* @param Jobs $object
*
* @return Jobs
*/
public function shouldCollectGitInfo(Jobs $object)
{
$same = $object->collectGitInfo();
// return $this
$this->assertSame($same, $object);
return $object;
}
/**
* @test
* @depends shouldCollectGitInfo
*
* @param Jobs $object
*
* @return JsonFile
*/
public function shouldHaveJsonFileAfterCollectGitInfo(Jobs $object)
{
$jsonFile = $object->getJsonFile();
$this->assertNotNull($jsonFile);
return $jsonFile;
}
/**
* @test
* @depends shouldHaveJsonFileAfterCollectGitInfo
*
* @param JsonFile $jsonFile
*/
public function shouldHaveGitAfterCollectGitInfo(JsonFile $jsonFile)
{
$git = $jsonFile->getGit();
$this->assertNotNull($git);
}
// send()
/**
* @test
*/
public function shouldSendTravisCiJob()
{
$this->makeProjectDir(null, $this->logsDir);
$serviceJobId = '1.1';
$server = [];
$server['TRAVIS'] = true;
$server['TRAVIS_BUILD_NUMBER'] = '654321';
$server['TRAVIS_JOB_ID'] = $serviceJobId;
$object = $this->createJobsWith();
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function shouldSendTravisProJob()
{
$this->makeProjectDir(null, $this->logsDir);
$serviceName = 'travis-pro';
$serviceJobId = '1.1';
$repoToken = 'your_token';
$server = [];
$server['TRAVIS'] = true;
$server['TRAVIS_BUILD_NUMBER'] = '8888';
$server['TRAVIS_JOB_ID'] = $serviceJobId;
$server['COVERALLS_REPO_TOKEN'] = $repoToken;
$object = $this->createJobsWith();
$object->getConfiguration()->setServiceName($serviceName);
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
$this->assertSame($serviceName, $jsonFile->getServiceName());
$this->assertSame($serviceJobId, $jsonFile->getServiceJobId());
$this->assertSame($repoToken, $jsonFile->getRepoToken());
}
/**
* @test
*/
public function shouldSendCircleCiJob()
{
$this->makeProjectDir(null, $this->logsDir);
$serviceNumber = '123';
$repoToken = 'token';
$server = [];
$server['COVERALLS_REPO_TOKEN'] = $repoToken;
$server['CIRCLECI'] = 'true';
$server['CIRCLE_WORKFLOW_ID'] = $serviceNumber;
$object = $this->createJobsWith();
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function shouldSendJenkinsJob()
{
$this->makeProjectDir(null, $this->logsDir);
$serviceNumber = '123';
$repoToken = 'token';
$server = [];
$server['COVERALLS_REPO_TOKEN'] = $repoToken;
$server['JENKINS_URL'] = 'http://localhost:8080';
$server['BUILD_NUMBER'] = $serviceNumber;
$object = $this->createJobsWith();
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function shouldSendLocalJob()
{
$this->makeProjectDir(null, $this->logsDir);
$server = [];
$server['COVERALLS_RUN_LOCALLY'] = '1';
$object = $this->createJobsWith();
$object->getConfiguration()->setRepoToken('token');
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function shouldSendUnsupportedJob()
{
$this->makeProjectDir(null, $this->logsDir);
$server = [];
$server['COVERALLS_REPO_TOKEN'] = 'token';
$object = $this->createJobsWith();
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function shouldSendUnsupportedGitJob()
{
$this->makeProjectDir(null, $this->logsDir);
$server = [];
$server['COVERALLS_REPO_TOKEN'] = 'token';
$server['GIT_COMMIT'] = 'abc123';
$object = $this->createJobsWith();
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function shouldNotSendJobIfTestEnv()
{
$this->makeProjectDir(null, $this->logsDir);
$server = [];
$server['TRAVIS'] = true;
$server['TRAVIS_BUILD_NUMBER'] = '198765';
$server['TRAVIS_JOB_ID'] = '1.1';
$object = $this->createJobsNeverSendOnDryRun();
$object->getConfiguration()->setEnv('test');
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function throwRuntimeExceptionIfInvalidEnv()
{
$this->expectException(\RuntimeException::class);
$server = [];
$object = $this->createJobsNeverSend();
$jsonFile = $this->collectJsonFile();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
/**
* @test
*/
public function throwRuntimeExceptionIfNoSourceFiles()
{
$this->expectException(\RuntimeException::class);
$server = [];
$server['TRAVIS'] = true;
$server['TRAVIS_BUILD_NUMBER'] = '12345';
$server['TRAVIS_JOB_ID'] = '1.1';
$server['GIT_COMMIT'] = 'abc123';
$object = $this->createJobsNeverSend();
$jsonFile = $this->collectJsonFileWithoutSourceFiles();
$object
->setJsonFile($jsonFile)
->collectEnvVars($server)
->dumpJsonFile()
->send();
}
protected function legacySetUp()
{
$this->setUpDir(realpath(__DIR__ . '/../../..'));
}
protected function legacyTearDown()
{
$this->rmFile($this->jsonPath);
$this->rmFile($this->cloverXmlPath);
$this->rmDir($this->logsDir);
$this->rmDir($this->buildDir);
}
/**
* @return Jobs
*/
protected function createJobsWith()
{
$config = new Configuration();
$config
->setEntryPoint('https://coveralls.io')
->setJsonPath($this->jsonPath)
->setDryRun(false);
$client = $this->createAdapterMockWith($this->url, $this->filename);
return new Jobs($config, $client);
}
/**
* @return Jobs
*/
protected function createJobsNeverSend()
{
$config = new Configuration();
$config
->setEntryPoint('https://coveralls.io')
->setJsonPath($this->jsonPath)
->setDryRun(false);
$client = $this->createAdapterMockNeverCalled();
return new Jobs($config, $client);
}
/**
* @return Jobs
*/
protected function createJobsNeverSendOnDryRun()
{
$config = new Configuration();
$config
->setEntryPoint('https://coveralls.io')
->setJsonPath($this->jsonPath)
->setDryRun(true);
$client = $this->createAdapterMockNeverCalled();
return new Jobs($config, $client);
}
/**
* @return Client
*/
protected function createAdapterMockNeverCalled()
{
$client = $this->prophesize(Client::class);
$client
->send()
->shouldNotBeCalled();
return $client->reveal();
}
/**
* @param string $url
* @param string $filename
*
* @return Client
*/
protected function createAdapterMockWith($url, $filename)
{
$response = $this->prophesize(Psr7\Response::class);
$response->reveal();
$client = $this->prophesize(Client::class);
$client
->post($url, \Prophecy\Argument::that(function ($options) use ($filename) {
return !empty($options['multipart'][0]['name'])
&& !empty($options['multipart'][0]['contents'])
&& $filename === $options['multipart'][0]['name']
&& is_string($options['multipart'][0]['contents']);
}))
->willReturn($response)
->shouldBeCalled();
return $client->reveal();
}
/**
* @return Configuration
*/
protected function createConfiguration()
{
$config = new Configuration();
return $config->addCloverXmlPath($this->cloverXmlPath);
}
/**
* @return string
*/
protected function getCloverXml()
{
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<coverage generated="1365848893">
<project timestamp="1365848893">
<file name="%s/test.php">
<class name="TestFile" namespace="global">
<metrics methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="1" coveredstatements="0" elements="2" coveredelements="0"/>
</class>
<line num="5" type="method" name="__construct" crap="1" count="0"/>
<line num="7" type="stmt" count="0"/>
</file>
<file name="%s/TestInterface.php">
<class name="TestInterface" namespace="global">
<metrics methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="1" coveredelements="0"/>
</class>
<line num="5" type="method" name="hello" crap="1" count="0"/>
</file>
<file name="%s/AbstractClass.php">
<class name="AbstractClass" namespace="global">
<metrics methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="0" coveredstatements="0" elements="1" coveredelements="0"/>
</class>
<line num="5" type="method" name="hello" crap="1" count="0"/>
</file>
<file name="dummy.php">
<class name="TestFile" namespace="global">
<metrics methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="1" coveredstatements="0" elements="2" coveredelements="0"/>
</class>
<line num="5" type="method" name="__construct" crap="1" count="0"/>
<line num="7" type="stmt" count="0"/>
</file>
<package name="Hoge">
<file name="%s/test2.php">
<class name="TestFile" namespace="Hoge">
<metrics methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="1" coveredstatements="0" elements="2" coveredelements="0"/>
</class>
<line num="6" type="method" name="__construct" crap="1" count="0"/>
<line num="8" type="stmt" count="0"/>
</file>
</package>
</project>
</coverage>
XML;
return sprintf($xml, $this->srcDir, $this->srcDir, $this->srcDir, $this->srcDir);
}
/**
* @return \SimpleXMLElement
*/
protected function createCloverXml()
{
$xml = $this->getCloverXml();
return simplexml_load_string($xml);
}
/**
* @return string
*/
protected function getNoSourceCloverXml()
{
return <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<coverage generated="1365848893">
<project timestamp="1365848893">
<file name="dummy.php">
<class name="TestFile" namespace="global">
<metrics methods="1" coveredmethods="0" conditionals="0" coveredconditionals="0" statements="1" coveredstatements="0" elements="2" coveredelements="0"/>
</class>
<line num="5" type="method" name="__construct" crap="1" count="0"/>
<line num="7" type="stmt" count="0"/>
</file>
</project>
</coverage>
XML;
}
/**
* @return \SimpleXMLElement
*/
protected function createNoSourceCloverXml()
{
$xml = $this->getNoSourceCloverXml();
return simplexml_load_string($xml);
}
/**
* @return JsonFile
*/
protected function collectJsonFile()
{
$xml = $this->createCloverXml();
$collector = new CloverXmlCoverageCollector();
return $collector->collect($xml, $this->srcDir);
}
/**
* @return JsonFile
*/
protected function collectJsonFileWithoutSourceFiles()
{
$xml = $this->createNoSourceCloverXml();
$collector = new CloverXmlCoverageCollector();
return $collector->collect($xml, $this->srcDir);
}
/**
* @param Configuration $config
*
* @return CiEnvVarsCollector
*/
protected function createCiEnvVarsCollector($config = null)
{
if ($config === null) {
$config = $this->createConfiguration();
}
return new CiEnvVarsCollector($config);
}
}
| mit |
ftomassetti/pyjslintwrapper | setup.py | 691 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A wrapper around JSLint, written in Python',
'author': 'Federico Tomassetti',
'url': 'https://github.com/ftomassetti/pyjslintwrapper',
'author_email': 'Federico Tomassetti',
'version': '0.1',
'install_requires': ['nose','pydiffparser'],
'packages': ['pyjslintwrapper'],
'scripts': [],
'name': 'pyjslintwrapper',
'classifiers': [
'Programming Language :: Python',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Development Status :: 3 - Alpha']
}
setup(**config) | mit |
loresoft/FluentRest | src/FluentRest/HeaderBuilder.cs | 10971 | using System;
using System.Net.Http;
using System.Net.Http.Headers;
namespace FluentRest
{
/// <summary>
/// Fluent header builder
/// </summary>
public class HeaderBuilder : HeaderBuilder<HeaderBuilder>
{
/// <summary>
/// Initializes a new instance of the <see cref="HeaderBuilder"/> class.
/// </summary>
/// <param name="requestMessage">The fluent HTTP request being built.</param>
public HeaderBuilder(HttpRequestMessage requestMessage) : base(requestMessage)
{
}
}
/// <summary>
/// Fluent header builder
/// </summary>
/// <typeparam name="TBuilder">The type of the builder.</typeparam>
public abstract class HeaderBuilder<TBuilder> : RequestBuilder<TBuilder>
where TBuilder : HeaderBuilder<TBuilder>
{
/// <summary>
/// Initializes a new instance of the <see cref="HeaderBuilder{TBuilder}"/> class.
/// </summary>
/// <param name="requestMessage">The fluent HTTP request being built.</param>
protected HeaderBuilder(HttpRequestMessage requestMessage) : base(requestMessage)
{
}
/// <summary>
/// Append the media-type to the Accept header for an HTTP request.
/// </summary>
/// <param name="mediaType">The media-type header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Accept(string mediaType, double? quality = null)
{
var header = quality.HasValue
? new MediaTypeWithQualityHeaderValue(mediaType, quality.Value)
: new MediaTypeWithQualityHeaderValue(mediaType);
RequestMessage.Headers.Accept.Add(header);
return this as TBuilder;
}
/// <summary>
/// Append the value to the Accept-Charset header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder AcceptCharset(string value, double? quality = null)
{
var header = quality.HasValue
? new StringWithQualityHeaderValue(value, quality.Value)
: new StringWithQualityHeaderValue(value);
RequestMessage.Headers.AcceptCharset.Add(header);
return this as TBuilder;
}
/// <summary>
/// Append the value to the Accept-Encoding header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder AcceptEncoding(string value, double? quality = null)
{
var header = quality.HasValue
? new StringWithQualityHeaderValue(value, quality.Value)
: new StringWithQualityHeaderValue(value);
RequestMessage.Headers.AcceptEncoding.Add(header);
return this as TBuilder;
}
/// <summary>
/// Append the value to the Accept-Language header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder AcceptLanguage(string value, double? quality = null)
{
var header = quality.HasValue
? new StringWithQualityHeaderValue(value, quality.Value)
: new StringWithQualityHeaderValue(value);
RequestMessage.Headers.AcceptLanguage.Add(header);
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Authorization header for an HTTP request.
/// </summary>
/// <param name="scheme">The scheme to use for authorization.</param>
/// <param name="parameter">The credentials containing the authentication information.</param>
/// <returns>A fluent header builder.</returns>
/// <exception cref="System.ArgumentNullException"></exception>
public TBuilder Authorization(string scheme, string parameter = null)
{
if (scheme == null)
throw new ArgumentNullException(nameof(scheme));
var header = new AuthenticationHeaderValue(scheme, parameter);
RequestMessage.Headers.Authorization = header;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Cache-Control header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <see langword="null"/></exception>
public TBuilder CacheControl(string value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var header = CacheControlHeaderValue.Parse(value);
RequestMessage.Headers.CacheControl = header;
return this as TBuilder;
}
/// <summary>
/// Append the value of the Expect header for an HTTP request.
/// </summary>
/// <param name="name">The header name.</param>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Expect(string name, string value = null)
{
var header = new NameValueWithParametersHeaderValue(name, value);
RequestMessage.Headers.Expect.Add(header);
return this as TBuilder;
}
/// <summary>
/// Sets the value of the From header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder From(string value)
{
RequestMessage.Headers.From = value;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Host header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Host(string value)
{
RequestMessage.Headers.Host = value;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the If-Modified-Since header for an HTTP request.
/// </summary>
/// <param name="modifiedDate">The modified date.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder IfModifiedSince(DateTimeOffset? modifiedDate)
{
RequestMessage.Headers.IfModifiedSince = modifiedDate;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the If-Unmodified-Since header for an HTTP request.
/// </summary>
/// <param name="modifiedDate">The modified date.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder IfUnmodifiedSince(DateTimeOffset? modifiedDate)
{
RequestMessage.Headers.IfUnmodifiedSince = modifiedDate;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Proxy-Authorization header for an HTTP request.
/// </summary>
/// <param name="scheme">The scheme to use for authorization.</param>
/// <param name="parameter">The credentials containing the authentication information.</param>
/// <returns>A fluent header builder.</returns>
/// <exception cref="ArgumentNullException"><paramref name="scheme"/> is <see langword="null"/></exception>
public TBuilder ProxyAuthorization(string scheme, string parameter = null)
{
if (scheme == null)
throw new ArgumentNullException(nameof(scheme));
var header = new AuthenticationHeaderValue(scheme, parameter);
RequestMessage.Headers.ProxyAuthorization = header;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Range header for an HTTP request.
/// </summary>
/// <param name="from">The position at which to start sending data.</param>
/// <param name="to">The position at which to stop sending data.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Range(long? from, long? to)
{
var header = new RangeHeaderValue(from, to);
RequestMessage.Headers.Range = header;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Referrer header for an HTTP request.
/// </summary>
/// <param name="uri">The header URI.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Referrer(Uri uri)
{
RequestMessage.Headers.Referrer = uri;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Referrer header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Referrer(string value)
{
if (string.IsNullOrEmpty(value))
return this as TBuilder;
var uri = new Uri(value);
RequestMessage.Headers.Referrer = uri;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the User-Agent header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder UserAgent(string value)
{
if (string.IsNullOrEmpty(value))
return this as TBuilder;
var header = ProductInfoHeaderValue.Parse(value);
RequestMessage.Headers.UserAgent.Add(header);
return this as TBuilder;
}
/// <summary>
/// Sets the value of the X-HTTP-Method-Override header for an HTTP request.
/// </summary>
/// <param name="method">The HTTP method.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder MethodOverride(HttpMethod method)
{
RequestMessage.Headers.Add(HttpRequestHeaders.MethodOverride, method.ToString());
return this as TBuilder;
}
}
} | mit |
techalien/carpool | public/controllers/signup.js | 849 | angular.module('carpooler')
.controller('SignupCtrl', function($scope, $alert, $auth) {
$scope.signup = function() {
$auth.signup({
displayName: $scope.displayName,
email: $scope.email,
password: $scope.password,
phoneNum:$scope.phoneNum
}).catch(function(response) {
if (typeof response.data.message === 'object') {
angular.forEach(response.data.message, function(message) {
$alert({
content: message[0],
animation: 'fadeZoomFadeDown',
type: 'info',
duration: 3
});
});
} else {
$alert({
content: response.data.message,
animation: 'fadeZoomFadeDown',
type: 'info',
duration: 3
});
}
});
};
});
| mit |
spapageo/ethmmyrss | src/main/java/com/spapageo/ethmmyrss/cli/RecreateTableCommand.java | 925 | package com.spapageo.ethmmyrss.cli;
import com.spapageo.ethmmyrss.ThmmyRssApplication;
import com.spapageo.ethmmyrss.ThmmyRssConfiguration;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import net.sourceforge.argparse4j.inf.Namespace;
public class RecreateTableCommand extends EnvironmentCommand<ThmmyRssConfiguration> {
private ThmmyRssApplication application;
public RecreateTableCommand(ThmmyRssApplication application,
String name, String description) {
super(application, name, description);
this.application = application;
}
@Override
protected void run(Environment env, Namespace namespace,
ThmmyRssConfiguration config) throws Exception {
application.getAnnouncementDAO().dropAnnouncementsTable();
application.getAnnouncementDAO().createAnnouncementsTable();
}
}
| mit |
studybreak/casio | lib/cql.js | 10784 | var _ = require('underscore')
// escape all single-quotes on strings...
function quote(s) {
if (typeof(s) === 'string') {
return "'" + s.replace(/'/g, "''") + "'";
} else if (s instanceof Array) {
return _.map(s, quote).join(', ');
}
return s;
}
var CQL = function(name){
this.name = name;
this._queries=[];
}
CQL.prototype = {
name:null,
_cmd:null,
_first:null,
_limit:null,
_reversed:null,
_cf:null,
_col:null,
_cols:null,
_consistency:null,
_where:null,
_set:null,
_ttl:null,
_timestamp:null,
_indexName:null,
_counter:null,
_range:null,
_queries:null,
}
CQL.prototype.first = function(num){
this._first = num;
return this;
}
CQL.prototype.limit = function(num){
this._limit = num;
return this;
}
CQL.prototype.reversed = function(b){
this._reversed = b;
return this;
}
CQL.prototype.from = function(cf){
this._cf = cf;
return this;
}
CQL.prototype.set = function(args){
this._set = args;
return this;
}
CQL.prototype.into = function(into){
this._into = _.map(into, quote);
return this;
}
CQL.prototype.values = function(values){
this._values = _.map(values, quote);
return this;
}
CQL.prototype.counter = function(args){
this._counter = args;
return this;
}
CQL.prototype.range = function(start, end){
start = quote(start);
end = quote(end);
this._cols = [[start, end].join('..')]
return this;
}
CQL.prototype.ttl = function(num){
this._ttl = num;
return this;
}
CQL.prototype.timestamp = function(num){
this._timestamp = num;
return this;
}
CQL.prototype.query = function(cql){
if (cql instanceof CQL){
this._queries.push(cql.statement());
} else if(cql.constructor===String){
this._queries.push(cql);
}
return this;
}
CQL.prototype.consistency = function(s){
/*
ZERO
ONE
QUORUM
ALL
DCQUORUM
DCQUORUMSYNC
*/
this._consistency = s;
return this;
}
/**
* Add a where clause to the query.
* Possible where clause cases. Allow these possible interpretations of s, args:
* str, obj -> clause.replace(args)
* obj -> (key = value) for each key in obj
* str -> str
*/
CQL.prototype.where = function(s, args) {
//
if (_.isString(s) && _.isObject(args)) {
for (var p in args) {
s = s.replace(new RegExp(':' + p), quote(args[p]));
}
this._where = s;
}
else if ((_.isObject(s) || _.isArray(s)) && !args) {
this._where = Object.keys(s).map(function (k) {
return Array.isArray(s[k]) && s[k].length ?
quote(k) + ' IN (' + _.map(s[k], quote).join(',') + ')' :
quote(k) + ' = ' + quote(s[k]);
}).join(' AND ');
}
else if (_.isString(s)) {
this._where = s;
}
return this;
}
CQL.prototype.select = function(cols){
this._cmd = 'SELECT';
if (_.isString(cols)){
cols = [cols];
}
this._cols = _.map(cols, function(v){
// don't quote *'s
if (v === '*') return v;
return quote(v);
});
return this;
}
CQL.prototype.update = function(cf){
this._cmd = 'UPDATE';
this._cf = cf;
return this;
}
CQL.prototype.insert = function(cf){
this._cmd = 'INSERT';
this._cf = cf;
return this;
}
CQL.prototype.delete = function(cols){
this.select(cols);
this._cmd = 'DELETE';
return this;
}
CQL.prototype.batch = function(c){
this._cmd = 'BEGIN BATCH';
if(c !== undefined){
this.consistency(c);
}
return this;
}
CQL.prototype.createIndex = function(cf, col){
this._cmd = 'CREATE INDEX';
this._indexName = cf + '_' + quote(col);
this._cf = cf;
this._col = quote(col);
return this;
}
CQL.prototype.count = function(){
return this;
}
CQL.prototype.statement = function(){
var cql = []
var cmd = this._cmd;
cql.push(cmd);
if (cmd === 'SELECT') {
// SELECT [FIRST N] [REVERSED] <SELECT EXPR> FROM
// <COLUMN FAMILY> [consistency <CONSISTENCY>] [WHERE <CLAUSE>] [LIMIT N];
if (this._first) {
cql.push('FIRST');
cql.push(this._first);
}
if (this._reversed) {
cql.push('REVERSED');
}
cql.push(this._cols.join(', '));
if (this._cf){
cql.push('FROM');
cql.push(this._cf)
}
if (this._consistency){
cql.push('USING CONSISTENCY');
cql.push(this._consistency)
}
if (this._where){
cql.push('WHERE');
cql.push(this._where)
}
if (this._limit){
cql.push('LIMIT');
cql.push(this._limit)
}
} else if (cmd === 'INSERT') {
// INSERT INTO (KEY, v1, v2, …) VALUES (, , ,) [consistency CONSISTENCY [AND TIMESTAMP ] [AND TTL]];
cql.push('INTO');
cql.push(this._cf);
cql.push('(' + this._into.join(', ') + ')');
cql.push('VALUES');
cql.push('(' + this._values.join(', ') + ')');
var using = [];
if (this._consistency){
using.push('CONSISTENCY ' + this._consistency);
}
// if (this._timestamp){
// using.push('TIMESTAMP ' + this._timestamp);
// }
if (this._ttl){
using.push('TTL ' + this._ttl);
}
if (using.length){
cql.push('USING')
cql.push(using.join(' AND '));
}
} else if (cmd === 'UPDATE') {
// UPDATE <COLUMN FAMILY>
// [consistency <CONSISTENCY> [AND TIMESTAMP <timestamp>] [AND TTL <timeToLive>]]
// SET name1 = value1, name2 = value2 WHERE KEY = keyname;
cql.push(this._cf);
var using = [];
if (this._consistency){
using.push('CONSISTENCY ' + this._consistency);
}
// if (this._timestamp){
// using.push('TIMESTAMP ' + this._timestamp);
// }
if (this._ttl){
using.push('TTL ' + this._ttl);
}
if (using.length){
cql.push('USING')
cql.push(using.join(' AND '));
}
cql.push('SET');
var values = [];
for (var p in this._set){
values.push(quote(p) + '=' + quote(this._set[p]));
}
for (var p in this._counter){
var num = this._counter[p];
var dir = (num > -1) ? '+' : ''; // ignore negative number dir
values.push(quote(p) + '=' + quote(p) + dir + num);
}
cql.push(values.join(', '))
if (this._where){
cql.push('WHERE');
cql.push(this._where)
}
} else if (cmd==='DELETE'){
// DELETE [COLUMNS] FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] WHERE KEY = keyname1
// DELETE [COLUMNS] FROM <COLUMN FAMILY> [consistency <CONSISTENCY>] WHERE KEY IN (keyname1, keyname2);
cql.push(this._cols.join(', '));
if (this._cf){
cql.push('FROM');
cql.push(this._cf)
}
var using = [];
if (this._consistency){
using.push('CONSISTENCY ' + this._consistency);
}
// if (this._timestamp){
// using.push('TIMESTAMP ' + this._timestamp);
// }
if (using.length){
cql.push('USING')
cql.push(using.join(' AND '));
}
if (this._where){
cql.push('WHERE');
cql.push(this._where)
}
} else if (cmd==='CREATE INDEX'){
// CREATE INDEX [index_name] ON <column_family> (column_name);
cql.push(this._indexName);
cql.push('ON');
cql.push(this._cf);
cql.push('(' + this._col + ')');
} else if (cmd==='BEGIN BATCH'){
var using = [];
if (this._consistency){
using.push('CONSISTENCY ' + this._consistency);
}
// if (this._timestamp){
// using.push('TIMESTAMP ' + this._timestamp);
// }
if (using.length){
cql[0] += ' USING ' + using.join(' AND ');
}
// cql[0] += '\n';
// BEGIN BATCH [consistency]
// UPDATE CF1 SET name1 = value1, name2 = value2 WHERE KEY = keyname1;
// UPDATE CF1 SET name3 = value3 WHERE KEY = keyname2;
// UPDATE CF2 SET name4 = value4, name5 = value5 WHERE KEY = keyname3;
// APPLY BATCH
cql.push(this._queries.join('; '));
cql.push('; APPLY BATCH;');
}
return cql.join(' ');
}
exports.CQL = CQL;
//////// SELECT
// var q = new CQL('selecting something');
// q.select(['first_name', 'birth_year'])
// q.from('users');
// q.first(10);
// q.reversed(true);
// q.limit(10);
// q.where('full_name = :full_name', {full_name:"Greg Melton's"})
// console.log(q.statement());
// var q = new CQL('selecting something');
// q.select();
// q.range('0', 'Z');
// q.from('users');
// q.where('key = :key', {key:1})
// console.log(q.statement());
//////// UPDATE
// var q = new CQL('update something');
// q.update('users');
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
// q.set({full_name:'Willard Hill'});
// q.where('KEY=:key', {key:1})
// console.log(q.statement());
// var q = new CQL('update something2');
// q.update('users');
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
// q.set({full_name:'Pitty da Fool'});
// q.where('KEY IN (:keys)', {keys:['1', '2', '3', '4']})
// console.log(q.statement());
//////// INSERT
// var q = new CQL('insert something');
// q.insert('users');
// q.into(['key', 'full_name', 'birth_year'])
// q.values(['2', 'Sam the Butcher', 2000])
// q.consistency('QUORUM');
// q.timestamp(123345);
// q.ttl(86400);
// console.log(q.statement());
//////// DELETE
// var q = new CQL('insert something');
// q.delete(['*']); // columns
// q.from('users');
// q.where('KEY=:key', {key:1})
// q.consistency('QUORUM');
// q.timestamp(123345);
// console.log(q.statement());
// var q = new CQL('delete something');
// q.delete(['first_name', 'last_name']); // columns
// q.from('users');
// q.where('KEY IN (:keys)', {keys:[1,2,3,4]})
// q.consistency('QUORUM');
// q.timestamp(123345);
// console.log(q.statement());
//////// CREATE INDEX
// var q = new CQL('create index');
// q.createIndex('users', 'birth_year');
// console.log(q.statement());
//////// BATCH
// var q1 = new CQL('q1');
// q1.select(['*'])
// q1.from('User')
// var q2 = new CQL('q2');
// q2.select(['*'])
// q2.from('Pet')
// var cql = new CQL('batch');
// cql.batch();
// cql.query(q1);
// cql.query(q2);
// console.log(cql.statement());
| mit |
eagletmt/procon | poj/2/2738.cc | 1027 | #include <cstdio>
#include <vector>
using namespace std;
int cache[1000][1000];
bool is_cached[1000][1000];
int solve(const vector<int>& v, int begin, int end)
{
if (begin > end) {
return 0;
} else if (is_cached[begin][end]) {
return cache[begin][end];
} else {
const int l = v[begin+1] >= v[end]
? solve(v, begin+2, end) + v[begin] - v[begin+1]
: (solve(v, begin+1, end-1) + v[begin] - v[end]);
const int r = v[begin] >= v[end-1]
? solve(v, begin+1, end-1) + v[end] - v[begin]
: (solve(v, begin, end-2) + v[end] - v[end-1]);
is_cached[begin][end] = true;
return cache[begin][end] = max(l, r);
}
}
int main()
{
int T = 0;
int N;
while (scanf("%d", &N) != EOF && N != 0) {
vector<int> v(N);
for (int i = 0; i < N; i++) {
scanf("%d", &v[i]);
}
for (int i = 0; i < N; i++) {
fill_n(is_cached[i], N, false);
}
printf("In game %d, the greedy strategy might lose by as many as %d points.\n", ++T, solve(v, 0, N-1));
}
return 0;
} | mit |
davidbarkhuizen/simagora | launcher.py | 1523 | import logging
from datetime import *
from time import clock
from decimal import Decimal
from simulator import Simulator
from strategy import Strategy
LOG_FILE_PATH = 'log/'
LOG_FILENAME = 'run_'
FORMAT = "%(message)s"
class Launcher(object):
def setup_logging(self):
t = datetime.now()
self.tstamp = '%d-%d-%d-%d-%d' % (t.year, t.month, t.day, t.hour, t.minute)
fname = LOG_FILE_PATH + LOG_FILENAME + self.tstamp + '.log'
logging.basicConfig(filename=fname,level=logging.INFO,format=FORMAT)
def configure(self, p):
print('constructing simulator')
self.sim = Simulator(p['ins'], p['strat'], p['start_date'], p['end_date'], p['open_bal'], self.tstamp)
def simulate(self):
print('running simulator')
start = clock()
self.sim.run()
end = clock()
dur_str = 'seconds = %f' % (end - start)
print(dur_str)
logging.info('sim time = ' + dur_str)
def report(self):
print('plotting')
start = clock()
self.sim.plot()
end = clock()
dur_str = 'seconds = %f' % (end - start)
print(dur_str)
logging.info('plot time = ' + dur_str)
def go(self, p):
self.setup_logging()
self.configure(p)
self.simulate()
self.report()
def main():
l = Launcher()
p = {
'start_date' : date(2008, 1, 1),
'end_date' : date(2010, 12, 30),
# equity/JPM
# equity_index/
'ins' : 'equity_index/^GSPC',
'strat' : 'movavg',
'open_bal' : Decimal('10000.00')
}
l.go(p)
if __name__ == '__main__':
main()
| mit |
IdleLands/AndroidFE | app/src/main/java/idle/land/app/logic/api/NotificationManager.java | 5644 | package idle.land.app.logic.api;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import idle.land.app.IdleLandApplication;
import idle.land.app.R;
import idle.land.app.logic.Model.Event;
import idle.land.app.logic.Preferences;
import idle.land.app.ui.MainActivity;
import java.util.Date;
import java.util.List;
public class NotificationManager {
public static final int EVENT_NOTIFICATION_ID = 31;
private static NotificationManager singelton;
Preferences mPreferences;
/**
* Time user opened the app the last time.
* Well be read out when new notifications are build to give a number of unseen events
* Must be updated when app opens
*/
Date lastTimeEventsSeen = new Date();
int lastNotificationCount = 0;
boolean isActive = true;
public static NotificationManager getInstance()
{
if(singelton == null)
singelton = new NotificationManager();
return singelton;
}
private NotificationManager() {
mPreferences = new Preferences();
}
/**
* returns an updated service status notification
* @return Notification to post
*/
public Notification buildServiceStatusNotification(Context context)
{
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent launchIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Intent stopIntent = new Intent(context, HeartbeatService.class);
stopIntent.putExtra(HeartbeatService.EXTRA_STOP, true);
PendingIntent stopPendingIntent = PendingIntent.getService(context, 1, stopIntent, 0);
Notification.Builder builder = new Notification.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(R.string.notification_no_news));
// Buttons only on sdk level >= 16
if(Build.VERSION.SDK_INT >= 16) {
builder.addAction(R.drawable.notification_close, context.getString(R.string.notification_action_stop), stopPendingIntent);
builder.addAction(R.drawable.notification_more, context.getString(R.string.notification_action_more), launchIntent);
}
builder.setContentIntent(launchIntent);
return builder.getNotification();
}
public void postEventNotification(Context context, @Nullable List<Event> events)
{
// get last unseen event if there are any
int totalUnseenEvents = 0;
Event lastUnseenEvent = null;
if(events != null)
{
for(Event e : events)
{
if(e.getCreatedAt().after(lastTimeEventsSeen)) {
totalUnseenEvents += 1;
if(lastUnseenEvent == null || e.getCreatedAt().after(lastUnseenEvent.getCreatedAt()))
lastUnseenEvent = e;
}
}
}
if(totalUnseenEvents > 0 && !isActive && lastNotificationCount < totalUnseenEvents)
{
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent launchPI = PendingIntent.getActivity(context, 2, notificationIntent, 0);
Intent dismissIntent = new Intent(context, HeartbeatService.class);
dismissIntent.putExtra(HeartbeatService.EXTRA_DISMISS_NOTIFICATION, true);
PendingIntent dismissPI = PendingIntent.getService(context, 3, dismissIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setStyle(new NotificationCompat.BigTextStyle().bigText(lastUnseenEvent.getMessage()))
.setSmallIcon(lastUnseenEvent.getType().getIconResId())
.setContentTitle(String.format("New Events! (%1$s)", totalUnseenEvents))
.setContentText(lastUnseenEvent.getMessage())
.setContentIntent(launchPI)
.addAction(R.drawable.notification_close, context.getString(R.string.notification_action_dismiss), dismissPI)
.addAction(R.drawable.notification_more, context.getString(R.string.notification_action_show), launchPI);
if(mPreferences.getBoolean(Preferences.Property.NOTIFICATION_PLAY_SOUND))
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Notification n = builder.build();
NotificationManagerCompat.from(context).notify(EVENT_NOTIFICATION_ID, n);
lastNotificationCount = totalUnseenEvents;
}
}
/**
* resets notifications
*/
public void resetNotifications(Context c)
{
NotificationManagerCompat.from(c).cancel(EVENT_NOTIFICATION_ID);
lastTimeEventsSeen = new Date();
lastNotificationCount = 0;
}
/**
* enables/disables showing of new events and updates last event time
* @param isActive
*/
public void setActive(boolean isActive)
{
this.isActive = isActive;
if(!isActive)
lastTimeEventsSeen = new Date();
else
((android.app.NotificationManager) IdleLandApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE)).cancel(EVENT_NOTIFICATION_ID);
}
}
| mit |
yangra/SoftUni | JavaFundamentals/JavaOOPBasic/EXAMS/exams/src/_12March2017Copy/entities/races/DragRace.java | 1638 | package _12March2017Copy.entities.races;
import _12March2017Copy.entities.cars.Car;
import _12March2017Copy.entities.races.Race;
import java.util.List;
import java.util.stream.Collectors;
public class DragRace extends Race {
public DragRace(int length, String route, int prizePool) {
super(length, route, prizePool);
}
@Override
public String start() {
if (this.getParticipants().size() < 1) {
throw new IllegalArgumentException("Cannot start the race with zero participants.");
}
List<Car> result = this.getParticipants().stream().sorted((c1, c2) -> {
int value1 = (c1.getHorsepower() / c1.getAcceleration());
int value2 = (c2.getHorsepower() / c2.getAcceleration());
return Integer.compare(value2, value1);
}).limit(3).collect(Collectors.toList());
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s - %d\n", this.getRoute(), this.getLength()));
int counter = 1;
for (Car car : result) {
sb.append(String.format("%d. %s %s %dPP - $%d", counter, car.getBrand(), car.getModel(),
(car.getHorsepower() / car.getAcceleration()),
counter == 1 ? this.getPrizePool() / 2 : counter == 2 ?
(this.getPrizePool() * 3) / 10 : counter == 3 ?
this.getPrizePool() / 5 : 0));
if (counter != 3&&!result.get(result.size()-1).equals(car)) {
sb.append(System.lineSeparator());
}
counter++;
}
return sb.toString();
}
}
| mit |
TheCamusean/DLRCev3 | scripts/Computer_vision_files/chessimages.py | 517 | #!/usr/bin/env python3
import cv2
import numpy as np
import sys
cap = cv2.VideoCapture(1)
flag=0
if len(sys.argv)>1:
number_of_photos=int(sys.argv[1])
else:
number_of_photos=10
image_name="Chessboard"
for i in range(number_of_photos):
while True:
ret,frame=cap.read()
cv2.imshow("camera",frame)
if cv2.waitKey(10) & 0xFF==32:
break
if cv2.waitKey(10) & 0xFF==27:
flag=1
break
if flag==1:
break
print("photo taken",i)
out_name="{}_{}.jpg".format(image_name,i)
cv2.imwrite(out_name,frame)
| mit |
devp-eu/tmcms-core | src/Orm/AbstractEntity.php | 2100 | <?php
declare(strict_types=1);
namespace TMCms\Orm;
use TMCms\DB\SQL;
use TMCms\DB\SqlDao;
use TMCms\Strings\Converter;
/**
* Class AbstractEntity
* @package TMCms\Orm
*/
abstract class AbstractEntity
{
const CLASS_RELATION_NAME_ENTITY = 'Entity'; // Represents one object with possible state saved in DB
const CLASS_RELATION_NAME_REPOSITORY = 'Repository'; // Represents a collection of objects and DB table with their states
protected $db_table = '';
protected $debug = false;
protected $translation_fields = [];
/**
* @var SqlDao
*/
protected $dao;
/**
* Return name in class or try to get from class name
*
* @return string
*/
public function getDbTableName(): string
{
// Name set in class
if ($this->db_table) {
return $this->db_table;
}
$db_table_from_class = mb_strtolower(Converter::fromCamelCase(str_replace([self::CLASS_RELATION_NAME_ENTITY, self::CLASS_RELATION_NAME_REPOSITORY], '', $this->getUnqualifiedShortClassName()))) . 's';
// Check DB in system tables
$this->db_table = 'cms_' . $db_table_from_class;
if (!SQL::getInstance()->tableExists($this->db_table)) {
// Or in module tables
$this->db_table = 'm_' . $db_table_from_class;
}
return $this->db_table;
}
/**
* @return string
*/
public function getUnqualifiedShortClassName(): string
{
return Converter::classWithNamespaceToUnqualifiedShort($this);
}
/**
* @return $this
*/
public function enableDebug()
{
$this->debug = true;
return $this;
}
/**
* @param mixed $data
*/
protected function debug($data = NULL)
{
if (!$this->debug) {
return;
}
if ($data === NULL) {
$data = $this;
}
dump($data);
}
/**
* @param SqlDao $dao
* @return $this
*/
public function setSqlDaoObject($dao) {
$this->dao = $dao;
return $this;
}
}
| mit |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_07_01/operations/_network_interface_ip_configurations_operations.py | 9056 | # coding=utf-8
# --------------------------------------------------------------------------
# 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.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class NetworkInterfaceIPConfigurationsOperations(object):
"""NetworkInterfaceIPConfigurationsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_07_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
resource_group_name, # type: str
network_interface_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.NetworkInterfaceIPConfigurationListResult"]
"""Get all ip configurations in a network interface.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_interface_name: The name of the network interface.
:type network_interface_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either NetworkInterfaceIPConfigurationListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_07_01.models.NetworkInterfaceIPConfigurationListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkInterfaceIPConfigurationListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-07-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkInterfaceName': self._serialize.url("network_interface_name", network_interface_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('NetworkInterfaceIPConfigurationListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations'} # type: ignore
def get(
self,
resource_group_name, # type: str
network_interface_name, # type: str
ip_configuration_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.NetworkInterfaceIPConfiguration"
"""Gets the specified network interface ip configuration.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_interface_name: The name of the network interface.
:type network_interface_name: str
:param ip_configuration_name: The name of the ip configuration name.
:type ip_configuration_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: NetworkInterfaceIPConfiguration, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_07_01.models.NetworkInterfaceIPConfiguration
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkInterfaceIPConfiguration"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-07-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkInterfaceName': self._serialize.url("network_interface_name", network_interface_name, 'str'),
'ipConfigurationName': self._serialize.url("ip_configuration_name", ip_configuration_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('NetworkInterfaceIPConfiguration', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/ipConfigurations/{ipConfigurationName}'} # type: ignore
| mit |
ralinc/ralin.net | db/schema.rb | 2361 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170530120112) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "articles", force: :cascade do |t|
t.string "title", null: false
t.text "content", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug", null: false
t.integer "status", default: 0, null: false
t.datetime "date", default: -> { "now()" }, null: false
t.index ["created_at"], name: "index_articles_on_created_at"
t.index ["slug"], name: "index_articles_on_slug", unique: true
end
create_table "taggings", force: :cascade do |t|
t.integer "article_id"
t.integer "tag_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["article_id"], name: "index_taggings_on_article_id"
t.index ["tag_id"], name: "index_taggings_on_tag_id"
end
create_table "tags", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["name"], name: "index_tags_on_name", unique: true
end
create_table "users", force: :cascade do |t|
t.string "email", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "encrypted_password", null: false
t.integer "failed_attempts", default: 0, null: false
t.datetime "locked_at"
t.index ["email"], name: "index_users_on_email", unique: true
end
add_foreign_key "taggings", "articles"
add_foreign_key "taggings", "tags"
end
| mit |
pikariop/todo | app/AppKernel.php | 1402 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
new OP\TodoAppBundle\OPTodoAppBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| mit |
bruz/bookshelf-delivery-example | spec/cli/features/add_book_spec.rb | 602 | require 'cli_features_helper'
describe 'POST /api/books' do
before do
BookRepository.clear
end
let(:book_title) { 'Confident Ruby' }
let(:book_author) { 'Avdi Grimm' }
it 'adds a new book' do
stdout, _stderr = cli_command('add', book_title, book_author)
stdout.must_match book_title
stdout.must_match book_author
book = BookRepository.first
book.title.must_equal book_title
book.author.must_equal book_author
end
it 'displays an error there is a missing parameter' do
_, stderr = cli_command('add', book_title)
stderr.must_match 'ERROR'
end
end
| mit |
AdenKejawen/erp | web/assets/app/store/Base.js | 157 | Ext.define("Com.GatotKaca.ERP.store.Base",{extend:"Ext.data.Store",autoLoad:false,autoSync:false,buffered:true,leadingBufferZone:LEADING,pageSize:PER_PAGE}); | mit |
fordham-css/ptp | make-keys.py | 293 | import os
print 'PIRATE TRADING PLATFORM uses the Robinhood retail investing service. Please enter your Robinhood credentials below.\n'
u = raw_input("Username: ")
p = raw_input("Password: ")
payload = "[['username','%s'],['password','%s']]" % (u,p)
os.system('echo "%s" > keys' % payload) | mit |
nlhkh/atomclinic | main.js | 1460 | 'use strict';
const app = require('app'); // Module to control application life.
const BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 960,
height: 640
});
// and load the index.html of the app.
mainWindow.loadUrl(`file://${__dirname}/index.html`);
// Open the DevTools.
if (process.env.NODE_ENV === 'development') {
mainWindow.openDevTools();
}
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
app.quit();
});
});
| mit |
anilpank/javascriptninja | oops.js | 688 | /**
Some objects defined by browser include
Document
Window - Global Object is the browser window itself.
Element
Event
Node
Comment
Console
Core Objects are objects defined by and built into the Javascript language itself.
Math
Object
String
Boolean
Array
Date
Number
All other objects are defined by coder as needed.
**/
'use strict';
var cat = {
name: 'fluffy',
color: 'white'
};
Object.defineProperty(cat,'name', {writable:false});
//cat.name='Nice';
console.log(Object.getOwnPropertyDescriptor(cat, 'name'));
for (var propertyName in cat) {
console.log(propertyName + ":" + cat[propertyName]);
}
console.log(Object.keys(cat));
console.log(JSON.stringify(cat)); | mit |
Murillo/Hackerrank-Algorithms | Algorithms/Strings/strong-password.py | 925 | # Strong Password
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/strong-password/problem
# Time complexity: O(n)
def minimumNumber(n, password):
total = 0
at_least = 6
numbers = list([i for i in "0123456789"])
lower_case = list([i for i in "abcdefghijklmnopqrstuvwxyz"])
upper_case = list([i for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"])
special_characters = list([i for i in "!@#$%^&*()-+"])
if not any(x in numbers for x in password):
total += 1
if not any(x in lower_case for x in password):
total += 1
if not any(x in upper_case for x in password):
total += 1
if not any(x in special_characters for x in password):
total += 1
rest = at_least - len(password)
total = rest if rest > 0 and rest >= total else total
return total
n = int(input().strip())
password = input().strip()
print(minimumNumber(n, password)) | mit |
platinumazure/eslint | lib/rules/semi-spacing.js | 8785 | /**
* @fileoverview Validates spacing before and after semicolon
* @author Mathias Schreck
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "layout",
docs: {
description: "enforce consistent spacing before and after semicolons",
recommended: false,
url: "https://eslint.org/docs/rules/semi-spacing"
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
before: {
type: "boolean",
default: false
},
after: {
type: "boolean",
default: true
}
},
additionalProperties: false
}
],
messages: {
unexpectedWhitespaceBefore: "Unexpected whitespace before semicolon.",
unexpectedWhitespaceAfter: "Unexpected whitespace after semicolon.",
missingWhitespaceBefore: "Missing whitespace before semicolon.",
missingWhitespaceAfter: "Missing whitespace after semicolon."
}
},
create(context) {
const config = context.options[0],
sourceCode = context.getSourceCode();
let requireSpaceBefore = false,
requireSpaceAfter = true;
if (typeof config === "object") {
requireSpaceBefore = config.before;
requireSpaceAfter = config.after;
}
/**
* Checks if a given token has leading whitespace.
* @param {Object} token The token to check.
* @returns {boolean} True if the given token has leading space, false if not.
*/
function hasLeadingSpace(token) {
const tokenBefore = sourceCode.getTokenBefore(token);
return tokenBefore && astUtils.isTokenOnSameLine(tokenBefore, token) && sourceCode.isSpaceBetweenTokens(tokenBefore, token);
}
/**
* Checks if a given token has trailing whitespace.
* @param {Object} token The token to check.
* @returns {boolean} True if the given token has trailing space, false if not.
*/
function hasTrailingSpace(token) {
const tokenAfter = sourceCode.getTokenAfter(token);
return tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter) && sourceCode.isSpaceBetweenTokens(token, tokenAfter);
}
/**
* Checks if the given token is the last token in its line.
* @param {Token} token The token to check.
* @returns {boolean} Whether or not the token is the last in its line.
*/
function isLastTokenInCurrentLine(token) {
const tokenAfter = sourceCode.getTokenAfter(token);
return !(tokenAfter && astUtils.isTokenOnSameLine(token, tokenAfter));
}
/**
* Checks if the given token is the first token in its line
* @param {Token} token The token to check.
* @returns {boolean} Whether or not the token is the first in its line.
*/
function isFirstTokenInCurrentLine(token) {
const tokenBefore = sourceCode.getTokenBefore(token);
return !(tokenBefore && astUtils.isTokenOnSameLine(token, tokenBefore));
}
/**
* Checks if the next token of a given token is a closing parenthesis.
* @param {Token} token The token to check.
* @returns {boolean} Whether or not the next token of a given token is a closing parenthesis.
*/
function isBeforeClosingParen(token) {
const nextToken = sourceCode.getTokenAfter(token);
return (nextToken && astUtils.isClosingBraceToken(nextToken) || astUtils.isClosingParenToken(nextToken));
}
/**
* Report location example :
*
* for unexpected space `before`
*
* var a = 'b' ;
* ^^^
*
* for unexpected space `after`
*
* var a = 'b'; c = 10;
* ^^
*
* Reports if the given token has invalid spacing.
* @param {Token} token The semicolon token to check.
* @param {ASTNode} node The corresponding node of the token.
* @returns {void}
*/
function checkSemicolonSpacing(token, node) {
if (astUtils.isSemicolonToken(token)) {
if (hasLeadingSpace(token)) {
if (!requireSpaceBefore) {
const tokenBefore = sourceCode.getTokenBefore(token);
const loc = {
start: tokenBefore.loc.end,
end: token.loc.start
};
context.report({
node,
loc,
messageId: "unexpectedWhitespaceBefore",
fix(fixer) {
return fixer.removeRange([tokenBefore.range[1], token.range[0]]);
}
});
}
} else {
if (requireSpaceBefore) {
const loc = token.loc;
context.report({
node,
loc,
messageId: "missingWhitespaceBefore",
fix(fixer) {
return fixer.insertTextBefore(token, " ");
}
});
}
}
if (!isFirstTokenInCurrentLine(token) && !isLastTokenInCurrentLine(token) && !isBeforeClosingParen(token)) {
if (hasTrailingSpace(token)) {
if (!requireSpaceAfter) {
const tokenAfter = sourceCode.getTokenAfter(token);
const loc = {
start: token.loc.end,
end: tokenAfter.loc.start
};
context.report({
node,
loc,
messageId: "unexpectedWhitespaceAfter",
fix(fixer) {
return fixer.removeRange([token.range[1], tokenAfter.range[0]]);
}
});
}
} else {
if (requireSpaceAfter) {
const loc = token.loc;
context.report({
node,
loc,
messageId: "missingWhitespaceAfter",
fix(fixer) {
return fixer.insertTextAfter(token, " ");
}
});
}
}
}
}
}
/**
* Checks the spacing of the semicolon with the assumption that the last token is the semicolon.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkNode(node) {
const token = sourceCode.getLastToken(node);
checkSemicolonSpacing(token, node);
}
return {
VariableDeclaration: checkNode,
ExpressionStatement: checkNode,
BreakStatement: checkNode,
ContinueStatement: checkNode,
DebuggerStatement: checkNode,
DoWhileStatement: checkNode,
ReturnStatement: checkNode,
ThrowStatement: checkNode,
ImportDeclaration: checkNode,
ExportNamedDeclaration: checkNode,
ExportAllDeclaration: checkNode,
ExportDefaultDeclaration: checkNode,
ForStatement(node) {
if (node.init) {
checkSemicolonSpacing(sourceCode.getTokenAfter(node.init), node);
}
if (node.test) {
checkSemicolonSpacing(sourceCode.getTokenAfter(node.test), node);
}
},
PropertyDefinition: checkNode
};
}
};
| mit |
picarresursix/libcnf | include/solver.hpp | 1516 | /**
* @name solver.hpp
* @author Leo "picarresursix" Perrin <[email protected]>
* @date Time-stamp: <2014-01-17 10:26:43 leo>
*
* @brief The header of the Solver class.
*/
#ifndef _CNF_SOLVER_H_
#define _CNF_SOLVER_H_
#include "libcnf.hpp"
namespace cnf {
/**
* A class providing an interface to use common SAT-solver
* (they all have the same CLI interface in theory).
*
* To solve a formula F, its content is flushed in a DIMACS file
* called inputName in current directory. Then, the cnf is solved and
* the corresponding DIMACS assignment is stored in file outputName
* from where it is retrieved and used to assign the variables in the
* set associated to the formula.
*/
class Solver
{
protected:
/** The name of the DIMACS file in which the cnf is stored. */
std::string inputName;
/** The name of the DIMACS file in which the assignment
* of the variables is stored. */
std::string outputName;
/** The command to call to launch the SAT-solver. */
std::string command;
public:
/** Initializes this instance. */
Solver(
std::string solverName,
std::initializer_list<std::string> options);
/** Solves the given Formula f. If it is satisfiable, returns
* true and assigns the variables in the VariableSet v
* accordingly. Otherwise, returns False. */
bool solve(Formula f, VariableSet * v);
};
} // closing namespace
#endif
| mit |
unusualcrow/redead_reloaded | gamemode/vgui/vgui_classpicker.lua | 1617 | local PANEL = {}
function PANEL:Init()
--self:SetTitle( "" )
--self:ShowCloseButton( false )
self:ChooseParent()
self.Items = {}
for k, v in pairs({CLASS_SCOUT, CLASS_COMMANDO, CLASS_SPECIALIST, CLASS_ENGINEER}) do
local desc = GAMEMODE.ClassDescriptions[k] or "TEH"
local logo = GAMEMODE.ClassLogos[k] or "brick/brick_model"
local button = vgui.Create("DImageButton", self)
button:SetImage(logo)
button:SetSize(100, 100)
button.OnMousePressed = function()
RunConsoleCommand("changeclass", k)
RunConsoleCommand("changeteam", TEAM_ARMY)
self:Remove()
end
button.ID = id
local label = vgui.Create("DLabel", self)
label:SetWrap(true)
label:SetText(desc)
label:SetFont("ItemDisplayFont")
label:SetSize(300, 100)
table.insert(self.Items, {button, label})
end
end
function PANEL:Think()
self.Dragging = false
end
function PANEL:ChooseParent()
end
function PANEL:GetPadding()
return 5
end
function PANEL:PerformLayout()
local x, y = self:GetPadding(), self:GetPadding() + 50
for k, v in pairs(self.Items) do
v[1]:SetPos(x, y)
v[2]:SetPos(x + 100 + self:GetPadding(), y)
y = y + 100 + self:GetPadding()
end
self:SizeToContents()
end
function PANEL:Paint()
draw.RoundedBox(4, 0, 0, self:GetWide(), self:GetTall(), Color(0, 0, 0, 255))
draw.RoundedBox(4, 1, 1, self:GetWide() - 2, self:GetTall() - 2, Color(150, 150, 150, 150))
--draw.SimpleText( "Class Menu", "ItemDisplayFont", self:GetWide() * 0.5, 10, Color( 255, 255, 255, 255 ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
end
derma.DefineControl("ClassPicker", "A class picker menu.", PANEL, "PanelBase")
| mit |
china20/MPFUI | trunk/suicore/src/System/Windows/HierarchicalItem.cpp | 1486 |
#include <Framework/Controls/HierarchicalItem.h>
namespace suic
{
ImplementRTTIOfClass(HierarchicalItem, NotifyPropChanged)
HierarchicalItem::HierarchicalItem()
: _size(0)
, _flag(0)
, _children(NULL)
{
}
HierarchicalItem::~HierarchicalItem()
{
if (NULL != _children)
{
_children->unref();
}
}
void HierarchicalItem::OnSetExpanded(bool val)
{
SetExpandedFlag(val);
}
ItemCollection* HierarchicalItem::GetChildren()
{
if (NULL == _children)
{
_children = new ObservableCollection();
_children->ref();
_children->CollectionChanged += NotifyCollChangedEventHandler(this, &HierarchicalItem::OnItemsChanged);
}
return _children;
}
void HierarchicalItem::HandleItemRemoved()
{
}
void HierarchicalItem::OnItemsChanged(NotifyCollChangedEventArg* e)
{
}
void HierarchicalItem::OnItemsChanged(Object* sender, NotifyCollChangedEventArg* e)
{
switch (e->GetAction())
{
case NotifyCollectionChangedAction::Reset:
case NotifyCollectionChangedAction::Remove:
HandleItemRemoved();
break;
case NotifyCollectionChangedAction::Add:
case NotifyCollectionChangedAction::Insert:
case NotifyCollectionChangedAction::Replace:
{
HierarchicalItem* pItem = RTTICast<HierarchicalItem>(e->GetNewItem());
if (NULL != pItem)
{
pItem->_parent = this;
}
}
break;
}
OnItemsChanged(e);
}
}
| mit |
pospanet/MagicMirror | MirrorUI/Properties/AssemblyInfo.cs | 1073 | 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("Magic Mirror")]
[assembly: AssemblyDescription("Magis Mirror UI")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pospa.NET")]
[assembly: AssemblyProduct("MirrorUI")]
[assembly: AssemblyCopyright("Copyright © Pospa.NET 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | mit |
ircmaxell/PHP-Datastructures | src/Ardent/SortedMap.php | 4477 | <?php
namespace Ardent;
use Ardent\Exception\EmptyException,
Ardent\Exception\KeyException,
Ardent\Exception\TypeException,
Ardent\Iterator\SortedMapIterator;
class SortedMap implements Map {
use StructureCollection;
private $avl;
/**
* @var callable
*/
private $comparator;
function __construct($comparator = NULL) {
$this->comparator = $comparator ?: [$this, 'compareStandard'];
$this->avl = new SplayTree([$this, 'compareKeys']);
}
function compareKeys(Pair $a, Pair $b) {
return call_user_func($this->comparator, $a->first, $b->first);
}
function compareStandard($a, $b) {
if ($a < $b) {
return -1;
} elseif ($b < $a) {
return 1;
} else {
return 0;
}
}
/**
* @return void
*/
function clear() {
$this->avl->clear();
}
/**
* @param mixed $item
* @param callable $callback
*
* @return bool
* @throws TypeException when $item is not the correct type.
*/
function containsItem($item, callable $callback = NULL) {
if ($callback === NULL) {
$callback = [$this, 'compareStandard'];
}
foreach ($this->avl as $pair) {
/**
* @var Pair $pair
*/
if (call_user_func($callback, $pair->second, $item) === 0) {
return TRUE;
}
}
return FALSE;
}
/**
* @return bool
*/
function isEmpty() {
return $this->avl->isEmpty();
}
/**
* @return mixed
* @throws EmptyException when the tree is empty
*/
function findFirst() {
return $this->avl->findFirst();
}
/**
* @return mixed
* @throws EmptyException when the tree is empty
*/
function findLast() {
return $this->avl->findLast();
}
/**
* @link http://php.net/manual/en/arrayaccess.offsetexists.php
*
* @param mixed $offset
*
* @return bool
*/
function offsetExists($offset) {
return $this->avl->containsItem(new Pair($offset, NULL));
}
/**
* @param mixed $offset
* @link http://php.net/manual/en/arrayaccess.offsetget.php
* @return mixed
* @throws KeyException
*/
function offsetGet($offset) {
if (!$this->offsetExists($offset)) {
throw new KeyException;
}
return $this->get($offset);
}
/**
* @link http://php.net/manual/en/arrayaccess.offsetset.php
*
* @param mixed $offset
* @param mixed $value
*
* @return void
*/
function offsetSet($offset, $value) {
$this->insert($offset, $value);
}
/**
* @link http://php.net/manual/en/arrayaccess.offsetunset.php
*
* @param mixed $offset
*
* @return void
*/
function offsetUnset($offset) {
$this->remove($offset);
}
/**
* @param $key
*
* @return mixed
* @throws TypeException when the $key is not the correct type.
* @throws KeyException when the $key is not the correct type.
*/
function get($key) {
if (!$this->offsetExists($key)) {
throw new KeyException;
}
/**
* @var Pair $pair
*/
$pair = $this->avl->get(new Pair($key, NULL));
return $pair->second;
}
/**
* Note that if the key is considered equal to an already existing key in
* the map that it's value will be replaced with the new one.
*
* @param $key
* @param mixed $value
*
* @return void
* @throws TypeException when the $key or value is not the correct type.
*/
function insert($key, $value) {
$this->avl->add(new Pair($key, $value));
}
/**
* @param $key
*
* @return mixed
* @throws TypeException when the $key is not the correct type.
*/
function remove($key) {
$this->avl->remove(new Pair($key, NULL));
}
/**
* @link http://php.net/manual/en/countable.count.php
* @return int
*/
function count() {
return $this->avl->count();
}
/**
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return SortedMapIterator
*/
function getIterator() {
return new SortedMapIterator($this->avl->getIterator(), $this->avl->count());
}
}
| mit |
Prick1/PBR | orthographic_camera.cpp | 1375 | #include "orthographic_camera.h"
OrthographicCamera::OrthographicCamera( void )
{}
OrthographicCamera::OrthographicCamera( const float min_x,
const float max_x,
const float min_y,
const float max_y,
const glm::ivec2 &resolution,
const glm::vec3 &position,
const glm::vec3 &up_vector,
const glm::vec3 &look_at ) :
Camera::Camera{ resolution,
position,
up_vector,
look_at },
min_x_{ min_x },
max_x_{ max_x },
min_y_{ min_y },
max_y_{ max_y }
{}
Ray OrthographicCamera::getWorldSpaceRay( const glm::vec2 &pixel_coord ) const
{
float width = max_x_ - min_x_;
float height = max_y_ - min_y_;
glm::vec3 origin{ pixel_coord[0] / static_cast< float >( resolution_[0] ) * width + min_x_,
-(pixel_coord[1] / static_cast< float >( resolution_[1] ) * height + min_y_),
0.0f };
return Ray{ onb_.getBasisMatrix() * origin + position_,
glm::normalize( onb_.getBasisMatrix() * glm::vec3{ 0.0f, 0.0f, -1.0f } ) };
}
| mit |
travis-ci/travis-core | spec/travis/services/find_caches_spec.rb | 2467 | require 'spec_helper'
describe Travis::Services::FindCaches do
include Support::ActiveRecord, Support::S3, Support::GCS
let(:user) { User.first || Factory(:user) }
let(:service) { described_class.new(user, params) }
let(:repo) { Factory(:repository, :owner_name => 'travis-ci', :name => 'travis-core') }
let(:cache_options) {{ s3: { bucket_name: '' , access_key_id: '', secret_access_key: ''} }}
let(:has_access) { true }
let(:result) { service.run }
subject { result }
before :each do
Travis.config.roles = {}
Travis.config.cache_options = cache_options
user.stubs(:permission?).returns(has_access)
end
describe 'given a repository_id' do
let(:params) {{ repository_id: repo.id }}
describe 'without any caches' do
it { should be == [] }
end
describe 'with caches' do
before do
s3_bucket << "#{repo.github_id}/master/cache--example1.tbz"
s3_bucket << "#{repo.github_id}/other/cache--example2.tbz"
s3_bucket << "#{repo.github_id.succ}/master/cache--example3.tbz"
end
its(:size) { should be == 2 }
describe 'the cache instances' do
subject { result.first }
its(:slug) { should be == 'cache--example1' }
its(:branch) { should be == 'master' }
its(:repository) { should be == repo }
its(:size) { should be == 0 }
end
describe 'with branch' do
let(:params) {{ repository_id: repo.id, branch: 'other' }}
its(:size) { should be == 1 }
end
describe 'with match' do
let(:params) {{ repository_id: repo.id, match: 'example1' }}
its(:size) { should be == 1 }
end
describe 'without access' do
let(:has_access) { false }
its(:size) { should be == 0 }
end
describe 'without s3 credentials' do
let(:cache_options) {{ }}
before { service.logger.expects(:warn).with("[services:find-caches] cache settings incomplete") }
it { should be == [] }
end
describe 'with multiple buckets' do
let(:cache_options) {[{ s3: { bucket_name: '', access_key_id: '', secret_access_key: '' } }, { s3: { bucket_name: '', access_key_id: '', secret_access_key: '' } }]}
its(:size) { should be == 4 }
end
end
context 'with GCS configuration' do
let(:cache_options) { { gcs: { bucket_name: '', json_key: '' } } }
its(:size) { should be == 0 }
end
end
end | mit |
heems/go-ipfs | p2p/net/mock/interface.go | 3187 | // Package mocknet provides a mock net.Network to test with.
//
// - a Mocknet has many inet.Networks
// - a Mocknet has many Links
// - a Link joins two inet.Networks
// - inet.Conns and inet.Streams are created by inet.Networks
package mocknet
import (
ic "github.com/ipfs/go-ipfs/p2p/crypto"
host "github.com/ipfs/go-ipfs/p2p/host"
inet "github.com/ipfs/go-ipfs/p2p/net"
peer "github.com/ipfs/go-ipfs/p2p/peer"
"io"
"time"
ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
)
type MeasuredNet interface {
GetBytesOut(p1, p2 peer.ID) int
}
type Mocknet interface {
// GenPeer generates a peer and its inet.Network in the Mocknet
GenPeer() (host.Host, error)
// AddPeer adds an existing peer. we need both a privkey and addr.
// ID is derived from PrivKey
AddPeer(ic.PrivKey, ma.Multiaddr) (host.Host, error)
// retrieve things (with randomized iteration order)
Peers() []peer.ID
Net(peer.ID) inet.Network
Nets() []inet.Network
Host(peer.ID) host.Host
Hosts() []host.Host
Links() LinkMap
LinksBetweenPeers(a, b peer.ID) []Link
LinksBetweenNets(a, b inet.Network) []Link
// Links are the **ability to connect**.
// think of Links as the physical medium.
// For p1 and p2 to connect, a link must exist between them.
// (this makes it possible to test dial failures, and
// things like relaying traffic)
LinkPeers(peer.ID, peer.ID) (Link, error)
LinkNets(inet.Network, inet.Network) (Link, error)
Unlink(Link) error
UnlinkPeers(peer.ID, peer.ID) error
UnlinkNets(inet.Network, inet.Network) error
// LinkDefaults are the default options that govern links
// if they do not have thier own option set.
SetLinkDefaults(LinkOptions)
LinkDefaults() LinkOptions
// Connections are the usual. Connecting means Dialing.
// **to succeed, peers must be linked beforehand**
ConnectPeers(peer.ID, peer.ID) (inet.Conn, error)
ConnectNets(inet.Network, inet.Network) (inet.Conn, error)
DisconnectPeers(peer.ID, peer.ID) error
DisconnectNets(inet.Network, inet.Network) error
LinkAll() error
}
// LinkOptions are used to change aspects of the links.
type LinkOptions struct {
Latency time.Duration
Bandwidth float64 // in bytes-per-second
// we can make these values distributions down the road.
}
// Link represents the **possibility** of a connection between
// two peers. Think of it like physical network links. Without
// them, the peers can try and try but they won't be able to
// connect. This allows constructing topologies where specific
// nodes cannot talk to each other directly. :)
type Link interface {
Networks() []inet.Network
Peers() []peer.ID
SetOptions(LinkOptions)
Options() LinkOptions
// Metrics() Metrics
}
// LinkMap is a 3D map to give us an easy way to track links.
// (wow, much map. so data structure. how compose. ahhh pointer)
type LinkMap map[string]map[string]map[Link]struct{}
// Printer lets you inspect things :)
type Printer interface {
// MocknetLinks shows the entire Mocknet's link table :)
MocknetLinks(mn Mocknet)
NetworkConns(ni inet.Network)
}
// PrinterTo returns a Printer ready to write to w.
func PrinterTo(w io.Writer) Printer {
return &printer{w}
}
| mit |
cmtj199337/zhiduoxing | src/api/api.js | 52 | let root = process.env.API_ROOT
export default root | mit |
markf78/dollarcoin | src/key.cpp | 19944 | // Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2013-2014 The Dollarcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "key.h"
#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/obj_mac.h>
#include <openssl/rand.h>
// anonymous namespace with local implementation code (OpenSSL interaction)
namespace {
// Generate a private key from just the secret parameter
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
{
int ok = 0;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
if (!eckey) return 0;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
pub_key = EC_POINT_new(group);
if (pub_key == NULL)
goto err;
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
goto err;
EC_KEY_set_private_key(eckey,priv_key);
EC_KEY_set_public_key(eckey,pub_key);
ok = 1;
err:
if (pub_key)
EC_POINT_free(pub_key);
if (ctx != NULL)
BN_CTX_free(ctx);
return(ok);
}
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
// recid selects which key is recovered
// if check is non-zero, additional checks are performed
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
{
if (!eckey) return 0;
int ret = 0;
BN_CTX *ctx = NULL;
BIGNUM *x = NULL;
BIGNUM *e = NULL;
BIGNUM *order = NULL;
BIGNUM *sor = NULL;
BIGNUM *eor = NULL;
BIGNUM *field = NULL;
EC_POINT *R = NULL;
EC_POINT *O = NULL;
EC_POINT *Q = NULL;
BIGNUM *rr = NULL;
BIGNUM *zero = NULL;
int n = 0;
int i = recid / 2;
const EC_GROUP *group = EC_KEY_get0_group(eckey);
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
BN_CTX_start(ctx);
order = BN_CTX_get(ctx);
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
x = BN_CTX_get(ctx);
if (!BN_copy(x, order)) { ret=-1; goto err; }
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
field = BN_CTX_get(ctx);
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
if (check)
{
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
}
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
n = EC_GROUP_get_degree(group);
e = BN_CTX_get(ctx);
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
zero = BN_CTX_get(ctx);
if (!BN_zero(zero)) { ret=-1; goto err; }
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
rr = BN_CTX_get(ctx);
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
sor = BN_CTX_get(ctx);
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
eor = BN_CTX_get(ctx);
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
ret = 1;
err:
if (ctx) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (R != NULL) EC_POINT_free(R);
if (O != NULL) EC_POINT_free(O);
if (Q != NULL) EC_POINT_free(Q);
return ret;
}
// RAII Wrapper around OpenSSL's EC_KEY
class CECKey {
private:
EC_KEY *pkey;
public:
CECKey() {
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
assert(pkey != NULL);
}
~CECKey() {
EC_KEY_free(pkey);
}
void GetSecretBytes(unsigned char vch[32]) const {
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
assert(bn);
int nBytes = BN_num_bytes(bn);
int n=BN_bn2bin(bn,&vch[32 - nBytes]);
assert(n == nBytes);
memset(vch, 0, 32 - nBytes);
}
void SetSecretBytes(const unsigned char vch[32]) {
bool ret;
BIGNUM bn;
BN_init(&bn);
ret = BN_bin2bn(vch, 32, &bn);
assert(ret);
ret = EC_KEY_regenerate_key(pkey, &bn);
assert(ret);
BN_clear_free(&bn);
}
void GetPrivKey(CPrivKey &privkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2d_ECPrivateKey(pkey, NULL);
assert(nSize);
privkey.resize(nSize);
unsigned char* pbegin = &privkey[0];
int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);
assert(nSize == nSize2);
}
bool SetPrivKey(const CPrivKey &privkey, bool fSkipCheck=false) {
const unsigned char* pbegin = &privkey[0];
if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {
if(fSkipCheck)
return true;
// d2i_ECPrivateKey returns true if parsing succeeds.
// This doesn't necessarily mean the key is valid.
if (EC_KEY_check_key(pkey))
return true;
}
return false;
}
void GetPubKey(CPubKey &pubkey, bool fCompressed) {
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
int nSize = i2o_ECPublicKey(pkey, NULL);
assert(nSize);
assert(nSize <= 65);
unsigned char c[65];
unsigned char *pbegin = c;
int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
assert(nSize == nSize2);
pubkey.Set(&c[0], &c[nSize]);
}
bool SetPubKey(const CPubKey &pubkey) {
const unsigned char* pbegin = pubkey.begin();
return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());
}
bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) {
vchSig.clear();
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig == NULL)
return false;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
const EC_GROUP *group = EC_KEY_get0_group(pkey);
BIGNUM *order = BN_CTX_get(ctx);
BIGNUM *halforder = BN_CTX_get(ctx);
EC_GROUP_get_order(group, order, ctx);
BN_rshift1(halforder, order);
if (BN_cmp(sig->s, halforder) > 0) {
// enforce low S values, by negating the value (modulo the order) if above order/2.
BN_sub(sig->s, order, sig->s);
}
BN_CTX_end(ctx);
BN_CTX_free(ctx);
unsigned int nSize = ECDSA_size(pkey);
vchSig.resize(nSize); // Make sure it is big enough
unsigned char *pos = &vchSig[0];
nSize = i2d_ECDSA_SIG(sig, &pos);
ECDSA_SIG_free(sig);
vchSig.resize(nSize); // Shrink to fit actual size
return true;
}
bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
// -1 = error, 0 = bad sig, 1 = good
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
return false;
return true;
}
bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) {
bool fOk = false;
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
if (sig==NULL)
return false;
memset(p64, 0, 64);
int nBitsR = BN_num_bits(sig->r);
int nBitsS = BN_num_bits(sig->s);
if (nBitsR <= 256 && nBitsS <= 256) {
CPubKey pubkey;
GetPubKey(pubkey, true);
for (int i=0; i<4; i++) {
CECKey keyRec;
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {
CPubKey pubkeyRec;
keyRec.GetPubKey(pubkeyRec, true);
if (pubkeyRec == pubkey) {
rec = i;
fOk = true;
break;
}
}
}
assert(fOk);
BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
}
ECDSA_SIG_free(sig);
return fOk;
}
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool Recover(const uint256 &hash, const unsigned char *p64, int rec)
{
if (rec<0 || rec>=3)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&p64[0], 32, sig->r);
BN_bin2bn(&p64[32], 32, sig->s);
bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
ECDSA_SIG_free(sig);
return ret;
}
static bool TweakSecret(unsigned char vchSecretOut[32], const unsigned char vchSecretIn[32], const unsigned char vchTweak[32])
{
bool ret = true;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM *bnSecret = BN_CTX_get(ctx);
BIGNUM *bnTweak = BN_CTX_get(ctx);
BIGNUM *bnOrder = BN_CTX_get(ctx);
EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1);
EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
BN_bin2bn(vchTweak, 32, bnTweak);
if (BN_cmp(bnTweak, bnOrder) >= 0)
ret = false; // extremely unlikely
BN_bin2bn(vchSecretIn, 32, bnSecret);
BN_add(bnSecret, bnSecret, bnTweak);
BN_nnmod(bnSecret, bnSecret, bnOrder, ctx);
if (BN_is_zero(bnSecret))
ret = false; // ridiculously unlikely
int nBits = BN_num_bits(bnSecret);
memset(vchSecretOut, 0, 32);
BN_bn2bin(bnSecret, &vchSecretOut[32-(nBits+7)/8]);
EC_GROUP_free(group);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ret;
}
bool TweakPublic(const unsigned char vchTweak[32]) {
bool ret = true;
BN_CTX *ctx = BN_CTX_new();
BN_CTX_start(ctx);
BIGNUM *bnTweak = BN_CTX_get(ctx);
BIGNUM *bnOrder = BN_CTX_get(ctx);
BIGNUM *bnOne = BN_CTX_get(ctx);
const EC_GROUP *group = EC_KEY_get0_group(pkey);
EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
BN_bin2bn(vchTweak, 32, bnTweak);
if (BN_cmp(bnTweak, bnOrder) >= 0)
ret = false; // extremely unlikely
EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
BN_one(bnOne);
EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
if (EC_POINT_is_at_infinity(group, point))
ret = false; // ridiculously unlikely
EC_KEY_set_public_key(pkey, point);
EC_POINT_free(point);
BN_CTX_end(ctx);
BN_CTX_free(ctx);
return ret;
}
};
}; // end of anonymous namespace
bool CKey::Check(const unsigned char *vch) {
// Do not convert to OpenSSL's data structures for range-checking keys,
// it's easy enough to do directly.
static const unsigned char vchMax[32] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
};
bool fIsZero = true;
for (int i=0; i<32 && fIsZero; i++)
if (vch[i] != 0)
fIsZero = false;
if (fIsZero)
return false;
for (int i=0; i<32; i++) {
if (vch[i] < vchMax[i])
return true;
if (vch[i] > vchMax[i])
return false;
}
return true;
}
void CKey::MakeNewKey(bool fCompressedIn) {
do {
RAND_bytes(vch, sizeof(vch));
} while (!Check(vch));
fValid = true;
fCompressed = fCompressedIn;
}
bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
CECKey key;
if (!key.SetPrivKey(privkey))
return false;
key.GetSecretBytes(vch);
fCompressed = fCompressedIn;
fValid = true;
return true;
}
CPrivKey CKey::GetPrivKey() const {
assert(fValid);
CECKey key;
key.SetSecretBytes(vch);
CPrivKey privkey;
key.GetPrivKey(privkey, fCompressed);
return privkey;
}
CPubKey CKey::GetPubKey() const {
assert(fValid);
CECKey key;
key.SetSecretBytes(vch);
CPubKey pubkey;
key.GetPubKey(pubkey, fCompressed);
return pubkey;
}
bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
if (!fValid)
return false;
CECKey key;
key.SetSecretBytes(vch);
return key.Sign(hash, vchSig);
}
bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
if (!fValid)
return false;
CECKey key;
key.SetSecretBytes(vch);
vchSig.resize(65);
int rec = -1;
if (!key.SignCompact(hash, &vchSig[1], rec))
return false;
assert(rec != -1);
vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
return true;
}
bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {
CECKey key;
if (!key.SetPrivKey(privkey, fSkipCheck))
return false;
key.GetSecretBytes(vch);
fCompressed = vchPubKey.IsCompressed();
fValid = true;
if (fSkipCheck)
return true;
if (GetPubKey() != vchPubKey)
return false;
return true;
}
bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
if (!key.Verify(hash, vchSig))
return false;
return true;
}
bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
if (vchSig.size() != 65)
return false;
CECKey key;
if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
return false;
key.GetPubKey(*this, (vchSig[0] - 27) & 4);
return true;
}
bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
if (!IsValid())
return false;
if (vchSig.size() != 65)
return false;
CECKey key;
if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
return false;
CPubKey pubkeyRec;
key.GetPubKey(pubkeyRec, IsCompressed());
if (*this != pubkeyRec)
return false;
return true;
}
bool CPubKey::IsFullyValid() const {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
return true;
}
bool CPubKey::Decompress() {
if (!IsValid())
return false;
CECKey key;
if (!key.SetPubKey(*this))
return false;
key.GetPubKey(*this, false);
return true;
}
void static BIP32Hash(const unsigned char chainCode[32], unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]) {
unsigned char num[4];
num[0] = (nChild >> 24) & 0xFF;
num[1] = (nChild >> 16) & 0xFF;
num[2] = (nChild >> 8) & 0xFF;
num[3] = (nChild >> 0) & 0xFF;
HMAC_SHA512_CTX ctx;
HMAC_SHA512_Init(&ctx, chainCode, 32);
HMAC_SHA512_Update(&ctx, &header, 1);
HMAC_SHA512_Update(&ctx, data, 32);
HMAC_SHA512_Update(&ctx, num, 4);
HMAC_SHA512_Final(output, &ctx);
}
bool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
assert(IsValid());
assert(IsCompressed());
unsigned char out[64];
LockObject(out);
if ((nChild >> 31) == 0) {
CPubKey pubkey = GetPubKey();
assert(pubkey.begin() + 33 == pubkey.end());
BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);
} else {
assert(begin() + 32 == end());
BIP32Hash(cc, nChild, 0, begin(), out);
}
memcpy(ccChild, out+32, 32);
bool ret = CECKey::TweakSecret((unsigned char*)keyChild.begin(), begin(), out);
UnlockObject(out);
keyChild.fCompressed = true;
keyChild.fValid = ret;
return ret;
}
bool CPubKey::Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
assert(IsValid());
assert((nChild >> 31) == 0);
assert(begin() + 33 == end());
unsigned char out[64];
BIP32Hash(cc, nChild, *begin(), begin()+1, out);
memcpy(ccChild, out+32, 32);
CECKey key;
bool ret = key.SetPubKey(*this);
ret &= key.TweakPublic(out);
key.GetPubKey(pubkeyChild, true);
return ret;
}
bool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = key.GetPubKey().GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = nChild;
return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);
}
void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
static const char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
HMAC_SHA512_CTX ctx;
HMAC_SHA512_Init(&ctx, hashkey, sizeof(hashkey));
HMAC_SHA512_Update(&ctx, seed, nSeedLen);
unsigned char out[64];
LockObject(out);
HMAC_SHA512_Final(out, &ctx);
key.Set(&out[0], &out[32], true);
memcpy(vchChainCode, &out[32], 32);
UnlockObject(out);
nDepth = 0;
nChild = 0;
memset(vchFingerprint, 0, sizeof(vchFingerprint));
}
CExtPubKey CExtKey::Neuter() const {
CExtPubKey ret;
ret.nDepth = nDepth;
memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
ret.nChild = nChild;
ret.pubkey = key.GetPubKey();
memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);
return ret;
}
void CExtKey::Encode(unsigned char code[74]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
memcpy(code+9, vchChainCode, 32);
code[41] = 0;
assert(key.size() == 32);
memcpy(code+42, key.begin(), 32);
}
void CExtKey::Decode(const unsigned char code[74]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(vchChainCode, code+9, 32);
key.Set(code+42, code+74, true);
}
void CExtPubKey::Encode(unsigned char code[74]) const {
code[0] = nDepth;
memcpy(code+1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
memcpy(code+9, vchChainCode, 32);
assert(pubkey.size() == 33);
memcpy(code+41, pubkey.begin(), 33);
}
void CExtPubKey::Decode(const unsigned char code[74]) {
nDepth = code[0];
memcpy(vchFingerprint, code+1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(vchChainCode, code+9, 32);
pubkey.Set(code+41, code+74);
}
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = pubkey.GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = nChild;
return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode);
}
| mit |
raoulvdberge/refinedstorage | src/main/java/com/refinedmods/refinedstorage/integration/jei/IngredientTracker.java | 4513 | package com.refinedmods.refinedstorage.integration.jei;
import com.refinedmods.refinedstorage.api.autocrafting.ICraftingPattern;
import com.refinedmods.refinedstorage.api.autocrafting.ICraftingPatternProvider;
import com.refinedmods.refinedstorage.api.util.IComparer;
import com.refinedmods.refinedstorage.apiimpl.API;
import com.refinedmods.refinedstorage.item.PatternItem;
import com.refinedmods.refinedstorage.screen.grid.stack.IGridStack;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.gui.ingredient.IGuiIngredient;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nullable;
import java.util.*;
public class IngredientTracker {
private final List<Ingredient> ingredients = new ArrayList<>();
private final Map<ResourceLocation, Integer> storedItems = new HashMap<>();
private boolean doTransfer;
public IngredientTracker(IRecipeLayout recipeLayout, boolean doTransfer) {
for (IGuiIngredient<ItemStack> guiIngredient : recipeLayout.getItemStacks().getGuiIngredients().values()) {
if (guiIngredient.isInput() && !guiIngredient.getAllIngredients().isEmpty()) {
ingredients.add(new Ingredient(guiIngredient));
}
}
this.doTransfer = doTransfer;
}
public Collection<Ingredient> getIngredients() {
return ingredients;
}
public void addAvailableStack(ItemStack stack, @Nullable IGridStack gridStack) {
int available = stack.getCount();
if (doTransfer) {
if (stack.getItem() instanceof ICraftingPatternProvider) {
ICraftingPattern pattern = PatternItem.fromCache(Minecraft.getInstance().level, stack);
if (pattern.isValid()) {
for (ItemStack outputStack : pattern.getOutputs()) {
storedItems.merge(outputStack.getItem().getRegistryName(), outputStack.getCount(), Integer::sum);
}
}
} else {
storedItems.merge(stack.getItem().getRegistryName(), available, Integer::sum);
}
}
for (Ingredient ingredient : ingredients) {
if (available == 0) {
return;
}
Optional<ItemStack> match = ingredient
.getGuiIngredient()
.getAllIngredients()
.stream()
.filter(s -> API.instance().getComparer().isEqual(stack, s, IComparer.COMPARE_NBT))
.findFirst();
if (match.isPresent()) {
// Craftables and non-craftables are 2 different gridstacks
// As such we need to ignore craftable stacks as they are not actual items
if (gridStack != null && gridStack.isCraftable()) {
ingredient.setCraftStackId(gridStack.getId());
} else if (!ingredient.isAvailable()) {
int needed = ingredient.getMissingAmount();
int used = Math.min(available, needed);
ingredient.fulfill(used);
available -= used;
}
}
}
}
public boolean hasMissing() {
return ingredients.stream().anyMatch(ingredient -> !ingredient.isAvailable());
}
public boolean hasMissingButAutocraftingAvailable() {
return ingredients.stream().anyMatch(ingredient -> !ingredient.isAvailable() && ingredient.isCraftable());
}
public boolean isAutocraftingAvailable() {
return ingredients.stream().anyMatch(Ingredient::isCraftable);
}
public Map<UUID, Integer> createCraftingRequests() {
Map<UUID, Integer> toRequest = new HashMap<>();
for (Ingredient ingredient : ingredients) {
if (!ingredient.isAvailable() && ingredient.isCraftable()) {
toRequest.merge(ingredient.getCraftStackId(), ingredient.getMissingAmount(), Integer::sum);
}
}
return toRequest;
}
public ItemStack findBestMatch(List<ItemStack> list) {
ItemStack stack = ItemStack.EMPTY;
int count = 0;
for (ItemStack itemStack : list) {
Integer stored = storedItems.get(itemStack.getItem().getRegistryName());
if (stored != null && stored > count) {
stack = itemStack;
count = stored;
}
}
return stack;
}
}
| mit |
XanderDwyl/bjssystem | app/views/layouts/main.blade.php | 5589 | <!DOCTYPE html>
@yield( 'head_wrapper' )
<head>
<meta charset="utf-8">
<title>BJS MotoShop</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="We sell motorcycle parts while we modified to works for your needs.">
<meta name="author" content="BJS MotoShop">
{{ HTML::style( 'packages/bootstrap/dist/css/bootstrap.css' ) }}
{{ HTML::style( 'packages/fontawesome/css/font-awesome.css' ) }}
{{ HTML::style( 'bjsAssets/css/main.css' ) }}
{{ HTML::style( 'bjsAssets/css/plugins/date-picker/datepicker.css' ) }}
{{ HTML::style( 'packages/bootstrap-select/dist/css/bootstrap-select.css' ) }}
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/home">BJS MotoShop</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-left">
@if(Auth::check())
<li><a href="/dashboard">Dashboard</a></li>
<li><a href="/pos">POS System</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Accounting System <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="payroll">Payroll</a></li>
<li><a href="cashadvance">Cash Advance</a></li>
<li class="divider"></li>
<li><a href="employee">Add Employee</a></li>
<li><a href="salary">Add Salary</a></li>
</ul>
</li>
@endif
</ul>
<ul class="nav navbar-nav navbar-right">
@if(!Auth::check())
<li>{{ HTML::link('login', 'Login') }}</li>
@else
<li class="dropdown user-dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-user"></i> {{ Auth::user()->getAuthUserName() }} <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="#"><i class="fa fa-user"></i> Profile</a></li>
<li><a href="#"><i class="fa fa-envelope"></i> Inbox <span class="badge">7</span></a></li>
<li><a href="#"><i class="fa fa-gear"></i> Settings</a></li>
<li class="divider"></li>
<li><a href="auth/logout"><i class="fa fa-power-off"></i> Log Out</a></li>
</ul>
</li>
@endif
</ul>
</div>
</div>
</div>
<div class="container">
{{-- */$status='danger';/* --}}
@if ( !count($errors ) )
{{-- */$status=Session::get( 'status' );/* --}}
@endif
@if ( count($errors ) || count(Session::get( 'status' )) )
<div class="alert alert-{{ $status }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
@if ( count($errors) )
<span>{{ 'Sorry, I can\'t proceed with errors! This useful information is highly needed.' }}</span>
@else
<span>{{ Session::get( 'message' ) }}</span>
@endif
</div>
@endif
{{ $content }}
</div>
<div class="footer">
@yield( 'footer' )
</div>
@section( 'script_files' )
{{ HTML::script( 'bjsAssets/scripts/jquery-1.10.2.js' ) }}
{{ HTML::script( 'packages/bootstrap/dist/js/bootstrap.js' ) }}
{{ HTML::script( 'bjsAssets/scripts/plugins/date-picker/bootstrap-datepicker.js' ) }}
<!-- angular packages -->
{{ HTML::script( 'packages/angular/angular.js' ) }}
{{ HTML::script( 'packages/angular-sanitize/angular-sanitize.js' ) }}
{{ HTML::script( 'packages/angular-route/angular-route.js' ) }}
{{ HTML::script( 'packages/underscore/underscore.js' ) }}
{{ HTML::script( 'packages/moment/moment.js' ) }}
{{ HTML::script( 'packages/moment-range/lib/moment-range.js' ) }}
{{ HTML::script( 'packages/angular-moment/angular-moment.js' ) }}
{{ HTML::script( 'bjsAssets/scripts/bjsas/app.js' ) }}
{{ HTML::script( 'bjsAssets/scripts/bjsas/controllers.js' ) }}
{{ HTML::script( 'bjsAssets/scripts/bjsas/services.js' ) }}
{{ HTML::script( 'bjsAssets/scripts/bjsas/filters.js' ) }}
{{ HTML::script( 'bjsAssets/scripts/bjsas/directives.js' ) }}
{{ HTML::script( 'packages/bootstrap-select/dist/js/bootstrap-select.js' ) }}
@yield( 'footer_scripts' )
@show
</body>
<script type="text/javascript">
$(function () {
angular.module("bjsApp").constant("CSRF_TOKEN", '<?php echo csrf_token(); ?>');
var formatTwo = function ( ) {
return ( arguments[ 0 ] < 10 ) ? '0' + arguments[0] : arguments[0];
}
var today = new Date();
var yr = today.getFullYear() - 18;
var dt = today.getDate();
var mt = today.getMonth();
var legalAgeDate = formatTwo( mt ) + '/' + formatTwo( dt ) + '/' + yr;
var toDate = formatTwo( mt + 1 ) + '/' + formatTwo( dt ) + '/' + today.getFullYear();
$('#birthDate').attr( 'placeholder', legalAgeDate );
$('#date_released, #hiredDate').attr( 'placeholder', toDate );
$('.input-group.date').datepicker( {
todayHighlight : true,
todayBtn : true,
orientation : 'top left',
format : 'mm/dd/yyyy'
} );
$("[data-toggle='tooltip']").tooltip( 'show' );
$(".sp-employee").selectpicker({
'size' : 10
});
$('#payperiod').datepicker( { } );
});
</script>
</html>
| mit |
muan/deploying-with-now | index.js | 299 | var http = require('http')
const server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.write(`Hi, this works.\nSecret ENV var: ${process.env.secret_env_var}`)
res.end()
})
server.listen(3000, function() {
console.log('Server started.')
})
| mit |
tivac/modular-css | jest.config.js | 842 | "use strict";
module.exports = {
clearMocks : true,
resetMocks : true,
restoreMocks : true,
notify : true,
coveragePathIgnorePatterns : [
"/node_modules/",
"/parsers/",
"/packages/test-utils/",
],
watchPathIgnorePatterns : [
"/output/",
"/specimens/",
],
setupFilesAfterEnv : [
"<rootDir>/packages/test-utils/expect/toMatchDiffSnapshot.js",
"<rootDir>/packages/test-utils/expect/toMatchLogspySnapshot.js",
"<rootDir>/packages/test-utils/expect/toMatchRollupAssetSnapshot.js",
"<rootDir>/packages/test-utils/expect/toMatchRollupCodeSnapshot.js",
"<rootDir>/packages/test-utils/expect/toMatchRollupSnapshot.js",
],
snapshotSerializers : [
require.resolve("snapshot-diff/serializer.js"),
],
};
| mit |
Rediker-Software/doac | doac/exceptions/unsupported_response_type.py | 155 | from .base import UnsupportedResponseType
class ResponseTypeNotValid(UnsupportedResponseType):
reason = "The request type was malformed or invalid."
| mit |
twistedstream/FormsToTokenAccessAuthentication | src/Sample.Service/Controllers/HomeController.cs | 711 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TS.FormsToTokenAccessAuthentication.Sample.Service.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
| mit |
increments/circleci-coverage_reporter | lib/circleci/coverage_reporter/vcs/base.rb | 526 | module CircleCI
module CoverageReporter
module VCS
# @abstract Subclass and override {#create_comment} to implement a custom VCS client class.
class Base
# @param token [String]
def initialize(token)
@token = token
end
# @param body [String]
# @return [void]
def create_comment(body) # rubocop:disable Lint/UnusedMethodArgument
raise NotImplementedError
end
private
attr_reader :token
end
end
end
end
| mit |
jakubka/Huerate | Huerate.WebUI/Content/Scripts/KnockoutBindings.js | 1648 | /*
Huerate - Mobile System for Customer Feedback Collection
Master Thesis at BUT FIT (http://www.fit.vutbr.cz), 2013
Available at http://huerate.cz
Author: Bc. Jakub Kadlubiec, [email protected] or [email protected]
*/
ko.bindingHandlers.loadingWhen = {
init: function (element) {
var $element = $(element);
var currentPosition = $element.css("position");
var $loader = $("<div>").addClass("loader").hide();
//add the loader
$element.append($loader);
//make sure that we can absolutely position the loader against the original element
if (currentPosition == "auto" || currentPosition == "static") {
$element.css("position", "relative");
}
//center the loader
//$loader.css({
// position: "absolute",
// top: "50%",
// left: "50%",
// "margin-left": -($loader.width() / 2) + "px",
// "margin-top": -($loader.height() / 2) + "px"
//});
},
update: function (element, valueAccessor) {
var isLoading = ko.utils.unwrapObservable(valueAccessor());
var $element = $(element);
//var $childrenToHide = $element.children(":not(div.loader)");
var $loader = $element.children("div.loader");
if (isLoading) {
//$childrenToHide.css("visibility", "hidden").attr("disabled", "disabled");
$loader.show();
} else {
$loader.fadeOut("fast");
//$childrenToHide.css("visibility", "visible").removeAttr("disabled");
}
}
}; | mit |
kristiankime/web-education-games | test/com/artclod/mathml/MathMLDerivativeSpec.scala | 1931 | package com.artclod.mathml
import com.artclod.mathml.Match._
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import org.specs2.mutable._
import com.artclod.mathml.scalar._
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import scala.xml._
import play.api.test._
import play.api.test.Helpers._
import org.specs2.mutable._
import com.artclod.mathml.scalar._
import com.artclod.mathml.scalar.apply._
import com.artclod.mathml.scalar.apply.{ ApplyLn => ln, ApplyLog => log }
import com.artclod.mathml.scalar.apply.trig.{ ApplySin => sin, ApplyCot => cot, ApplyTan => tan, ApplySec => sec, ApplyCos => cos, ApplyCsc => csc }
import com.artclod.mathml.Match._
// LATER try out http://rlegendi.github.io/specs2-runner/ and remove RunWith
@RunWith(classOf[JUnitRunner])
class MathMLDerivativeSpec extends Specification {
"Checking symbolic differentiation and manual derivative " should {
"confirm ln(x)' = 1 / x" in {
(ln(x) dx) must beEqualTo(`1` / x)
}
// LATER try to simplify these
//
// "1 / ln(x)' = -1 / (x * log(x)^2)" in {
// ( (`1` / ln(x))ʹ ) must beEqualTo( `-1` / (x * (ln(x) ^ `2`)) )
// }
//
// "x / ln(x)' = (ln(x)-1) / (ln(x)^2)" in {
// (x / ln(x)ʹ) must beEqualTo((ln(x) - `1`) / (ln(x) ^ `2`))
// }
// <apply><times/><apply><times/><cn type="integer">4</cn><apply><power/><ci>x</ci><cn type="integer">3</cn></apply></apply><apply><power/><exponentiale/><ci>x</ci></apply></apply>
// "(4 * x ^ 3 * e ^ x)' = " in {
// val mathF = MathML(<apply><times/><apply><times/><cn type="integer">4</cn><apply><power/><ci>x</ci><cn type="integer">3</cn></apply></apply><apply><power/><exponentiale/><ci>x</ci></apply></apply>).get
// val f = ((`4` * (x ^ `3`)) * (e ^ x))
//
// System.err.println(f dx);
//
// f must beEqualTo(mathF)
//
// (f dx) must beEqualTo( Cn(4 * math.E) )
// }
}
} | mit |
tonylukasavage/vm-titanium | Gruntfile.js | 513 | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
ti_run: {
all: {
files: {
'tmp/all/Resources': ['test/*', 'vm-titanium.js', '__context.js',
'node_modules/should/should.js', 'node_modules/ti-mocha/ti-mocha.js']
}
}
},
clean: {
src: ['tmp']
}
});
// Load grunt plugins for modules
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-titanium');
// Register tasks
grunt.registerTask('default', ['clean', 'ti_run']);
};
| mit |
abduld/clreflect | extern/llvm/tools/clang/test/SemaCXX/address-of-temporary.cpp | 503 | // RUN: %clang_cc1 -fsyntax-only -Wno-error=address-of-temporary -verify %s
struct X {
X();
X(int);
X(int, int);
};
void f0() { (void)&X(); } // expected-warning{{taking the address of a temporary object}}
void f1() { (void)&X(1); } // expected-warning{{taking the address of a temporary object}}
void f2() { (void)&X(1, 2); } // expected-warning{{taking the address of a temporary object}}
void f3() { (void)&(X)1; } // expected-warning{{taking the address of a temporary object}}
| mit |
Lokukarawita/EpisodeInformer | EpisodeInformer.Data/DBEMainQuery.cs | 7799 | using EpisodeInformer.Data.Basics;
using EpisodeInformer.Data.Remoting;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
namespace EpisodeInformer.Data
{
public static class DBEMainQuery
{
public static List<DBEpisode> GetTodaysDownloads()
{
List<DBEpisode> list = new List<DBEpisode>();
try
{
OleDbCommand cmd = new OleDbCommand("exec GetTodaysDLs");
DataSet data = CommandExecuter.GetData(cmd);
cmd.Dispose();
if (data != null)
{
if (data.Tables.Count > 0 && data.Tables[0].Rows.Count > 0)
{
foreach (DataRow dataRow in (InternalDataCollectionBase)data.Tables[0].Rows)
{
DBEpisode episodes = DBMainQuery.GetEpisodes((int)dataRow["sID"], (int)dataRow["eID"]);
list.Add(episodes);
}
}
data.Dispose();
}
}
catch (Exception)
{
GC.Collect();
}
return list;
}
public static int GetTodaysDownloadCount()
{
int num = 0;
try
{
object scalerData = ClientSideRemoting.Executer.GetScalerData("exec GetTodayDLCount");
if (scalerData != null)
num = int.Parse(scalerData.ToString());
}
catch (Exception)
{
GC.Collect();
}
return num;
}
public static List<DBEpisode> GetTodaysDownloadsALL()
{
List<DBEpisode> list = new List<DBEpisode>();
try
{
DataSet data = ClientSideRemoting.Executer.GetData("exec GetTodaysDLsALL");
if (data != null)
{
if (data.Tables.Count > 0 && data.Tables[0].Rows.Count > 0)
{
foreach (DataRow dataRow in (InternalDataCollectionBase)data.Tables[0].Rows)
{
DBEpisode episodes = DBMainQuery.GetEpisodes((int)dataRow["sID"], (int)dataRow["eID"]);
list.Add(episodes);
}
}
data.Dispose();
}
}
catch (Exception)
{
GC.Collect();
}
return list;
}
public static List<DBEpisode> GetDownloadsByDay(DateTime date)
{
List<DBEpisode> list = new List<DBEpisode>();
try
{
DataSet data = ClientSideRemoting.Executer.GetData("exec GetDownloadsByDayForView '@1'", new object[1]
{
(object) date.ToShortDateString()
});
if (data != null)
{
if (data.Tables.Count > 0 && data.Tables[0].Rows.Count > 0)
{
foreach (DataRow dataRow in (InternalDataCollectionBase)data.Tables[0].Rows)
{
DBEpisode episodes = DBMainQuery.GetEpisodes((int)dataRow["sID"], (int)dataRow["eID"]);
list.Add(episodes);
}
}
data.Dispose();
}
}
catch (Exception)
{
GC.Collect();
}
return list;
}
public static List<DBEpisode> GetTodaysDownloadsForView()
{
List<DBEpisode> list = new List<DBEpisode>();
try
{
DataSet data = ClientSideRemoting.Executer.GetData("exec GetTodaysDLsForView");
if (data != null)
{
if (data.Tables.Count > 0 && data.Tables[0].Rows.Count > 0)
{
foreach (DataRow dataRow in (InternalDataCollectionBase)data.Tables[0].Rows)
{
DBEpisode episodes = DBMainQuery.GetEpisodes((int)dataRow["sID"], (int)dataRow["eID"]);
list.Add(episodes);
}
}
data.Dispose();
}
}
catch (Exception)
{
GC.Collect();
}
return list;
}
public static List<DBEpisode> GetTodaysDownloadsExCl()
{
List<DBEpisode> list = new List<DBEpisode>();
try
{
OleDbCommand cmd = new OleDbCommand("exec GetTodaysDLsExCl");
DataSet data = CommandExecuter.GetData(cmd);
cmd.Dispose();
if (data != null)
{
if (data.Tables.Count > 0 && data.Tables[0].Rows.Count > 0)
{
foreach (DataRow dataRow in (InternalDataCollectionBase)data.Tables[0].Rows)
{
DBEpisode episodes = DBMainQuery.GetEpisodes((int)dataRow["sID"], (int)dataRow["eID"]);
list.Add(episodes);
}
}
data.Dispose();
}
}
catch (Exception)
{
GC.Collect();
}
return list;
}
public static int GetTodaysDownloadsExClCount()
{
int num = 0;
try
{
object scalerData = ClientSideRemoting.Executer.GetScalerData("exec GetTodaysDLsExClCount");
if (scalerData != null)
num = int.Parse(scalerData.ToString());
}
catch (Exception)
{
GC.Collect();
}
return num;
}
public static int SeriesRowCount()
{
int num;
try
{
num = int.Parse(ClientSideRemoting.Executer.GetScalerData("SELECT COUNT(sID) FROM Series").ToString());
}
catch (Exception)
{
num = -1;
}
return num;
}
public static int EpisodeRowCount()
{
int num;
try
{
num = int.Parse(ClientSideRemoting.Executer.GetScalerData("SELECT COUNT(eID) FROM Episodes").ToString());
}
catch (Exception)
{
num = -1;
}
return num;
}
public static int DLSRowCount()
{
int num;
try
{
num = int.Parse(ClientSideRemoting.Executer.GetScalerData("SELECT COUNT(sID) FROM DownloadSettings").ToString());
}
catch (Exception)
{
num = -1;
}
return num;
}
public static bool ExistIgnored(int SeriesID, int EpisodeID)
{
try
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM IgnoredEpisodes WHERE sID=@s, eID=@e");
cmd.Parameters.AddWithValue("@s", (object)SeriesID);
cmd.Parameters.AddWithValue("@e", (object)EpisodeID);
DataSet data = CommandExecuter.GetData(cmd);
return data != null && data.Tables[0].Rows.Count > 0;
}
catch (Exception)
{
return false;
}
}
}
}
| mit |
ravendb/ravendb-nodejs-client | src/Mapping/Json/Conventions/index.ts | 1331 | import { CONSTANTS } from "../../../Constants";
import { getIgnoreKeyCaseTransformKeysFromDocumentMetadata } from "../Docs";
import { CasingConvention } from "../../../Utility/ObjectUtil";
import {
ObjectKeyCaseTransformStreamOptionsBase,
ObjectKeyCaseTransformStreamOptions
} from "../Streams/ObjectKeyCaseTransformStream";
export const DOCUMENT_LOAD_KEY_CASE_TRANSFORM_PROFILE: ObjectKeyCaseTransformStreamOptionsBase = {
ignorePaths: [ CONSTANTS.Documents.Metadata.IGNORE_CASE_TRANSFORM_REGEX ],
ignoreKeys: [/^@/],
paths: [
{
transform: "camel",
path: /@metadata\.@attachments/
}
]
};
export const MULTI_GET_KEY_CASE_TRANSFORM_PROFILE: ObjectKeyCaseTransformStreamOptionsBase = {
ignorePaths: [/^headers\./i]
};
export type ObjectKeyCaseTransformProfile =
"DOCUMENT_LOAD"
| "DOCUMENT_QUERY";
export function getObjectKeyCaseTransformProfile(
defaultTransform: CasingConvention, profile?: ObjectKeyCaseTransformProfile): ObjectKeyCaseTransformStreamOptions {
switch (profile) {
case "DOCUMENT_LOAD":
case "DOCUMENT_QUERY":
return Object.assign({ defaultTransform }, DOCUMENT_LOAD_KEY_CASE_TRANSFORM_PROFILE);
default:
return { defaultTransform };
}
}
| mit |
baccigalupi/unicycle | server.js | 329 | var buffet = require('buffet')(__dirname + '/site', {});
var port = process.env.PORT || 9000;
var http = require('http');
http.createServer(function (req, res) {
buffet(req, res, function next () {
buffet.notFound(req, res);
});
}).listen(port, function() {
console.log('static server running on port ' + port);
});
| mit |
libocca/occa | src/occa/internal/lang/expr/primitiveNode.cpp | 1072 | #include <occa/internal/lang/expr/primitiveNode.hpp>
namespace occa {
namespace lang {
primitiveNode::primitiveNode(token_t *token_,
primitive value_) :
exprNode(token_),
value(value_) {}
primitiveNode::primitiveNode(const primitiveNode &node) :
exprNode(node.token),
value(node.value) {}
primitiveNode::~primitiveNode() {}
udim_t primitiveNode::type() const {
return exprNodeType::primitive;
}
exprNode* primitiveNode::clone() const {
return new primitiveNode(token, value);
}
bool primitiveNode::canEvaluate() const {
return true;
}
primitive primitiveNode::evaluate() const {
return value;
}
void primitiveNode::print(printer &pout) const {
pout << value.toString();
}
void primitiveNode::debugPrint(const std::string &prefix) const {
printer pout(io::stderr);
io::stderr << prefix << "|\n"
<< prefix << "|---[";
pout << (*this);
io::stderr << "] (primitive)\n";
}
}
}
| mit |
wwdenis/wwa | samples/Marketplace/Marketplace.Web/app/models/StatusType.ts | 278 | // Copyright 2017 (c) [Denis Da Silva]. All rights reserved.
// See License.txt in the project root for license information.
/// <reference path="../_references.ts" />
module App.Models {
'use strict';
export class StatusType extends NamedModel {
}
}
| mit |
windbender/chpcadscraper | src/main/java/com/github/windbender/chpcadscraper/chpdata/Able.java | 191 | package com.github.windbender.chpcadscraper.chpdata;
import org.xml.sax.Attributes;
public interface Able {
void addChars(String chars);
void doAttributes(Attributes attributes);
}
| mit |
nix-rust/nix | test/sys/test_uio.rs | 8153 | use nix::sys::uio::*;
use nix::unistd::*;
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
use std::{cmp, iter};
use std::fs::{OpenOptions};
use std::os::unix::io::AsRawFd;
#[cfg(not(target_os = "redox"))]
use tempfile::tempfile;
use tempfile::tempdir;
#[test]
fn test_writev() {
let mut to_write = Vec::with_capacity(16 * 128);
for _ in 0..16 {
let s: String = thread_rng()
.sample_iter(&Alphanumeric)
.map(char::from)
.take(128)
.collect();
let b = s.as_bytes();
to_write.extend(b.iter().cloned());
}
// Allocate and fill iovecs
let mut iovecs = Vec::new();
let mut consumed = 0;
while consumed < to_write.len() {
let left = to_write.len() - consumed;
let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64..cmp::min(256, left)) };
let b = &to_write[consumed..consumed+slice_len];
iovecs.push(IoVec::from_slice(b));
consumed += slice_len;
}
let pipe_res = pipe();
assert!(pipe_res.is_ok());
let (reader, writer) = pipe_res.ok().unwrap();
// FileDesc will close its filedesc (reader).
let mut read_buf: Vec<u8> = iter::repeat(0u8).take(128 * 16).collect();
// Blocking io, should write all data.
let write_res = writev(writer, &iovecs);
// Successful write
assert!(write_res.is_ok());
let written = write_res.ok().unwrap();
// Check whether we written all data
assert_eq!(to_write.len(), written);
let read_res = read(reader, &mut read_buf[..]);
// Successful read
assert!(read_res.is_ok());
let read = read_res.ok().unwrap() as usize;
// Check we have read as much as we written
assert_eq!(read, written);
// Check equality of written and read data
assert_eq!(&to_write, &read_buf);
let close_res = close(writer);
assert!(close_res.is_ok());
let close_res = close(reader);
assert!(close_res.is_ok());
}
#[test]
#[cfg(not(target_os = "redox"))]
fn test_readv() {
let s:String = thread_rng()
.sample_iter(&Alphanumeric)
.map(char::from)
.take(128)
.collect();
let to_write = s.as_bytes().to_vec();
let mut storage = Vec::new();
let mut allocated = 0;
while allocated < to_write.len() {
let left = to_write.len() - allocated;
let vec_len = if left <= 64 { left } else { thread_rng().gen_range(64..cmp::min(256, left)) };
let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect();
storage.push(v);
allocated += vec_len;
}
let mut iovecs = Vec::with_capacity(storage.len());
for v in &mut storage {
iovecs.push(IoVec::from_mut_slice(&mut v[..]));
}
let pipe_res = pipe();
assert!(pipe_res.is_ok());
let (reader, writer) = pipe_res.ok().unwrap();
// Blocking io, should write all data.
let write_res = write(writer, &to_write);
// Successful write
assert!(write_res.is_ok());
let read_res = readv(reader, &mut iovecs[..]);
assert!(read_res.is_ok());
let read = read_res.ok().unwrap();
// Check whether we've read all data
assert_eq!(to_write.len(), read);
// Cccumulate data from iovecs
let mut read_buf = Vec::with_capacity(to_write.len());
for iovec in &iovecs {
read_buf.extend(iovec.as_slice().iter().cloned());
}
// Check whether iovecs contain all written data
assert_eq!(read_buf.len(), to_write.len());
// Check equality of written and read data
assert_eq!(&read_buf, &to_write);
let close_res = close(reader);
assert!(close_res.is_ok());
let close_res = close(writer);
assert!(close_res.is_ok());
}
#[test]
#[cfg(not(target_os = "redox"))]
fn test_pwrite() {
use std::io::Read;
let mut file = tempfile().unwrap();
let buf = [1u8;8];
assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8));
let mut file_content = Vec::new();
file.read_to_end(&mut file_content).unwrap();
let mut expected = vec![0u8;8];
expected.extend(vec![1;8]);
assert_eq!(file_content, expected);
}
#[test]
fn test_pread() {
use std::io::Write;
let tempdir = tempdir().unwrap();
let path = tempdir.path().join("pread_test_file");
let mut file = OpenOptions::new().write(true).read(true).create(true)
.truncate(true).open(path).unwrap();
let file_content: Vec<u8> = (0..64).collect();
file.write_all(&file_content).unwrap();
let mut buf = [0u8;16];
assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16));
let expected: Vec<_> = (16..32).collect();
assert_eq!(&buf[..], &expected[..]);
}
#[test]
#[cfg(not(target_os = "redox"))]
fn test_pwritev() {
use std::io::Read;
let to_write: Vec<u8> = (0..128).collect();
let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat();
let iovecs = [
IoVec::from_slice(&to_write[0..17]),
IoVec::from_slice(&to_write[17..64]),
IoVec::from_slice(&to_write[64..128]),
];
let tempdir = tempdir().unwrap();
// pwritev them into a temporary file
let path = tempdir.path().join("pwritev_test_file");
let mut file = OpenOptions::new().write(true).read(true).create(true)
.truncate(true).open(path).unwrap();
let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap();
assert_eq!(written, to_write.len());
// Read the data back and make sure it matches
let mut contents = Vec::new();
file.read_to_end(&mut contents).unwrap();
assert_eq!(contents, expected);
}
#[test]
#[cfg(not(target_os = "redox"))]
fn test_preadv() {
use std::io::Write;
let to_write: Vec<u8> = (0..200).collect();
let expected: Vec<u8> = (100..200).collect();
let tempdir = tempdir().unwrap();
let path = tempdir.path().join("preadv_test_file");
let mut file = OpenOptions::new().read(true).write(true).create(true)
.truncate(true).open(path).unwrap();
file.write_all(&to_write).unwrap();
let mut buffers: Vec<Vec<u8>> = vec![
vec![0; 24],
vec![0; 1],
vec![0; 75],
];
{
// Borrow the buffers into IoVecs and preadv into them
let iovecs: Vec<_> = buffers.iter_mut().map(
|buf| IoVec::from_mut_slice(&mut buf[..])).collect();
assert_eq!(Ok(100), preadv(file.as_raw_fd(), &iovecs, 100));
}
let all = buffers.concat();
assert_eq!(all, expected);
}
#[test]
#[cfg(all(target_os = "linux", not(target_env = "uclibc")))] // uclibc doesn't implement process_vm_readv
// qemu-user doesn't implement process_vm_readv/writev on most arches
#[cfg_attr(qemu, ignore)]
fn test_process_vm_readv() {
use nix::unistd::ForkResult::*;
use nix::sys::signal::*;
use nix::sys::wait::*;
use crate::*;
require_capability!("test_process_vm_readv", CAP_SYS_PTRACE);
let _m = crate::FORK_MTX.lock();
// Pre-allocate memory in the child, since allocation isn't safe
// post-fork (~= async-signal-safe)
let mut vector = vec![1u8, 2, 3, 4, 5];
let (r, w) = pipe().unwrap();
match unsafe{fork()}.expect("Error: Fork Failed") {
Parent { child } => {
close(w).unwrap();
// wait for child
read(r, &mut [0u8]).unwrap();
close(r).unwrap();
let ptr = vector.as_ptr() as usize;
let remote_iov = RemoteIoVec { base: ptr, len: 5 };
let mut buf = vec![0u8; 5];
let ret = process_vm_readv(child,
&[IoVec::from_mut_slice(&mut buf)],
&[remote_iov]);
kill(child, SIGTERM).unwrap();
waitpid(child, None).unwrap();
assert_eq!(Ok(5), ret);
assert_eq!(20u8, buf.iter().sum());
},
Child => {
let _ = close(r);
for i in &mut vector {
*i += 1;
}
let _ = write(w, b"\0");
let _ = close(w);
loop { let _ = pause(); }
},
}
}
| mit |
gporte/GestAssoc | GestAssoc/GestAssoc.Model/Models/Mapping/VerificationMap.cs | 1292 | using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace GestAssoc.Model.Models.Mapping
{
public class VerificationMap : EntityTypeConfiguration<Verification>
{
public VerificationMap()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
this.Property(t => t.Commentaire)
.HasMaxLength(4000);
// Table & Column Mappings
this.ToTable("Verifications");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.Commentaire).HasColumnName("Commentaire");
this.Property(t => t.StatutVerification).HasColumnName("StatutVerification");
this.Property(t => t.CampagneVerification_ID).HasColumnName("CampagneVerification_ID");
this.Property(t => t.Equipement_ID).HasColumnName("Equipement_ID");
// Relationships
this.HasOptional(t => t.CampagneVerification)
.WithMany(t => t.Verifications)
.HasForeignKey(d => d.CampagneVerification_ID);
this.HasOptional(t => t.Equipement)
.WithMany(t => t.Verifications)
.HasForeignKey(d => d.Equipement_ID);
}
}
}
| mit |
osorubeki-fujita/odpt_tokyo_metro | lib/tokyo_metro/factory/convert/patch/api/train_timetable/namboku_line_from_musashi_kosugi/info.rb | 206 | class TokyoMetro::Factory::Convert::Patch::Api::TrainTimetable::NambokuLineFromMusashiKosugi::Info < TokyoMetro::Factory::Convert::Common::Api::MetaClass::TrainInfos::NambokuLineFromMusashiKosugi::Info
end
| mit |
felix9064/python | Demo/fluent_python/poker_card.py | 1462 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 流畅的Python 第一章示例程序1-1
# 生成一副扑克牌
from collections import namedtuple
from random import choice
# namedtuple可以生成一个带名字的tuple
Card = namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
# 生成扑克牌从2到A的序列
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
# 生成扑克牌的花色序列
suits = 'spades diamonds clubs hearts'.split()
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
def __init__(self):
print(self.suits)
self._cards = [Card(rank, suit) for rank in self.ranks
for suit in self.suits]
def __len__(self):
return len(self._cards)
def __getitem__(self, item):
return self._cards[item]
@staticmethod
def spades_high(poker_card):
"""计算一张牌在整副牌中的位置,其中梅花2为最小,黑桃A为最大"""
rank_value = FrenchDeck.ranks.index(poker_card.rank)
return rank_value * len(FrenchDeck.suit_values) + FrenchDeck.suit_values[card.suit]
if __name__ == '__main__':
deck = FrenchDeck()
print(deck[51])
print(len(deck))
# random库的choice方法是从列表中随机抽取一个元素
for x in range(11):
print(choice(deck))
print('排序后的所有的牌为')
for card in sorted(deck, key=FrenchDeck.spades_high):
print(card)
| mit |
Neeraj-nitd/ZapAnalyzer | src/main/java/com/zapstitch/analyzer/base/AppUser.java | 2391 | package com.zapstitch.analyzer.base;
import java.io.Serializable;
import org.apache.commons.lang.StringUtils;
import com.zapstitch.analyzer.utils.OauthUtils;
/**
* @author Neeraj Nayal
* [email protected]
*/
public class AppUser implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
public AppUser() {
tokenCertified = false;
}
/**
* @param token
*/
public AppUser(String token) {
stateToken = token;
tokenCertified = false;
}
/**
*
*/
public void clear() {
tokenCertified = false;
username = null;
email = null;
}
private String refreshToken = StringUtils.EMPTY;
private String accessToken = StringUtils.EMPTY;
private boolean tokenCertified;
private String username = null;
private String email = null;
private String stateToken = null;
private int attempt = 0;
/**
* @return
*/
public boolean isTokenCertified() {
return tokenCertified;
}
/**
* @param tokenCertified
*/
public void setTokenCertified(boolean tokenCertified) {
this.tokenCertified = tokenCertified;
}
/**
* @return
*/
public int getAttempt() {
return attempt;
}
/**
* @param attempt
*/
public void setAttempt(int attempt) {
this.attempt = attempt;
}
/**
* @return
*/
public String getStateToken() {
return stateToken;
}
/**
* @param token
*/
public void setStateToken(String token) {
stateToken = token;
}
/**
* @return
*/
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return
*/
public String getEmail() {
return email;
}
/**
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return
*/
public String getAccessToken() {
return accessToken;
}
/**
* @param accessToken
*/
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
/**
* @return
*/
public String getRefreshToken() {
return refreshToken;
}
/**
* @param refreshToken
*/
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
/**
* @return
*/
public String buildLoginUrl() {
if (StringUtils.isNotBlank(stateToken)){
return OauthUtils.getLoginUrl(stateToken);
}else{
return Constants.VIEW_ERROR;
}
}
}
| mit |
Venkatakrishnan/art-api | routers/users/users.js | 525 | import express from 'express';
import {error, log} from '../../shared/logger';
import fs from 'fs';
export default (jsonfilepath) =>{
const router = express.Router();
//reads from mock json file but has to be hooked upto database
//Index call
router.get("/", async (req,res,next)=>{
try{
fs.readFile(jsonfilepath,'utf8', async(err, fileContents)=>{
res.send(fileContents);
});
}catch(err){
next(err);
}
});
return router;
} | mit |
twilio/twilio-csharp | src/Twilio/Rest/Trusthub/V1/SupportingDocumentTypeOptions.cs | 1841 | /// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Trusthub.V1
{
/// <summary>
/// Retrieve a list of all Supporting Document Types.
/// </summary>
public class ReadSupportingDocumentTypeOptions : ReadOptions<SupportingDocumentTypeResource>
{
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// Fetch a specific Supporting Document Type Instance.
/// </summary>
public class FetchSupportingDocumentTypeOptions : IOptions<SupportingDocumentTypeResource>
{
/// <summary>
/// The unique string that identifies the Supporting Document Type resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchSupportingDocumentTypeOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the Supporting Document Type resource </param>
public FetchSupportingDocumentTypeOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
} | mit |
bnkr/lrcon | examples/rcon_deferred_authorisation.cpp | 1425 | try {
rcon::host h("127.0.0.1", "27015");
rcon::connection conn(h);
const char *pass = "password";
size_t retries = 3;
rcon::auth_command::auth_t auth_value = rcon::auth_command::error;
do {
rcon::auth_command returned(conn, pass, rcon::auth_command::nocheck);
auth_value = returned.auth();
if (retries == 0) {
std::cerr << "Authorisation retries limit reached:\n" << returned.data() << std::endl;
goto error_finish;
}
else if (auth_value == rcon::auth_command::failed) {
std::cerr << "Authorisation was denied:\n" << returned.data() << std::endl;
break;
}
--retries;
}
while (auth_value == rcon::auth_command::error);
retries = 3;
while (retries--) {
rcon::command returned(conn, "status", rcon::command::nocheck);
if (! returned.auth_lost()) {
std::cout << returned.data() << std::endl;
break;
}
else {
std::cerr << "There was an error: " << returned.data() << std::endl;
}
}
error_finish:
}
catch (rcon::connection_error &e) {
std::cerr << "Unable to connect: " << e.what() << std::endl;
}
catch (rcon::proto_error &e) {
std::cerr << "There was an error in protocol: " << e.what() << std::endl;
}
catch (rcon::recv_error &e) {
std::cerr << e.what() << std::endl;
}
catch (rcon::send_error &e) {
std::cerr << e.what() << std::endl;
}
catch (rcon::error &e) {
std::cerr << e.what() << std::endl;
}
| mit |
lgollut/material-ui | packages/material-ui-icons/src/Looks6Rounded.js | 354 | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M11 15h2v-2h-2v2zm8-12H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 6h-3v2h2c1.1 0 2 .9 2 2v2c0 1.11-.9 2-2 2h-2c-1.1 0-2-.89-2-2V9c0-1.1.9-2 2-2h3c.55 0 1 .45 1 1s-.45 1-1 1z" />
, 'Looks6Rounded');
| mit |
giang-pham/carousell-plus | karma-test-shim.js | 2699 | /*global jasmine, __karma__, window*/
(function () {
// Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
// Cancel Karma's synchronous start,
// we call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function () { };
// SET THE RUNTIME APPLICATION ROOT HERE
var appRoot ='app'; // no trailing slash!
// RegExp for client application base path within karma (which always starts 'base\')
var karmaBase = '^\/base\/'; // RegEx string for base of karma folders
var appPackage = 'base/' + appRoot; //e.g., base/app
var appRootRe = new RegExp(karmaBase + appRoot + '\/');
var onlyAppFilesRe = new RegExp(karmaBase + appRoot + '\/(?!.*\.spec\.js$)([a-z0-9-_\.\/]+)\.js$');
var moduleNames = [];
// Configure systemjs packages to use the .js extension for imports from the app folder
var packages = {};
packages[appPackage] = {
defaultExtension: false,
format: 'register',
map: Object.keys(window.__karma__.files)
.filter(onlyAppFiles)
// Create local module name mapping to karma file path for app files
// with karma's fingerprint in query string, e.g.:
// './hero.service': '/base/app/hero.service.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
.reduce(function (pathsMapping, appPath) {
var moduleName = appPath.replace(appRootRe, './').replace(/\.js$/, '');
pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath];
return pathsMapping;
}, {})
}
System.config({ packages: packages });
// Configure Angular for the browser and
// with test versions of the platform providers
System.import('angular2/testing')
.then(function (testing) {
return System.import('angular2/platform/testing/browser')
.then(function (providers) {
testing.setBaseTestProviders(
providers.TEST_BROWSER_PLATFORM_PROVIDERS,
providers.TEST_BROWSER_APPLICATION_PROVIDERS
);
});
})
// Load all spec files
// (e.g. 'base/app/hero.service.spec.js')
.then(function () {
return Promise.all(
Object.keys(window.__karma__.files)
.filter(onlySpecFiles)
.map(function (moduleName) {
moduleNames.push(moduleName);
return System.import(moduleName);
}));
})
.then(success, fail);
////// Helpers //////
function onlyAppFiles(filePath) {
return onlyAppFilesRe.test(filePath);
}
function onlySpecFiles(filePath) {
return /\.spec\.js$/.test(filePath);
}
function success () {
console.log(
'Spec files loaded:\n ' +
moduleNames.join('\n ') +
'\nStarting Jasmine testrunner');
__karma__.start();
}
function fail(error) {
__karma__.error(error.stack || error);
}
})();
| mit |
mcMickJuice/fun-with-asts | babel/expensive-operation-logging/src/does-not-use-expensive-operation.js | 227 | const request = require('./request')
module.exports = function iDoNothing() {
//just references expensiveOperation, doesn't call it
//therefore this won't be modified
request.expensiveOperation;
const name = 'mike';
} | mit |
Swegrock/Dynamic-Splitscreen | Assets/Scripts/SplitScreen.cs | 6073 | using UnityEngine;
using System;
using System.Collections;
public class SplitScreen : MonoBehaviour {
/*Reference both the transforms of the two players on screen.
Necessary to find out their current positions.*/
public Transform player1;
public Transform player2;
//The distance at which the splitscreen will be activated.
public float splitDistance = 5;
//The color and width of the splitter which splits the two screens up.
public Color splitterColor;
public float splitterWidth;
//The two cameras, both of which are initalized/referenced in the start function.
private GameObject camera1;
private GameObject camera2;
//The two quads used to draw the second screen, both of which are initalized in the start function.
private GameObject split;
private GameObject splitter;
void Start () {
//Referencing camera1 and initalizing camera2.
camera1 = Camera.main.gameObject;
Camera c1 = camera1.GetComponent<Camera>();
camera2 = new GameObject("Generated Splitscreen Camera");
Camera c2 = camera2.AddComponent<Camera>();
// Ensure the second camera renders before the first one
c2.depth = c1.depth - 1;
//Setting up the culling mask of camera2 to ignore the layer "TransparentFX" as to avoid rendering the split and splitter on both cameras.
c2.cullingMask = ~(1 << LayerMask.NameToLayer("TransparentFX"));
//Setting up the splitter and initalizing the gameobject.
splitter = GameObject.CreatePrimitive (PrimitiveType.Quad);
splitter.transform.parent = gameObject.transform;
splitter.transform.localPosition = Vector3.forward;
splitter.transform.localScale = new Vector3 (2, splitterWidth/10, 1);
splitter.transform.localEulerAngles = Vector3.zero;
splitter.SetActive (false);
//Setting up the split and initalizing the gameobject.
split = GameObject.CreatePrimitive (PrimitiveType.Quad);
split.transform.parent = splitter.transform;
split.transform.localPosition = new Vector3(0, -(1 / (splitterWidth / 10)), 0.0001f); // Add a little bit of Z-distance to avoid clipping with splitter
split.transform.localScale = new Vector3 (1, 2/(splitterWidth/10), 1);
split.transform.localEulerAngles = Vector3.zero;
//Creates both temporary materials required to create the splitscreen.
Material tempMat = new Material (Shader.Find ("Unlit/Color"));
tempMat.color = splitterColor;
splitter.GetComponent<Renderer>().material = tempMat;
splitter.GetComponent<Renderer> ().sortingOrder = 2;
splitter.layer = LayerMask.NameToLayer ("TransparentFX");
Material tempMat2 = new Material (Shader.Find ("Mask/SplitScreen"));
split.GetComponent<Renderer>().material = tempMat2;
split.layer = LayerMask.NameToLayer ("TransparentFX");
}
void LateUpdate () {
//Gets the z axis distance between the two players and just the standard distance.
float zDistance = player1.position.z - player2.transform.position.z;
float distance = Vector3.Distance (player1.position, player2.transform.position);
//Sets the angle of the player up, depending on who's leading on the x axis.
float angle;
if (player1.transform.position.x <= player2.transform.position.x) {
angle = Mathf.Rad2Deg * Mathf.Acos (zDistance / distance);
} else {
angle = Mathf.Rad2Deg * Mathf.Asin (zDistance / distance) - 90;
}
//Rotates the splitter according to the new angle.
splitter.transform.localEulerAngles = new Vector3 (0, 0, angle);
//Gets the exact midpoint between the two players.
Vector3 midPoint = new Vector3 ((player1.position.x + player2.position.x) / 2, (player1.position.y + player2.position.y) / 2, (player1.position.z + player2.position.z) / 2);
//Waits for the two cameras to split and then calcuates a midpoint relevant to the difference in position between the two cameras.
if (distance > splitDistance) {
Vector3 offset = midPoint - player1.position;
offset.x = Mathf.Clamp(offset.x,-splitDistance/2,splitDistance/2);
offset.y = Mathf.Clamp(offset.y,-splitDistance/2,splitDistance/2);
offset.z = Mathf.Clamp(offset.z,-splitDistance/2,splitDistance/2);
midPoint = player1.position + offset;
Vector3 offset2 = midPoint - player2.position;
offset2.x = Mathf.Clamp(offset.x,-splitDistance/2,splitDistance/2);
offset2.y = Mathf.Clamp(offset.y,-splitDistance/2,splitDistance/2);
offset2.z = Mathf.Clamp(offset.z,-splitDistance/2,splitDistance/2);
Vector3 midPoint2 = player2.position - offset;
//Sets the splitter and camera to active and sets the second camera position as to avoid lerping continuity errors.
if (splitter.activeSelf == false) {
splitter.SetActive (true);
camera2.SetActive (true);
camera2.transform.position = camera1.transform.position;
camera2.transform.rotation = camera1.transform.rotation;
} else {
//Lerps the second cameras position and rotation to that of the second midpoint, so relative to the second player.
camera2.transform.position = Vector3.Lerp(camera2.transform.position,midPoint2 + new Vector3(0,6,-5),Time.deltaTime*5);
Quaternion newRot2 = Quaternion.LookRotation(midPoint2-camera2.transform.position);
camera2.transform.rotation = Quaternion.Lerp(camera2.transform.rotation, newRot2, Time.deltaTime*5);
}
} else {
//Deactivates the splitter and camera once the distance is less than the splitting distance (assuming it was at one point).
if (splitter.activeSelf)
splitter.SetActive (false);
camera2.SetActive (false);
}
/*Lerps the first cameras position and rotation to that of the second midpoint, so relative to the first player
or when both players are in view it lerps the camera to their midpoint.*/
camera1.transform.position = Vector3.Lerp(camera1.transform.position,midPoint + new Vector3(0,6,-5),Time.deltaTime*5);
Quaternion newRot = Quaternion.LookRotation(midPoint-camera1.transform.position);
camera1.transform.rotation = Quaternion.Lerp(camera1.transform.rotation, newRot, Time.deltaTime*5);
}
}
| mit |
Albeoris/Esthar | Esthar.Transform/Locations/Scripts/Bindings/AsmAbsoluteRequestBinding.cs | 1040 | namespace Esthar.Data.Transform
{
public sealed class AsmAbsoluteRequestBinding : AsmBinding
{
public readonly ushort TargetModuleIndex;
public readonly AsmValueSource TargetEventLabel;
public AsmAbsoluteRequestBinding(AsmSegment source, int sourceOffset, int targetModuleIndex, AsmValueSource targetEventLabel)
: base(AsmBindingType.AbsoluteRequest, source, sourceOffset)
{
TargetModuleIndex = (ushort)targetModuleIndex;
TargetEventLabel = targetEventLabel;
}
public override AsmSegment[] ResolveTargets()
{
int? eventLabel = TargetEventLabel.TryResolveValue();
if (eventLabel == null)
return null;
AsmSegment target = SourceSegment.Event.Module.ParentCollection.GetModuleByIndex(TargetModuleIndex)[(ushort)eventLabel].Segments[0];
return new[] { target };
}
public override bool? ResolveCondition()
{
return true;
}
}
} | mit |
tonygalmiche/is_plastigray | wizard/stock_transfer_details.py | 5997 | # -*- coding: utf-8 -*-
from openerp import models, fields, api
from openerp.tools.translate import _
from openerp.exceptions import Warning
import openerp.addons.decimal_precision as dp
import datetime
def _date_reception():
return datetime.date.today().strftime('%Y-%m-%d')
class stock_transfer_details(models.TransientModel):
_inherit = 'stock.transfer_details'
_description = 'Picking wizard'
is_purchase_order_id = fields.Many2one('purchase.order', 'Commande Fournisseur')
is_num_bl = fields.Char("N° BL fournisseur")
is_date_reception = fields.Date('Date de réception')
_defaults = {
'is_date_reception': lambda *a: _date_reception(),
}
@api.one
def do_detailed_transfer(self):
res = super(stock_transfer_details, self).do_detailed_transfer()
for obj in self:
obj.picking_id.is_num_bl = obj.is_num_bl
obj.picking_id.is_date_reception = obj.is_date_reception
if obj.picking_id.is_purchase_order_id:
for row in obj.item_ids:
if row.lot_id:
row.lot_id.is_lot_fournisseur=row.is_lot_fournisseur
return res
def default_get(self, cr, uid, fields, context=None):
if context is None: context = {}
picking_ids = context.get('active_ids', [])
picking_id, = picking_ids
picking = self.pool.get('stock.picking').browse(cr, uid, picking_id, context=context)
stock_product_lot_obj = self.pool.get('stock.production.lot')
res = super(stock_transfer_details, self).default_get(cr, uid, fields, context=context)
#** Permet de gérer les réceptions avec le même article ****************
picking_ids = context.get('active_ids', [])
active_model = context.get('active_model')
if not picking_ids or len(picking_ids) != 1:
return res
assert active_model in ('stock.picking'), 'Bad context propagation'
picking_id, = picking_ids
picking = self.pool.get('stock.picking').browse(cr, uid, picking_id, context=context)
items = []
packs = []
if not picking.pack_operation_ids:
picking.do_prepare_partial()
for op in picking.pack_operation_ids:
item = {
'packop_id': op.id,
'product_id': op.product_id.id,
'product_uom_id': op.product_uom_id.id,
'quantity': op.product_qty,
'package_id': op.package_id.id,
'lot_id': op.lot_id.id,
'is_lot_fournisseur':op.lot_id.is_lot_fournisseur,
'sourceloc_id': op.location_id.id,
'destinationloc_id': op.location_dest_id.id,
'result_package_id': op.result_package_id.id,
'date': op.date,
'owner_id': op.owner_id.id,
'name':op.move_id.name
}
if op.product_id:
items.append(item)
elif op.package_id:
packs.append(item)
res.update(item_ids=items)
res.update(packop_ids=packs)
#***********************************************************************
# #** Permet de créer un lot avec le même numéro que la réception ********
# if picking.is_purchase_order_id:
# res.update({'is_purchase_order_id': picking.is_purchase_order_id.id})
# item_data = res.get('item_ids',[])
# for item in item_data:
# if item.get('lot_id', False) == False:
# lot_id = stock_product_lot_obj.search(cr, uid, [('name','=', picking.name),('product_id','=', item.get('product_id'))], context=context)
# if lot_id: lot_id = lot_id[0]
# else:
# lot_id = stock_product_lot_obj.create(cr, uid, {
# 'name': picking.name,
# 'product_id': item.get('product_id'),
# }, context=context)
# if lot_id:
# item['lot_id']=lot_id
# #***********************************************************************
#** Créer lot avec le même numéro que la réception et la date devant ***
if picking.is_purchase_order_id:
res.update({'is_purchase_order_id': picking.is_purchase_order_id.id})
item_data = res.get('item_ids',[])
for item in item_data:
if item.get('lot_id', False) == False:
numlot=datetime.date.today().strftime('%y%m%d')+picking.name
lot_id = stock_product_lot_obj.search(cr, uid, [
('name','=', numlot),
('product_id','=', item.get('product_id'))
], context=context)
if lot_id: lot_id = lot_id[0]
else:
lot_id = stock_product_lot_obj.create(cr, uid, {
'name': numlot,
'product_id': item.get('product_id'),
}, context=context)
if lot_id:
item['lot_id']=lot_id
#***********************************************************************
return res
class stock_transfer_details_items(models.TransientModel):
_inherit = 'stock.transfer_details_items'
name = fields.Char('Description')
is_lot_fournisseur = fields.Char("Lot fournisseur / Date péremption")
is_produit_perissable = fields.Boolean("Produit périssable", related="product_id.is_produit_perissable", readonly=True)
is_ctrl_rcp = fields.Selection([('bloque','Produit bloqué')], "Contrôle réception", related='product_id.is_ctrl_rcp', readonly=True)
@api.multi
def produit_perissable_action(self):
print self
| mit |
PollubCafe/Project-X | src/main/web/systemjs.config.js | 1820 | /**
* System configuration for Angular samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'js/lib/@angular/core/bundles/core.umd.js',
'@angular/common': 'js/lib/@angular/common/bundles/common.umd.js',
'@angular/compiler': 'js/lib/@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'js/lib/@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'js/lib/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'js/lib/@angular/http/bundles/http.umd.js',
'@angular/router': 'js/lib/@angular/router/bundles/router.umd.js',
'@angular/forms': 'js/lib/@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'js/lib/rxjs',
'angular2-in-memory-web-api': 'js/lib/angular2-in-memory-web-api',
'moment': 'js/lib/moment.js',
'jquery': 'js/lib/jquery.js',
'symbol-observable': 'js/lib/symbol-observable',
'ng2-bootstrap/ng2-bootstrap': 'js/lib/ngx-bootstrap.umd.js'
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
'symbol-observable': {
main: './index.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
| mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.